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, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
29 ;; A grab-bag of basic Emacs commands not specifically related to some
30 ;; major mode or to file-handling.
34 (declare-function widget-convert
"wid-edit" (type &rest args
))
35 (declare-function shell-mode
"shell" ())
37 (defvar compilation-current-error
)
39 (defcustom idle-update-delay
0.5
40 "*Idle time delay before updating various things on the screen.
41 Various Emacs features that update auxiliary information when point moves
42 wait this many seconds after Emacs becomes idle before doing an update."
48 "Killing and yanking commands."
51 (defgroup paren-matching nil
52 "Highlight (un)matching of parens and expressions."
55 (defun get-next-valid-buffer (list &optional buffer visible-ok frame
)
56 "Search LIST for a valid buffer to display in FRAME.
57 Return nil when all buffers in LIST are undesirable for display,
58 otherwise return the first suitable buffer in LIST.
60 Buffers not visible in windows are preferred to visible buffers,
61 unless VISIBLE-OK is non-nil.
62 If the optional argument FRAME is nil, it defaults to the selected frame.
63 If BUFFER is non-nil, ignore occurrences of that buffer in LIST."
64 ;; This logic is more or less copied from other-buffer.
65 (setq frame
(or frame
(selected-frame)))
66 (let ((pred (frame-parameter frame
'buffer-predicate
))
68 (while (and (not found
) list
)
70 (if (and (not (eq buffer buf
))
72 (or (null pred
) (funcall pred buf
))
73 (not (eq (aref (buffer-name buf
) 0) ?\s
))
74 (or visible-ok
(null (get-buffer-window buf
'visible
))))
76 (setq list
(cdr list
))))
79 (defun last-buffer (&optional buffer visible-ok frame
)
80 "Return the last non-hidden displayable buffer in the buffer list.
81 If BUFFER is non-nil, last-buffer will ignore that buffer.
82 Buffers not visible in windows are preferred to visible buffers,
83 unless optional argument VISIBLE-OK is non-nil.
84 If the optional third argument FRAME is non-nil, use that frame's
85 buffer list instead of the selected frame's buffer list.
86 If no other buffer exists, the buffer `*scratch*' is returned."
87 (setq frame
(or frame
(selected-frame)))
88 (or (get-next-valid-buffer (nreverse (buffer-list frame
))
89 buffer visible-ok frame
)
91 (set-buffer-major-mode (get-buffer-create "*scratch*"))
92 (get-buffer "*scratch*"))))
94 "Switch to the next buffer in cyclic order."
96 (let ((buffer (current-buffer)))
97 (switch-to-buffer (other-buffer buffer t
))
98 (bury-buffer buffer
)))
100 (defun previous-buffer ()
101 "Switch to the previous buffer in cyclic order."
103 (switch-to-buffer (last-buffer (current-buffer) t
)))
106 ;;; next-error support framework
108 (defgroup next-error nil
109 "`next-error' support framework."
114 '((t (:inherit region
)))
115 "Face used to highlight next error locus."
119 (defcustom next-error-highlight
0.5
120 "*Highlighting of locations in selected source buffers.
121 If a number, highlight the locus in `next-error' face for the given time
122 in seconds, or until the next command is executed.
123 If t, highlight the locus until the next command is executed, or until
124 some other locus replaces it.
125 If nil, don't highlight the locus in the source buffer.
126 If `fringe-arrow', indicate the locus by the fringe arrow."
127 :type
'(choice (number :tag
"Highlight for specified time")
128 (const :tag
"Semipermanent highlighting" t
)
129 (const :tag
"No highlighting" nil
)
130 (const :tag
"Fringe arrow" fringe-arrow
))
134 (defcustom next-error-highlight-no-select
0.5
135 "*Highlighting of locations in `next-error-no-select'.
136 If number, highlight the locus in `next-error' face for given time in seconds.
137 If t, highlight the locus indefinitely until some other locus replaces it.
138 If nil, don't highlight the locus in the source buffer.
139 If `fringe-arrow', indicate the locus by the fringe arrow."
140 :type
'(choice (number :tag
"Highlight for specified time")
141 (const :tag
"Semipermanent highlighting" t
)
142 (const :tag
"No highlighting" nil
)
143 (const :tag
"Fringe arrow" fringe-arrow
))
147 (defcustom next-error-recenter nil
148 "*Display the line in the visited source file recentered as specified.
149 If non-nil, the value is passed directly to `recenter'."
150 :type
'(choice (integer :tag
"Line to recenter to")
151 (const :tag
"Center of window" (4))
152 (const :tag
"No recentering" nil
))
156 (defcustom next-error-hook nil
157 "*List of hook functions run by `next-error' after visiting source file."
161 (defvar next-error-highlight-timer nil
)
163 (defvar next-error-overlay-arrow-position nil
)
164 (put 'next-error-overlay-arrow-position
'overlay-arrow-string
"=>")
165 (add-to-list 'overlay-arrow-variable-list
'next-error-overlay-arrow-position
)
167 (defvar next-error-last-buffer nil
168 "The most recent `next-error' buffer.
169 A buffer becomes most recent when its compilation, grep, or
170 similar mode is started, or when it is used with \\[next-error]
171 or \\[compile-goto-error].")
173 (defvar next-error-function nil
174 "Function to use to find the next error in the current buffer.
175 The function is called with 2 parameters:
176 ARG is an integer specifying by how many errors to move.
177 RESET is a boolean which, if non-nil, says to go back to the beginning
178 of the errors before moving.
179 Major modes providing compile-like functionality should set this variable
180 to indicate to `next-error' that this is a candidate buffer and how
183 (make-variable-buffer-local 'next-error-function
)
185 (defsubst next-error-buffer-p
(buffer
186 &optional avoid-current
188 extra-test-exclusive
)
189 "Test if BUFFER is a `next-error' capable buffer.
191 If AVOID-CURRENT is non-nil, treat the current buffer
192 as an absolute last resort only.
194 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
195 that normally would not qualify. If it returns t, the buffer
196 in question is treated as usable.
198 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
199 that would normally be considered usable. If it returns nil,
200 that buffer is rejected."
201 (and (buffer-name buffer
) ;First make sure it's live.
202 (not (and avoid-current
(eq buffer
(current-buffer))))
203 (with-current-buffer buffer
204 (if next-error-function
; This is the normal test.
205 ;; Optionally reject some buffers.
206 (if extra-test-exclusive
207 (funcall extra-test-exclusive
)
209 ;; Optionally accept some other buffers.
210 (and extra-test-inclusive
211 (funcall extra-test-inclusive
))))))
213 (defun next-error-find-buffer (&optional avoid-current
215 extra-test-exclusive
)
216 "Return a `next-error' capable buffer.
218 If AVOID-CURRENT is non-nil, treat the current buffer
219 as an absolute last resort only.
221 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
222 that normally would not qualify. If it returns t, the buffer
223 in question is treated as usable.
225 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
226 that would normally be considered usable. If it returns nil,
227 that buffer is rejected."
229 ;; 1. If one window on the selected frame displays such buffer, return it.
230 (let ((window-buffers
232 (delq nil
(mapcar (lambda (w)
233 (if (next-error-buffer-p
236 extra-test-inclusive extra-test-exclusive
)
239 (if (eq (length window-buffers
) 1)
240 (car window-buffers
)))
241 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
242 (if (and next-error-last-buffer
243 (next-error-buffer-p next-error-last-buffer avoid-current
244 extra-test-inclusive extra-test-exclusive
))
245 next-error-last-buffer
)
246 ;; 3. If the current buffer is acceptable, choose it.
247 (if (next-error-buffer-p (current-buffer) avoid-current
248 extra-test-inclusive extra-test-exclusive
)
250 ;; 4. Look for any acceptable buffer.
251 (let ((buffers (buffer-list)))
253 (not (next-error-buffer-p
254 (car buffers
) avoid-current
255 extra-test-inclusive extra-test-exclusive
)))
256 (setq buffers
(cdr buffers
)))
258 ;; 5. Use the current buffer as a last resort if it qualifies,
259 ;; even despite AVOID-CURRENT.
261 (next-error-buffer-p (current-buffer) nil
262 extra-test-inclusive extra-test-exclusive
)
264 (message "This is the only buffer with error message locations")
267 (error "No buffers contain error message locations")))
269 (defun next-error (&optional arg reset
)
270 "Visit next `next-error' message and corresponding source code.
272 If all the error messages parsed so far have been processed already,
273 the message buffer is checked for new ones.
275 A prefix ARG specifies how many error messages to move;
276 negative means move back to previous error messages.
277 Just \\[universal-argument] as a prefix means reparse the error message buffer
278 and start at the first error.
280 The RESET argument specifies that we should restart from the beginning.
282 \\[next-error] normally uses the most recently started
283 compilation, grep, or occur buffer. It can also operate on any
284 buffer with output from the \\[compile], \\[grep] commands, or,
285 more generally, on any buffer in Compilation mode or with
286 Compilation Minor mode enabled, or any buffer in which
287 `next-error-function' is bound to an appropriate function.
288 To specify use of a particular buffer for error messages, type
289 \\[next-error] in that buffer when it is the only one displayed
290 in the current frame.
292 Once \\[next-error] has chosen the buffer for error messages, it
293 runs `next-error-hook' with `run-hooks', and stays with that buffer
294 until you use it in some other buffer which uses Compilation mode
295 or Compilation Minor mode.
297 See variables `compilation-parse-errors-function' and
298 \`compilation-error-regexp-alist' for customization ideas."
300 (if (consp arg
) (setq reset t arg nil
))
301 (when (setq next-error-last-buffer
(next-error-find-buffer))
302 ;; we know here that next-error-function is a valid symbol we can funcall
303 (with-current-buffer next-error-last-buffer
304 (funcall next-error-function
(prefix-numeric-value arg
) reset
)
305 (when next-error-recenter
306 (recenter next-error-recenter
))
307 (run-hooks 'next-error-hook
))))
309 (defun next-error-internal ()
310 "Visit the source code corresponding to the `next-error' message at point."
311 (setq next-error-last-buffer
(current-buffer))
312 ;; we know here that next-error-function is a valid symbol we can funcall
313 (with-current-buffer next-error-last-buffer
314 (funcall next-error-function
0 nil
)
315 (when next-error-recenter
316 (recenter next-error-recenter
))
317 (run-hooks 'next-error-hook
)))
319 (defalias 'goto-next-locus
'next-error
)
320 (defalias 'next-match
'next-error
)
322 (defun previous-error (&optional n
)
323 "Visit previous `next-error' message and corresponding source code.
325 Prefix arg N says how many error messages to move backwards (or
326 forwards, if negative).
328 This operates on the output from the \\[compile] and \\[grep] commands."
330 (next-error (- (or n
1))))
332 (defun first-error (&optional n
)
333 "Restart at the first error.
334 Visit corresponding source code.
335 With prefix arg N, visit the source code of the Nth error.
336 This operates on the output from the \\[compile] command, for instance."
340 (defun next-error-no-select (&optional n
)
341 "Move point to the next error in the `next-error' buffer and highlight match.
342 Prefix arg N says how many error messages to move forwards (or
343 backwards, if negative).
344 Finds and highlights the source line like \\[next-error], but does not
345 select the source buffer."
347 (let ((next-error-highlight next-error-highlight-no-select
))
349 (pop-to-buffer next-error-last-buffer
))
351 (defun previous-error-no-select (&optional n
)
352 "Move point to the previous error in the `next-error' buffer and highlight match.
353 Prefix arg N says how many error messages to move backwards (or
354 forwards, if negative).
355 Finds and highlights the source line like \\[previous-error], but does not
356 select the source buffer."
358 (next-error-no-select (- (or n
1))))
360 ;;; Internal variable for `next-error-follow-mode-post-command-hook'.
361 (defvar next-error-follow-last-line nil
)
363 (define-minor-mode next-error-follow-minor-mode
364 "Minor mode for compilation, occur and diff modes.
365 When turned on, cursor motion in the compilation, grep, occur or diff
366 buffer causes automatic display of the corresponding source code
368 :group
'next-error
:init-value nil
:lighter
" Fol"
369 (if (not next-error-follow-minor-mode
)
370 (remove-hook 'post-command-hook
'next-error-follow-mode-post-command-hook t
)
371 (add-hook 'post-command-hook
'next-error-follow-mode-post-command-hook nil t
)
372 (make-local-variable 'next-error-follow-last-line
)))
374 ;;; Used as a `post-command-hook' by `next-error-follow-mode'
375 ;;; for the *Compilation* *grep* and *Occur* buffers.
376 (defun next-error-follow-mode-post-command-hook ()
377 (unless (equal next-error-follow-last-line
(line-number-at-pos))
378 (setq next-error-follow-last-line
(line-number-at-pos))
380 (let ((compilation-context-lines nil
))
381 (setq compilation-current-error
(point))
382 (next-error-no-select 0))
388 (defun fundamental-mode ()
389 "Major mode not specialized for anything in particular.
390 Other major modes are defined by comparison with this one."
392 (kill-all-local-variables)
393 (unless delay-mode-hooks
394 (run-hooks 'after-change-major-mode-hook
)))
396 ;; Making and deleting lines.
398 (defvar hard-newline
(propertize "\n" 'hard t
'rear-nonsticky
'(hard)))
400 (defun newline (&optional arg
)
401 "Insert a newline, and move to left margin of the new line if it's blank.
402 If `use-hard-newlines' is non-nil, the newline is marked with the
403 text-property `hard'.
404 With ARG, insert that many newlines.
405 Call `auto-fill-function' if the current column number is greater
406 than the value of `fill-column' and ARG is nil."
408 (barf-if-buffer-read-only)
409 ;; Inserting a newline at the end of a line produces better redisplay in
410 ;; try_window_id than inserting at the beginning of a line, and the textual
411 ;; result is the same. So, if we're at beginning of line, pretend to be at
412 ;; the end of the previous line.
413 (let ((flag (and (not (bobp))
415 ;; Make sure no functions want to be told about
416 ;; the range of the changes.
417 (not after-change-functions
)
418 (not before-change-functions
)
419 ;; Make sure there are no markers here.
420 (not (buffer-has-markers-at (1- (point))))
421 (not (buffer-has-markers-at (point)))
422 ;; Make sure no text properties want to know
423 ;; where the change was.
424 (not (get-char-property (1- (point)) 'modification-hooks
))
425 (not (get-char-property (1- (point)) 'insert-behind-hooks
))
427 (not (get-char-property (point) 'insert-in-front-hooks
)))
428 ;; Make sure the newline before point isn't intangible.
429 (not (get-char-property (1- (point)) 'intangible
))
430 ;; Make sure the newline before point isn't read-only.
431 (not (get-char-property (1- (point)) 'read-only
))
432 ;; Make sure the newline before point isn't invisible.
433 (not (get-char-property (1- (point)) 'invisible
))
434 ;; Make sure the newline before point has the same
435 ;; properties as the char before it (if any).
436 (< (or (previous-property-change (point)) -
2)
438 (was-page-start (and (bolp)
439 (looking-at page-delimiter
)))
441 (if flag
(backward-char 1))
442 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
443 ;; Set last-command-char to tell self-insert what to insert.
444 (let ((last-command-char ?
\n)
445 ;; Don't auto-fill if we have a numeric argument.
446 ;; Also not if flag is true (it would fill wrong line);
447 ;; there is no need to since we're at BOL.
448 (auto-fill-function (if (or arg flag
) nil auto-fill-function
)))
450 (self-insert-command (prefix-numeric-value arg
))
451 ;; If we get an error in self-insert-command, put point at right place.
452 (if flag
(forward-char 1))))
453 ;; Even if we did *not* get an error, keep that forward-char;
454 ;; all further processing should apply to the newline that the user
455 ;; thinks he inserted.
457 ;; Mark the newline(s) `hard'.
458 (if use-hard-newlines
459 (set-hard-newline-properties
460 (- (point) (prefix-numeric-value arg
)) (point)))
461 ;; If the newline leaves the previous line blank,
462 ;; and we have a left margin, delete that from the blank line.
465 (goto-char beforepos
)
467 (and (looking-at "[ \t]$")
468 (> (current-left-margin) 0)
469 (delete-region (point) (progn (end-of-line) (point))))))
470 ;; Indent the line after the newline, except in one case:
471 ;; when we added the newline at the beginning of a line
472 ;; which starts a page.
474 (move-to-left-margin nil t
)))
477 (defun set-hard-newline-properties (from to
)
478 (let ((sticky (get-text-property from
'rear-nonsticky
)))
479 (put-text-property from to
'hard
't
)
480 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
481 (if (and (listp sticky
) (not (memq 'hard sticky
)))
482 (put-text-property from
(point) 'rear-nonsticky
483 (cons 'hard sticky
)))))
486 "Insert a newline and leave point before it.
487 If there is a fill prefix and/or a `left-margin', insert them
488 on the new line if the line would have been blank.
489 With arg N, insert N newlines."
491 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
492 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
494 ;; Don't expand an abbrev before point.
500 (if do-left-margin
(indent-to (current-left-margin)))
501 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
507 (defun split-line (&optional arg
)
508 "Split current line, moving portion beyond point vertically down.
509 If the current line starts with `fill-prefix', insert it on the new
510 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
512 When called from Lisp code, ARG may be a prefix string to copy."
514 (skip-chars-forward " \t")
515 (let* ((col (current-column))
517 ;; What prefix should we check for (nil means don't).
518 (prefix (cond ((stringp arg
) arg
)
521 ;; Does this line start with it?
522 (have-prfx (and prefix
525 (looking-at (regexp-quote prefix
))))))
527 (if have-prfx
(insert-and-inherit prefix
))
531 (defun delete-indentation (&optional arg
)
532 "Join this line to previous and fix up whitespace at join.
533 If there is a fill prefix, delete it from the beginning of this line.
534 With argument, join this line to following line."
537 (if arg
(forward-line 1))
538 (if (eq (preceding-char) ?
\n)
540 (delete-region (point) (1- (point)))
541 ;; If the second line started with the fill prefix,
542 ;; delete the prefix.
544 (<= (+ (point) (length fill-prefix
)) (point-max))
546 (buffer-substring (point)
547 (+ (point) (length fill-prefix
)))))
548 (delete-region (point) (+ (point) (length fill-prefix
))))
549 (fixup-whitespace))))
551 (defalias 'join-line
#'delete-indentation
) ; easier to find
553 (defun delete-blank-lines ()
554 "On blank line, delete all surrounding blank lines, leaving just one.
555 On isolated blank line, delete that one.
556 On nonblank line, delete any immediately following blank lines."
558 (let (thisblank singleblank
)
561 (setq thisblank
(looking-at "[ \t]*$"))
562 ;; Set singleblank if there is just one blank line here.
565 (not (looking-at "[ \t]*\n[ \t]*$"))
567 (progn (forward-line -
1)
568 (not (looking-at "[ \t]*$")))))))
569 ;; Delete preceding blank lines, and this one too if it's the only one.
573 (if singleblank
(forward-line 1))
574 (delete-region (point)
575 (if (re-search-backward "[^ \t\n]" nil t
)
576 (progn (forward-line 1) (point))
578 ;; Delete following blank lines, unless the current line is blank
579 ;; and there are no following blank lines.
580 (if (not (and thisblank singleblank
))
584 (delete-region (point)
585 (if (re-search-forward "[^ \t\n]" nil t
)
586 (progn (beginning-of-line) (point))
588 ;; Handle the special case where point is followed by newline and eob.
589 ;; Delete the line, leaving point at eob.
590 (if (looking-at "^[ \t]*\n\\'")
591 (delete-region (point) (point-max)))))
593 (defun delete-trailing-whitespace ()
594 "Delete all the trailing whitespace across the current buffer.
595 All whitespace after the last non-whitespace character in a line is deleted.
596 This respects narrowing, created by \\[narrow-to-region] and friends.
597 A formfeed is not considered whitespace by this function."
601 (goto-char (point-min))
602 (while (re-search-forward "\\s-$" nil t
)
603 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
604 ;; Don't delete formfeeds, even if they are considered whitespace.
606 (if (looking-at ".*\f")
607 (goto-char (match-end 0))))
608 (delete-region (point) (match-end 0))))))
610 (defun newline-and-indent ()
611 "Insert a newline, then indent according to major mode.
612 Indentation is done using the value of `indent-line-function'.
613 In programming language modes, this is the same as TAB.
614 In some text modes, where TAB inserts a tab, this command indents to the
615 column specified by the function `current-left-margin'."
617 (delete-horizontal-space t
)
619 (indent-according-to-mode))
621 (defun reindent-then-newline-and-indent ()
622 "Reindent current line, insert newline, then indent the new line.
623 Indentation of both lines is done according to the current major mode,
624 which means calling the current value of `indent-line-function'.
625 In programming language modes, this is the same as TAB.
626 In some text modes, where TAB inserts a tab, this indents to the
627 column specified by the function `current-left-margin'."
630 ;; Be careful to insert the newline before indenting the line.
631 ;; Otherwise, the indentation might be wrong.
635 ;; We are at EOL before the call to indent-according-to-mode, and
636 ;; after it we usually are as well, but not always. We tried to
637 ;; address it with `save-excursion' but that uses a normal marker
638 ;; whereas we need `move after insertion', so we do the save/restore
640 (setq pos
(copy-marker pos t
))
641 (indent-according-to-mode)
643 ;; Remove the trailing white-space after indentation because
644 ;; indentation may introduce the whitespace.
645 (delete-horizontal-space t
))
646 (indent-according-to-mode)))
648 (defun quoted-insert (arg)
649 "Read next input character and insert it.
650 This is useful for inserting control characters.
652 If the first character you type after this command is an octal digit,
653 you should type a sequence of octal digits which specify a character code.
654 Any nondigit terminates the sequence. If the terminator is a RET,
655 it is discarded; any other terminator is used itself as input.
656 The variable `read-quoted-char-radix' specifies the radix for this feature;
657 set it to 10 or 16 to use decimal or hex instead of octal.
659 In overwrite mode, this function inserts the character anyway, and
660 does not handle octal digits specially. This means that if you use
661 overwrite as your normal editing mode, you can use this function to
662 insert characters when necessary.
664 In binary overwrite mode, this function does overwrite, and octal
665 digits are interpreted as a character code. This is intended to be
666 useful for editing binary files."
668 (let* ((char (let (translation-table-for-input input-method-function
)
669 (if (or (not overwrite-mode
)
670 (eq overwrite-mode
'overwrite-mode-binary
))
673 ;; Assume character codes 0240 - 0377 stand for characters in some
674 ;; single-byte character set, and convert them to Emacs
676 (if (and enable-multibyte-characters
679 (setq char
(unibyte-char-to-multibyte char
)))
681 (if (eq overwrite-mode
'overwrite-mode-binary
)
684 (insert-and-inherit char
)
685 (setq arg
(1- arg
)))))
687 (defun forward-to-indentation (&optional arg
)
688 "Move forward ARG lines and position at first nonblank character."
690 (forward-line (or arg
1))
691 (skip-chars-forward " \t"))
693 (defun backward-to-indentation (&optional arg
)
694 "Move backward ARG lines and position at first nonblank character."
696 (forward-line (- (or arg
1)))
697 (skip-chars-forward " \t"))
699 (defun back-to-indentation ()
700 "Move point to the first non-whitespace character on this line."
702 (beginning-of-line 1)
703 (skip-syntax-forward " " (line-end-position))
704 ;; Move back over chars that have whitespace syntax but have the p flag.
705 (backward-prefix-chars))
707 (defun fixup-whitespace ()
708 "Fixup white space between objects around point.
709 Leave one space or none, according to the context."
712 (delete-horizontal-space)
713 (if (or (looking-at "^\\|\\s)")
714 (save-excursion (forward-char -
1)
715 (looking-at "$\\|\\s(\\|\\s'")))
719 (defun delete-horizontal-space (&optional backward-only
)
720 "Delete all spaces and tabs around point.
721 If BACKWARD-ONLY is non-nil, only delete them before point."
723 (let ((orig-pos (point)))
728 (skip-chars-forward " \t")
729 (constrain-to-field nil orig-pos t
)))
731 (skip-chars-backward " \t")
732 (constrain-to-field nil orig-pos
)))))
734 (defun just-one-space (&optional n
)
735 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
737 (let ((orig-pos (point)))
738 (skip-chars-backward " \t")
739 (constrain-to-field nil orig-pos
)
740 (dotimes (i (or n
1))
741 (if (= (following-char) ?\s
)
747 (skip-chars-forward " \t")
748 (constrain-to-field nil orig-pos t
)))))
750 (defun beginning-of-buffer (&optional arg
)
751 "Move point to the beginning of the buffer; leave mark at previous position.
752 With \\[universal-argument] prefix, do not set mark at previous position.
753 With numeric arg N, put point N/10 of the way from the beginning.
755 If the buffer is narrowed, this command uses the beginning and size
756 of the accessible part of the buffer.
758 Don't use this command in Lisp programs!
759 \(goto-char (point-min)) is faster and avoids clobbering the mark."
764 (let ((size (- (point-max) (point-min))))
765 (goto-char (if (and arg
(not (consp arg
)))
768 ;; Avoid overflow for large buffer sizes!
769 (* (prefix-numeric-value arg
)
771 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
773 (if (and arg
(not (consp arg
))) (forward-line 1)))
775 (defun end-of-buffer (&optional arg
)
776 "Move point to the end of the buffer; leave mark at previous position.
777 With \\[universal-argument] prefix, do not set mark at previous position.
778 With numeric arg N, put point N/10 of the way from the end.
780 If the buffer is narrowed, this command uses the beginning and size
781 of the accessible part of the buffer.
783 Don't use this command in Lisp programs!
784 \(goto-char (point-max)) is faster and avoids clobbering the mark."
786 (or (consp arg
) (region-active-p) (push-mark))
787 (let ((size (- (point-max) (point-min))))
788 (goto-char (if (and arg
(not (consp arg
)))
791 ;; Avoid overflow for large buffer sizes!
792 (* (prefix-numeric-value arg
)
794 (/ (* size
(prefix-numeric-value arg
)) 10)))
796 ;; If we went to a place in the middle of the buffer,
797 ;; adjust it to the beginning of a line.
798 (cond ((and arg
(not (consp arg
))) (forward-line 1))
799 ((> (point) (window-end nil t
))
800 ;; If the end of the buffer is not already on the screen,
801 ;; then scroll specially to put it near, but not at, the bottom.
802 (overlay-recenter (point))
805 (defun mark-whole-buffer ()
806 "Put point at beginning and mark at end of buffer.
807 You probably should not use this function in Lisp programs;
808 it is usually a mistake for a Lisp function to use any subroutine
809 that uses or sets the mark."
812 (push-mark (point-max) nil t
)
813 (goto-char (point-min)))
816 ;; Counting lines, one way or another.
818 (defun goto-line (arg &optional buffer
)
819 "Goto line ARG, counting from line 1 at beginning of buffer.
820 Normally, move point in the current buffer, and leave mark at previous
821 position. With just \\[universal-argument] as argument, move point
822 in the most recently displayed other buffer, and switch to it.
823 When called from Lisp code, the optional argument BUFFER specifies
824 a buffer to switch to.
826 If there's a number in the buffer at point, it is the default for ARG."
828 (if (and current-prefix-arg
(not (consp current-prefix-arg
)))
829 (list (prefix-numeric-value current-prefix-arg
))
830 ;; Look for a default, a number in the buffer at point.
833 (skip-chars-backward "0-9")
834 (if (looking-at "[0-9]")
835 (buffer-substring-no-properties
837 (progn (skip-chars-forward "0-9")
839 ;; Decide if we're switching buffers.
841 (if (consp current-prefix-arg
)
842 (other-buffer (current-buffer) t
)))
845 (concat " in " (buffer-name buffer
))
847 ;; Read the argument, offering that number (if any) as default.
848 (list (read-from-minibuffer (format (if default
"Goto line%s (%s): "
856 ;; Switch to the desired buffer, one way or another.
858 (let ((window (get-buffer-window buffer
)))
859 (if window
(select-window window
)
860 (switch-to-buffer-other-window buffer
))))
861 ;; Leave mark at previous position
862 (or (region-active-p) (push-mark))
863 ;; Move to the specified line number in that buffer.
867 (if (eq selective-display t
)
868 (re-search-forward "[\n\C-m]" nil
'end
(1- arg
))
869 (forward-line (1- arg
)))))
871 (defun count-lines-region (start end
)
872 "Print number of lines and characters in the region."
874 (message "Region has %d lines, %d characters"
875 (count-lines start end
) (- end start
)))
878 "Print the current buffer line number and narrowed line number of point."
880 (let ((start (point-min))
881 (n (line-number-at-pos)))
883 (message "Line %d" n
)
887 (message "line %d (narrowed line %d)"
888 (+ n
(line-number-at-pos start
) -
1) n
))))))
890 (defun count-lines (start end
)
891 "Return number of lines between START and END.
892 This is usually the number of newlines between them,
893 but can be one more if START is not equal to END
894 and the greater of them is not at the start of a line."
897 (narrow-to-region start end
)
898 (goto-char (point-min))
899 (if (eq selective-display t
)
902 (while (re-search-forward "[\n\C-m]" nil t
40)
903 (setq done
(+ 40 done
)))
904 (while (re-search-forward "[\n\C-m]" nil t
1)
905 (setq done
(+ 1 done
)))
906 (goto-char (point-max))
907 (if (and (/= start end
)
911 (- (buffer-size) (forward-line (buffer-size)))))))
913 (defun line-number-at-pos (&optional pos
)
914 "Return (narrowed) buffer line number at position POS.
915 If POS is nil, use current buffer location.
916 Counting starts at (point-min), so the value refers
917 to the contents of the accessible portion of the buffer."
918 (let ((opoint (or pos
(point))) start
)
920 (goto-char (point-min))
924 (1+ (count-lines start
(point))))))
926 (defun what-cursor-position (&optional detail
)
927 "Print info on cursor position (on screen and within buffer).
928 Also describe the character after point, and give its character code
929 in octal, decimal and hex.
931 For a non-ASCII multibyte character, also give its encoding in the
932 buffer's selected coding system if the coding system encodes the
933 character safely. If the character is encoded into one byte, that
934 code is shown in hex. If the character is encoded into more than one
935 byte, just \"...\" is shown.
937 In addition, with prefix argument, show details about that character
938 in *Help* buffer. See also the command `describe-char'."
940 (let* ((char (following-char))
944 (total (buffer-size))
945 (percent (if (> total
50000)
946 ;; Avoid overflow from multiplying by 100!
947 (/ (+ (/ total
200) (1- pos
)) (max (/ total
100) 1))
948 (/ (+ (/ total
2) (* 100 (1- pos
))) (max total
1))))
949 (hscroll (if (= (window-hscroll) 0)
951 (format " Hscroll=%d" (window-hscroll))))
952 (col (current-column)))
954 (if (or (/= beg
1) (/= end
(1+ total
)))
955 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
956 pos total percent beg end col hscroll
)
957 (message "point=%d of %d (EOB) column=%d%s"
958 pos total col hscroll
))
959 (let ((coding buffer-file-coding-system
)
960 encoded encoding-msg display-prop under-display
)
962 (eq (coding-system-type coding
) t
))
963 (setq coding default-buffer-file-coding-system
))
964 (if (eq (char-charset char
) 'eight-bit
)
966 (format "(%d, #o%o, #x%x, raw-byte)" char char char
))
967 ;; Check if the character is displayed with some `display'
968 ;; text property. In that case, set under-display to the
969 ;; buffer substring covered by that property.
970 (setq display-prop
(get-text-property pos
'display
))
972 (let ((to (or (next-single-property-change pos
'display
)
975 (setq under-display
"")
976 (setq under-display
"..."
979 (concat (buffer-substring-no-properties pos to
)
981 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
984 (if (not (stringp display-prop
))
985 (format "(%d, #o%o, #x%x, part of display \"%s\")"
986 char char char under-display
)
987 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
988 char char char under-display display-prop
))
990 (format "(%d, #o%o, #x%x, file %s)"
992 (if (> (length encoded
) 1)
994 (encoded-string-description encoded coding
)))
995 (format "(%d, #o%o, #x%x)" char char char
)))))
997 ;; We show the detailed information about CHAR.
998 (describe-char (point)))
999 (if (or (/= beg
1) (/= end
(1+ total
)))
1000 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1002 (single-key-description char
)
1003 (buffer-substring-no-properties (point) (1+ (point))))
1004 encoding-msg pos total percent beg end col hscroll
)
1005 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
1006 (if enable-multibyte-characters
1008 (single-key-description char
)
1009 (buffer-substring-no-properties (point) (1+ (point))))
1010 (single-key-description char
))
1011 encoding-msg pos total percent col hscroll
))))))
1013 ;; Initialize read-expression-map. It is defined at C level.
1014 (let ((m (make-sparse-keymap)))
1015 (define-key m
"\M-\t" 'lisp-complete-symbol
)
1016 (set-keymap-parent m minibuffer-local-map
)
1017 (setq read-expression-map m
))
1019 (defvar read-expression-history nil
)
1021 (defvar minibuffer-completing-symbol nil
1022 "Non-nil means completing a Lisp symbol in the minibuffer.")
1024 (defcustom eval-expression-print-level
4
1025 "Value for `print-level' while printing value in `eval-expression'.
1026 A value of nil means no limit."
1028 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1031 (defcustom eval-expression-print-length
12
1032 "Value for `print-length' while printing value in `eval-expression'.
1033 A value of nil means no limit."
1035 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1038 (defcustom eval-expression-debug-on-error t
1039 "If non-nil set `debug-on-error' to t in `eval-expression'.
1040 If nil, don't change the value of `debug-on-error'."
1045 (defun eval-expression-print-format (value)
1046 "Format VALUE as a result of evaluated expression.
1047 Return a formatted string which is displayed in the echo area
1048 in addition to the value printed by prin1 in functions which
1049 display the result of expression evaluation."
1050 (if (and (integerp value
)
1051 (or (not (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1052 (eq this-command last-command
)
1053 (if (boundp 'edebug-active
) edebug-active
)))
1055 (if (or (if (boundp 'edebug-active
) edebug-active
)
1056 (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1057 (prin1-char value
))))
1059 (format " (#o%o, #x%x, %s)" value value char-string
)
1060 (format " (#o%o, #x%x)" value value
)))))
1062 ;; We define this, rather than making `eval' interactive,
1063 ;; for the sake of completion of names like eval-region, eval-buffer.
1064 (defun eval-expression (eval-expression-arg
1065 &optional eval-expression-insert-value
)
1066 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1067 Value is also consed on to front of the variable `values'.
1068 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
1069 insert the result into the current buffer instead of printing it in
1072 If `eval-expression-debug-on-error' is non-nil, which is the default,
1073 this command arranges for all errors to enter the debugger."
1075 (list (let ((minibuffer-completing-symbol t
))
1076 (read-from-minibuffer "Eval: "
1077 nil read-expression-map t
1078 'read-expression-history
))
1079 current-prefix-arg
))
1081 (if (null eval-expression-debug-on-error
)
1082 (setq values
(cons (eval eval-expression-arg
) values
))
1083 (let ((old-value (make-symbol "t")) new-value
)
1084 ;; Bind debug-on-error to something unique so that we can
1085 ;; detect when evaled code changes it.
1086 (let ((debug-on-error old-value
))
1087 (setq values
(cons (eval eval-expression-arg
) values
))
1088 (setq new-value debug-on-error
))
1089 ;; If evaled code has changed the value of debug-on-error,
1090 ;; propagate that change to the global binding.
1091 (unless (eq old-value new-value
)
1092 (setq debug-on-error new-value
))))
1094 (let ((print-length eval-expression-print-length
)
1095 (print-level eval-expression-print-level
))
1096 (if eval-expression-insert-value
1098 (let ((standard-output (current-buffer)))
1099 (prin1 (car values
))))
1101 (prin1 (car values
) t
)
1102 (let ((str (eval-expression-print-format (car values
))))
1103 (if str
(princ str t
)))))))
1105 (defun edit-and-eval-command (prompt command
)
1106 "Prompting with PROMPT, let user edit COMMAND and eval result.
1107 COMMAND is a Lisp expression. Let user edit that expression in
1108 the minibuffer, then read and evaluate the result."
1110 (let ((print-level nil
)
1111 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1113 (read-from-minibuffer prompt
1114 (prin1-to-string command
)
1115 read-expression-map t
1117 ;; If command was added to command-history as a string,
1118 ;; get rid of that. We want only evaluable expressions there.
1119 (if (stringp (car command-history
))
1120 (setq command-history
(cdr command-history
)))))))
1122 ;; If command to be redone does not match front of history,
1123 ;; add it to the history.
1124 (or (equal command
(car command-history
))
1125 (setq command-history
(cons command command-history
)))
1128 (defun repeat-complex-command (arg)
1129 "Edit and re-evaluate last complex command, or ARGth from last.
1130 A complex command is one which used the minibuffer.
1131 The command is placed in the minibuffer as a Lisp form for editing.
1132 The result is executed, repeating the command as changed.
1133 If the command has been changed or is not the most recent previous command
1134 it is added to the front of the command history.
1135 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1136 to get different commands to edit and resubmit."
1138 (let ((elt (nth (1- arg
) command-history
))
1143 (let ((print-level nil
)
1144 (minibuffer-history-position arg
)
1145 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1147 (read-from-minibuffer
1148 "Redo: " (prin1-to-string elt
) read-expression-map t
1149 (cons 'command-history arg
))
1151 ;; If command was added to command-history as a
1152 ;; string, get rid of that. We want only
1153 ;; evaluable expressions there.
1154 (if (stringp (car command-history
))
1155 (setq command-history
(cdr command-history
))))))
1157 ;; If command to be redone does not match front of history,
1158 ;; add it to the history.
1159 (or (equal newcmd
(car command-history
))
1160 (setq command-history
(cons newcmd command-history
)))
1163 (error "Argument %d is beyond length of command history" arg
)
1164 (error "There are no previous complex commands to repeat")))))
1166 (defvar minibuffer-history nil
1167 "Default minibuffer history list.
1168 This is used for all minibuffer input
1169 except when an alternate history list is specified.
1171 Maximum length of the history list is determined by the value
1172 of `history-length', which see.")
1173 (defvar minibuffer-history-sexp-flag nil
1174 "Control whether history list elements are expressions or strings.
1175 If the value of this variable equals current minibuffer depth,
1176 they are expressions; otherwise they are strings.
1177 \(That convention is designed to do the right thing for
1178 recursive uses of the minibuffer.)")
1179 (setq minibuffer-history-variable
'minibuffer-history
)
1180 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1181 (defvar minibuffer-history-search-history nil
)
1183 (defvar minibuffer-text-before-history nil
1184 "Text that was in this minibuffer before any history commands.
1185 This is nil if there have not yet been any history commands
1186 in this use of the minibuffer.")
1188 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1190 (defun minibuffer-history-initialize ()
1191 (setq minibuffer-text-before-history nil
))
1193 (defun minibuffer-avoid-prompt (new old
)
1194 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1195 (constrain-to-field nil
(point-max)))
1197 (defcustom minibuffer-history-case-insensitive-variables nil
1198 "*Minibuffer history variables for which matching should ignore case.
1199 If a history variable is a member of this list, then the
1200 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1201 commands ignore case when searching it, regardless of `case-fold-search'."
1202 :type
'(repeat variable
)
1205 (defun previous-matching-history-element (regexp n
)
1206 "Find the previous history element that matches REGEXP.
1207 \(Previous history elements refer to earlier actions.)
1208 With prefix argument N, search for Nth previous match.
1209 If N is negative, find the next or Nth next match.
1210 Normally, history elements are matched case-insensitively if
1211 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1212 makes the search case-sensitive.
1213 See also `minibuffer-history-case-insensitive-variables'."
1215 (let* ((enable-recursive-minibuffers t
)
1216 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1218 minibuffer-local-map
1220 'minibuffer-history-search-history
1221 (car minibuffer-history-search-history
))))
1222 ;; Use the last regexp specified, by default, if input is empty.
1223 (list (if (string= regexp
"")
1224 (if minibuffer-history-search-history
1225 (car minibuffer-history-search-history
)
1226 (error "No previous history search regexp"))
1228 (prefix-numeric-value current-prefix-arg
))))
1230 (if (and (zerop minibuffer-history-position
)
1231 (null minibuffer-text-before-history
))
1232 (setq minibuffer-text-before-history
1233 (minibuffer-contents-no-properties)))
1234 (let ((history (symbol-value minibuffer-history-variable
))
1236 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1237 ;; On some systems, ignore case for file names.
1238 (if (memq minibuffer-history-variable
1239 minibuffer-history-case-insensitive-variables
)
1241 ;; Respect the user's setting for case-fold-search:
1247 (pos minibuffer-history-position
))
1250 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1251 (when (= pos prevpos
)
1252 (error (if (= pos
1)
1253 "No later matching history item"
1254 "No earlier matching history item")))
1256 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1257 (let ((print-level nil
))
1258 (prin1-to-string (nth (1- pos
) history
)))
1259 (nth (1- pos
) history
)))
1262 (and (string-match regexp match-string
)
1264 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1265 (match-beginning 1))))
1267 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1268 (setq minibuffer-history-position pos
)
1269 (goto-char (point-max))
1270 (delete-minibuffer-contents)
1271 (insert match-string
)
1272 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1273 (if (memq (car (car command-history
)) '(previous-matching-history-element
1274 next-matching-history-element
))
1275 (setq command-history
(cdr command-history
))))
1277 (defun next-matching-history-element (regexp n
)
1278 "Find the next history element that matches REGEXP.
1279 \(The next history element refers to a more recent action.)
1280 With prefix argument N, search for Nth next match.
1281 If N is negative, find the previous or Nth previous match.
1282 Normally, history elements are matched case-insensitively if
1283 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1284 makes the search case-sensitive."
1286 (let* ((enable-recursive-minibuffers t
)
1287 (regexp (read-from-minibuffer "Next element matching (regexp): "
1289 minibuffer-local-map
1291 'minibuffer-history-search-history
1292 (car minibuffer-history-search-history
))))
1293 ;; Use the last regexp specified, by default, if input is empty.
1294 (list (if (string= regexp
"")
1295 (if minibuffer-history-search-history
1296 (car minibuffer-history-search-history
)
1297 (error "No previous history search regexp"))
1299 (prefix-numeric-value current-prefix-arg
))))
1300 (previous-matching-history-element regexp
(- n
)))
1302 (defvar minibuffer-temporary-goal-position nil
)
1304 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
1305 "Function run by `goto-history-element' before consuming `minibuffer-default'.
1306 This is useful to dynamically add more elements to the list `minibuffer-default'
1307 when `goto-history-element' reaches the end of this list.
1308 Before calling this function `goto-history-element' sets the variable
1309 `minibuffer-default-add-done' to t, so it will call this function only
1310 once. In special cases, when this function needs to be called more
1311 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1312 overriding the setting of this variable to t in `goto-history-element'.")
1314 (defvar minibuffer-default-add-done nil
1315 "When nil, add more elements to the end of the list of default values.
1316 The value nil causes `goto-history-element' to add more elements to
1317 the list of defaults when it reaches the end of this list. It does
1318 this by calling a function defined by `minibuffer-default-add-function'.")
1320 (make-variable-buffer-local 'minibuffer-default-add-done
)
1322 (defun minibuffer-default-add-completions ()
1323 "Return a list of all completions without the default value.
1324 This function is used to add all elements of the completion table to
1325 the end of the list of defaults just after the default value."
1327 (let ((def minibuffer-default
)
1328 (all (all-completions ""
1329 minibuffer-completion-table
1330 minibuffer-completion-predicate
1334 (cons def
(delete def all
)))))
1336 (defun goto-history-element (nabs)
1337 "Puts element of the minibuffer history in the minibuffer.
1338 The argument NABS specifies the absolute history position."
1340 (when (and (not minibuffer-default-add-done
)
1341 (functionp minibuffer-default-add-function
)
1342 (< nabs
(- (if (listp minibuffer-default
)
1343 (length minibuffer-default
)
1345 (setq minibuffer-default-add-done t
1346 minibuffer-default
(funcall minibuffer-default-add-function
)))
1347 (let ((minimum (if minibuffer-default
1348 (- (if (listp minibuffer-default
)
1349 (length minibuffer-default
)
1352 elt minibuffer-returned-to-present
)
1353 (if (and (zerop minibuffer-history-position
)
1354 (null minibuffer-text-before-history
))
1355 (setq minibuffer-text-before-history
1356 (minibuffer-contents-no-properties)))
1357 (if (< nabs minimum
)
1358 (if minibuffer-default
1359 (error "End of defaults; no next item")
1360 (error "End of history; no default available")))
1361 (if (> nabs
(length (symbol-value minibuffer-history-variable
)))
1362 (error "Beginning of history; no preceding item"))
1363 (unless (memq last-command
'(next-history-element
1364 previous-history-element
))
1365 (let ((prompt-end (minibuffer-prompt-end)))
1366 (set (make-local-variable 'minibuffer-temporary-goal-position
)
1367 (cond ((<= (point) prompt-end
) prompt-end
)
1370 (goto-char (point-max))
1371 (delete-minibuffer-contents)
1372 (setq minibuffer-history-position nabs
)
1374 (setq elt
(if (listp minibuffer-default
)
1375 (nth (1- (abs nabs
)) minibuffer-default
)
1376 minibuffer-default
)))
1378 (setq elt
(or minibuffer-text-before-history
""))
1379 (setq minibuffer-returned-to-present t
)
1380 (setq minibuffer-text-before-history nil
))
1381 (t (setq elt
(nth (1- minibuffer-history-position
)
1382 (symbol-value minibuffer-history-variable
)))))
1384 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1385 (not minibuffer-returned-to-present
))
1386 (let ((print-level nil
))
1387 (prin1-to-string elt
))
1389 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
1391 (defun next-history-element (n)
1392 "Puts next element of the minibuffer history in the minibuffer.
1393 With argument N, it uses the Nth following element."
1396 (goto-history-element (- minibuffer-history-position n
))))
1398 (defun previous-history-element (n)
1399 "Puts previous element of the minibuffer history in the minibuffer.
1400 With argument N, it uses the Nth previous element."
1403 (goto-history-element (+ minibuffer-history-position n
))))
1405 (defun next-complete-history-element (n)
1406 "Get next history element which completes the minibuffer before the point.
1407 The contents of the minibuffer after the point are deleted, and replaced
1408 by the new completion."
1410 (let ((point-at-start (point)))
1411 (next-matching-history-element
1413 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1415 ;; next-matching-history-element always puts us at (point-min).
1416 ;; Move to the position we were at before changing the buffer contents.
1417 ;; This is still sensical, because the text before point has not changed.
1418 (goto-char point-at-start
)))
1420 (defun previous-complete-history-element (n)
1422 Get previous history element which completes the minibuffer before the point.
1423 The contents of the minibuffer after the point are deleted, and replaced
1424 by the new completion."
1426 (next-complete-history-element (- n
)))
1428 ;; For compatibility with the old subr of the same name.
1429 (defun minibuffer-prompt-width ()
1430 "Return the display width of the minibuffer prompt.
1431 Return 0 if current buffer is not a minibuffer."
1432 ;; Return the width of everything before the field at the end of
1433 ;; the buffer; this should be 0 for normal buffers.
1434 (1- (minibuffer-prompt-end)))
1436 ;; isearch minibuffer history
1437 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
1439 (defvar minibuffer-history-isearch-message-overlay
)
1440 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
1442 (defun minibuffer-history-isearch-setup ()
1443 "Set up a minibuffer for using isearch to search the minibuffer history.
1444 Intended to be added to `minibuffer-setup-hook'."
1445 (set (make-local-variable 'isearch-search-fun-function
)
1446 'minibuffer-history-isearch-search
)
1447 (set (make-local-variable 'isearch-message-function
)
1448 'minibuffer-history-isearch-message
)
1449 (set (make-local-variable 'isearch-wrap-function
)
1450 'minibuffer-history-isearch-wrap
)
1451 (set (make-local-variable 'isearch-push-state-function
)
1452 'minibuffer-history-isearch-push-state
)
1453 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
1455 (defun minibuffer-history-isearch-end ()
1456 "Clean up the minibuffer after terminating isearch in the minibuffer."
1457 (if minibuffer-history-isearch-message-overlay
1458 (delete-overlay minibuffer-history-isearch-message-overlay
)))
1460 (defun minibuffer-history-isearch-search ()
1461 "Return the proper search function, for isearch in minibuffer history."
1464 (if isearch-forward
'word-search-forward
'word-search-backward
))
1466 (lambda (string bound noerror
)
1468 ;; Use standard functions to search within minibuffer text
1471 (if isearch-forward
're-search-forward
're-search-backward
))
1473 (if isearch-forward
'search-forward
'search-backward
))))
1475 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1476 ;; searching forward. Lazy-highlight calls this lambda with the
1477 ;; bound arg, so skip the minibuffer prompt.
1478 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
1479 (goto-char (minibuffer-prompt-end)))
1481 ;; 1. First try searching in the initial minibuffer text
1482 (funcall search-fun string
1483 (if isearch-forward bound
(minibuffer-prompt-end))
1485 ;; 2. If the above search fails, start putting next/prev history
1486 ;; elements in the minibuffer successively, and search the string
1487 ;; in them. Do this only when bound is nil (i.e. not while
1488 ;; lazy-highlighting search strings in the current minibuffer text).
1493 (cond (isearch-forward
1494 (next-history-element 1)
1495 (goto-char (minibuffer-prompt-end)))
1497 (previous-history-element 1)
1498 (goto-char (point-max))))
1499 (setq isearch-barrier
(point) isearch-opoint
(point))
1500 ;; After putting the next/prev history element, search
1501 ;; the string in them again, until next-history-element
1502 ;; or previous-history-element raises an error at the
1503 ;; beginning/end of history.
1504 (setq found
(funcall search-fun string
1505 (unless isearch-forward
1506 ;; For backward search, don't search
1507 ;; in the minibuffer prompt
1508 (minibuffer-prompt-end))
1510 ;; Return point of the new search result
1512 ;; Return nil when next(prev)-history-element fails
1515 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
1516 "Display the minibuffer history search prompt.
1517 If there are no search errors, this function displays an overlay with
1518 the isearch prompt which replaces the original minibuffer prompt.
1519 Otherwise, it displays the standard isearch message returned from
1521 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
1522 ;; Use standard function `isearch-message' when not in the minibuffer,
1523 ;; or search fails, or has an error (like incomplete regexp).
1524 ;; This function overwrites minibuffer text with isearch message,
1525 ;; so it's possible to see what is wrong in the search string.
1526 (isearch-message c-q-hack ellipsis
)
1527 ;; Otherwise, put the overlay with the standard isearch prompt over
1528 ;; the initial minibuffer prompt.
1529 (if (overlayp minibuffer-history-isearch-message-overlay
)
1530 (move-overlay minibuffer-history-isearch-message-overlay
1531 (point-min) (minibuffer-prompt-end))
1532 (setq minibuffer-history-isearch-message-overlay
1533 (make-overlay (point-min) (minibuffer-prompt-end)))
1534 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
1535 (overlay-put minibuffer-history-isearch-message-overlay
1536 'display
(isearch-message-prefix c-q-hack ellipsis
))
1537 ;; And clear any previous isearch message.
1540 (defun minibuffer-history-isearch-wrap ()
1541 "Wrap the minibuffer history search when search is failed.
1542 Move point to the first history element for a forward search,
1543 or to the last history element for a backward search."
1544 (unless isearch-word
1545 ;; When `minibuffer-history-isearch-search' fails on reaching the
1546 ;; beginning/end of the history, wrap the search to the first/last
1547 ;; minibuffer history element.
1549 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
1550 (goto-history-element 0))
1551 (setq isearch-success t
))
1552 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
1554 (defun minibuffer-history-isearch-push-state ()
1555 "Save a function restoring the state of minibuffer history search.
1556 Save `minibuffer-history-position' to the additional state parameter
1557 in the search status stack."
1559 (minibuffer-history-isearch-pop-state cmd
,minibuffer-history-position
)))
1561 (defun minibuffer-history-isearch-pop-state (cmd hist-pos
)
1562 "Restore the minibuffer history search state.
1563 Go to the history element by the absolute history position `hist-pos'."
1564 (goto-history-element hist-pos
))
1567 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1568 (defalias 'advertised-undo
'undo
)
1570 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
1571 "Table mapping redo records to the corresponding undo one.
1572 A redo record for undo-in-region maps to t.
1573 A redo record for ordinary undo maps to the following (earlier) undo.")
1575 (defvar undo-in-region nil
1576 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1578 (defvar undo-no-redo nil
1579 "If t, `undo' doesn't go through redo entries.")
1581 (defvar pending-undo-list nil
1582 "Within a run of consecutive undo commands, list remaining to be undone.
1583 If t, we undid all the way to the end of it.")
1585 (defun undo (&optional arg
)
1586 "Undo some previous changes.
1587 Repeat this command to undo more changes.
1588 A numeric argument serves as a repeat count.
1590 In Transient Mark mode when the mark is active, only undo changes within
1591 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1592 as an argument limits undo to changes within the current region."
1594 ;; Make last-command indicate for the next command that this was an undo.
1595 ;; That way, another undo will undo more.
1596 ;; If we get to the end of the undo history and get an error,
1597 ;; another undo command will find the undo history empty
1598 ;; and will get another error. To begin undoing the undos,
1599 ;; you must type some other command.
1600 (let ((modified (buffer-modified-p))
1601 (recent-save (recent-auto-save-p))
1603 ;; If we get an error in undo-start,
1604 ;; the next command should not be a "consecutive undo".
1605 ;; So set `this-command' to something other than `undo'.
1606 (setq this-command
'undo-start
)
1608 (unless (and (eq last-command
'undo
)
1609 (or (eq pending-undo-list t
)
1610 ;; If something (a timer or filter?) changed the buffer
1611 ;; since the previous command, don't continue the undo seq.
1612 (let ((list buffer-undo-list
))
1613 (while (eq (car list
) nil
)
1614 (setq list
(cdr list
)))
1615 ;; If the last undo record made was made by undo
1616 ;; it shows nothing else happened in between.
1617 (gethash list undo-equiv-table
))))
1618 (setq undo-in-region
1619 (or (region-active-p) (and arg
(not (numberp arg
)))))
1621 (undo-start (region-beginning) (region-end))
1623 ;; get rid of initial undo boundary
1625 ;; If we got this far, the next command should be a consecutive undo.
1626 (setq this-command
'undo
)
1627 ;; Check to see whether we're hitting a redo record, and if
1628 ;; so, ask the user whether she wants to skip the redo/undo pair.
1629 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
1630 (or (eq (selected-window) (minibuffer-window))
1631 (setq message
(if undo-in-region
1632 (if equiv
"Redo in region!" "Undo in region!")
1633 (if equiv
"Redo!" "Undo!"))))
1634 (when (and (consp equiv
) undo-no-redo
)
1635 ;; The equiv entry might point to another redo record if we have done
1636 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1637 (while (let ((next (gethash equiv undo-equiv-table
)))
1638 (if next
(setq equiv next
))))
1639 (setq pending-undo-list equiv
)))
1642 (prefix-numeric-value arg
)
1644 ;; Record the fact that the just-generated undo records come from an
1645 ;; undo operation--that is, they are redo records.
1646 ;; In the ordinary case (not within a region), map the redo
1647 ;; record to the following undos.
1648 ;; I don't know how to do that in the undo-in-region case.
1649 (puthash buffer-undo-list
1650 (if undo-in-region t pending-undo-list
)
1652 ;; Don't specify a position in the undo record for the undo command.
1653 ;; Instead, undoing this should move point to where the change is.
1654 (let ((tail buffer-undo-list
)
1657 (when (integerp (car tail
))
1658 (let ((pos (car tail
)))
1660 (setcdr prev
(cdr tail
))
1661 (setq buffer-undo-list
(cdr tail
)))
1662 (setq tail
(cdr tail
))
1664 (if (eq pos
(car tail
))
1666 (setcdr prev
(cdr tail
))
1667 (setq buffer-undo-list
(cdr tail
)))
1669 (setq tail
(cdr tail
)))
1671 (setq prev tail tail
(cdr tail
))))
1672 ;; Record what the current undo list says,
1673 ;; so the next command can tell if the buffer was modified in between.
1674 (and modified
(not (buffer-modified-p))
1675 (delete-auto-save-file-if-necessary recent-save
))
1676 ;; Display a message announcing success.
1678 (message "%s" message
))))
1680 (defun buffer-disable-undo (&optional buffer
)
1681 "Make BUFFER stop keeping undo information.
1682 No argument or nil as argument means do this for the current buffer."
1684 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
1685 (setq buffer-undo-list t
)))
1687 (defun undo-only (&optional arg
)
1688 "Undo some previous changes.
1689 Repeat this command to undo more changes.
1690 A numeric argument serves as a repeat count.
1691 Contrary to `undo', this will not redo a previous undo."
1693 (let ((undo-no-redo t
)) (undo arg
)))
1695 (defvar undo-in-progress nil
1696 "Non-nil while performing an undo.
1697 Some change-hooks test this variable to do something different.")
1699 (defun undo-more (n)
1700 "Undo back N undo-boundaries beyond what was already undone recently.
1701 Call `undo-start' to get ready to undo recent changes,
1702 then call `undo-more' one or more times to undo them."
1703 (or (listp pending-undo-list
)
1704 (error (concat "No further undo information"
1705 (and undo-in-region
" for region"))))
1706 (let ((undo-in-progress t
))
1707 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
1708 (if (null pending-undo-list
)
1709 (setq pending-undo-list t
))))
1711 ;; Deep copy of a list
1712 (defun undo-copy-list (list)
1713 "Make a copy of undo list LIST."
1714 (mapcar 'undo-copy-list-1 list
))
1716 (defun undo-copy-list-1 (elt)
1718 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
1721 (defun undo-start (&optional beg end
)
1722 "Set `pending-undo-list' to the front of the undo list.
1723 The next call to `undo-more' will undo the most recently made change.
1724 If BEG and END are specified, then only undo elements
1725 that apply to text between BEG and END are used; other undo elements
1726 are ignored. If BEG and END are nil, all undo elements are used."
1727 (if (eq buffer-undo-list t
)
1728 (error "No undo information in this buffer"))
1729 (setq pending-undo-list
1730 (if (and beg end
(not (= beg end
)))
1731 (undo-make-selective-list (min beg end
) (max beg end
))
1734 (defvar undo-adjusted-markers
)
1736 (defun undo-make-selective-list (start end
)
1737 "Return a list of undo elements for the region START to END.
1738 The elements come from `buffer-undo-list', but we keep only
1739 the elements inside this region, and discard those outside this region.
1740 If we find an element that crosses an edge of this region,
1741 we stop and ignore all further elements."
1742 (let ((undo-list-copy (undo-copy-list buffer-undo-list
))
1743 (undo-list (list nil
))
1744 undo-adjusted-markers
1746 undo-elt undo-elt temp-undo-list delta
)
1747 (while undo-list-copy
1748 (setq undo-elt
(car undo-list-copy
))
1750 (cond ((and (consp undo-elt
) (eq (car undo-elt
) t
))
1751 ;; This is a "was unmodified" element.
1752 ;; Keep it if we have kept everything thus far.
1753 (not some-rejected
))
1755 (undo-elt-in-region undo-elt start end
)))))
1758 (setq end
(+ end
(cdr (undo-delta undo-elt
))))
1759 ;; Don't put two nils together in the list
1760 (if (not (and (eq (car undo-list
) nil
)
1762 (setq undo-list
(cons undo-elt undo-list
))))
1763 (if (undo-elt-crosses-region undo-elt start end
)
1764 (setq undo-list-copy nil
)
1765 (setq some-rejected t
)
1766 (setq temp-undo-list
(cdr undo-list-copy
))
1767 (setq delta
(undo-delta undo-elt
))
1769 (when (/= (cdr delta
) 0)
1770 (let ((position (car delta
))
1771 (offset (cdr delta
)))
1773 ;; Loop down the earlier events adjusting their buffer
1774 ;; positions to reflect the fact that a change to the buffer
1775 ;; isn't being undone. We only need to process those element
1776 ;; types which undo-elt-in-region will return as being in
1777 ;; the region since only those types can ever get into the
1780 (while temp-undo-list
1781 (setq undo-elt
(car temp-undo-list
))
1782 (cond ((integerp undo-elt
)
1783 (if (>= undo-elt position
)
1784 (setcar temp-undo-list
(- undo-elt offset
))))
1785 ((atom undo-elt
) nil
)
1786 ((stringp (car undo-elt
))
1787 ;; (TEXT . POSITION)
1788 (let ((text-pos (abs (cdr undo-elt
)))
1789 (point-at-end (< (cdr undo-elt
) 0 )))
1790 (if (>= text-pos position
)
1791 (setcdr undo-elt
(* (if point-at-end -
1 1)
1792 (- text-pos offset
))))))
1793 ((integerp (car undo-elt
))
1795 (when (>= (car undo-elt
) position
)
1796 (setcar undo-elt
(- (car undo-elt
) offset
))
1797 (setcdr undo-elt
(- (cdr undo-elt
) offset
))))
1798 ((null (car undo-elt
))
1799 ;; (nil PROPERTY VALUE BEG . END)
1800 (let ((tail (nthcdr 3 undo-elt
)))
1801 (when (>= (car tail
) position
)
1802 (setcar tail
(- (car tail
) offset
))
1803 (setcdr tail
(- (cdr tail
) offset
))))))
1804 (setq temp-undo-list
(cdr temp-undo-list
))))))))
1805 (setq undo-list-copy
(cdr undo-list-copy
)))
1806 (nreverse undo-list
)))
1808 (defun undo-elt-in-region (undo-elt start end
)
1809 "Determine whether UNDO-ELT falls inside the region START ... END.
1810 If it crosses the edge, we return nil."
1811 (cond ((integerp undo-elt
)
1812 (and (>= undo-elt start
)
1818 ((stringp (car undo-elt
))
1819 ;; (TEXT . POSITION)
1820 (and (>= (abs (cdr undo-elt
)) start
)
1821 (< (abs (cdr undo-elt
)) end
)))
1822 ((and (consp undo-elt
) (markerp (car undo-elt
)))
1823 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1824 ;; See if MARKER is inside the region.
1825 (let ((alist-elt (assq (car undo-elt
) undo-adjusted-markers
)))
1827 (setq alist-elt
(cons (car undo-elt
)
1828 (marker-position (car undo-elt
))))
1829 (setq undo-adjusted-markers
1830 (cons alist-elt undo-adjusted-markers
)))
1831 (and (cdr alist-elt
)
1832 (>= (cdr alist-elt
) start
)
1833 (<= (cdr alist-elt
) end
))))
1834 ((null (car undo-elt
))
1835 ;; (nil PROPERTY VALUE BEG . END)
1836 (let ((tail (nthcdr 3 undo-elt
)))
1837 (and (>= (car tail
) start
)
1838 (<= (cdr tail
) end
))))
1839 ((integerp (car undo-elt
))
1841 (and (>= (car undo-elt
) start
)
1842 (<= (cdr undo-elt
) end
)))))
1844 (defun undo-elt-crosses-region (undo-elt start end
)
1845 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1846 This assumes we have already decided that UNDO-ELT
1847 is not *inside* the region START...END."
1848 (cond ((atom undo-elt
) nil
)
1849 ((null (car undo-elt
))
1850 ;; (nil PROPERTY VALUE BEG . END)
1851 (let ((tail (nthcdr 3 undo-elt
)))
1852 (and (< (car tail
) end
)
1853 (> (cdr tail
) start
))))
1854 ((integerp (car undo-elt
))
1856 (and (< (car undo-elt
) end
)
1857 (> (cdr undo-elt
) start
)))))
1859 ;; Return the first affected buffer position and the delta for an undo element
1860 ;; delta is defined as the change in subsequent buffer positions if we *did*
1862 (defun undo-delta (undo-elt)
1863 (if (consp undo-elt
)
1864 (cond ((stringp (car undo-elt
))
1865 ;; (TEXT . POSITION)
1866 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
1867 ((integerp (car undo-elt
))
1869 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
1874 (defcustom undo-ask-before-discard nil
1875 "If non-nil ask about discarding undo info for the current command.
1876 Normally, Emacs discards the undo info for the current command if
1877 it exceeds `undo-outer-limit'. But if you set this option
1878 non-nil, it asks in the echo area whether to discard the info.
1879 If you answer no, there is a slight risk that Emacs might crash, so
1880 only do it if you really want to undo the command.
1882 This option is mainly intended for debugging. You have to be
1883 careful if you use it for other purposes. Garbage collection is
1884 inhibited while the question is asked, meaning that Emacs might
1885 leak memory. So you should make sure that you do not wait
1886 excessively long before answering the question."
1891 (defvar undo-extra-outer-limit nil
1892 "If non-nil, an extra level of size that's ok in an undo item.
1893 We don't ask the user about truncating the undo list until the
1894 current item gets bigger than this amount.
1896 This variable only matters if `undo-ask-before-discard' is non-nil.")
1897 (make-variable-buffer-local 'undo-extra-outer-limit
)
1899 ;; When the first undo batch in an undo list is longer than
1900 ;; undo-outer-limit, this function gets called to warn the user that
1901 ;; the undo info for the current command was discarded. Garbage
1902 ;; collection is inhibited around the call, so it had better not do a
1904 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
1905 (defun undo-outer-limit-truncate (size)
1906 (if undo-ask-before-discard
1907 (when (or (null undo-extra-outer-limit
)
1908 (> size undo-extra-outer-limit
))
1909 ;; Don't ask the question again unless it gets even bigger.
1910 ;; This applies, in particular, if the user quits from the question.
1911 ;; Such a quit quits out of GC, but something else will call GC
1912 ;; again momentarily. It will call this function again,
1913 ;; but we don't want to ask the question again.
1914 (setq undo-extra-outer-limit
(+ size
50000))
1915 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
1916 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
1917 (buffer-name) size
)))
1918 (progn (setq buffer-undo-list nil
)
1919 (setq undo-extra-outer-limit nil
)
1922 (display-warning '(undo discard-info
)
1924 (format "Buffer `%s' undo info was %d bytes long.\n"
1926 "The undo info was discarded because it exceeded \
1929 This is normal if you executed a command that made a huge change
1930 to the buffer. In that case, to prevent similar problems in the
1931 future, set `undo-outer-limit' to a value that is large enough to
1932 cover the maximum size of normal changes you expect a single
1933 command to make, but not so large that it might exceed the
1934 maximum memory allotted to Emacs.
1936 If you did not execute any such command, the situation is
1937 probably due to a bug and you should report it.
1939 You can disable the popping up of this buffer by adding the entry
1940 \(undo discard-info) to the user option `warning-suppress-types'.\n")
1942 (setq buffer-undo-list nil
)
1945 (defvar shell-command-history nil
1946 "History list for some commands that read shell commands.
1948 Maximum length of the history list is determined by the value
1949 of `history-length', which see.")
1951 (defvar shell-command-switch
"-c"
1952 "Switch used to have the shell execute its command line argument.")
1954 (defvar shell-command-default-error-buffer nil
1955 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1956 This buffer is used when `shell-command' or `shell-command-on-region'
1957 is run interactively. A value of nil means that output to stderr and
1958 stdout will be intermixed in the output stream.")
1960 (defun minibuffer-complete-shell-command ()
1961 "Dynamically complete shell command at point."
1964 (run-hook-with-args-until-success 'shell-dynamic-complete-functions
))
1966 (defvar minibuffer-local-shell-command-map
1967 (let ((map (make-sparse-keymap)))
1968 (set-keymap-parent map minibuffer-local-map
)
1969 (define-key map
"\t" 'minibuffer-complete-shell-command
)
1971 "Keymap used for completiing shell commands in minibufffer.")
1973 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
1974 "Read a shell command from the minibuffer.
1975 The arguments are the same as the ones of `read-from-minibuffer',
1976 except READ and KEYMAP are missing and HIST defaults
1977 to `shell-command-history'."
1978 (apply 'read-from-minibuffer prompt initial-contents
1979 minibuffer-local-shell-command-map
1981 (or hist
'shell-command-history
)
1984 (defun shell-command (command &optional output-buffer error-buffer
)
1985 "Execute string COMMAND in inferior shell; display output, if any.
1986 With prefix argument, insert the COMMAND's output at point.
1988 If COMMAND ends in ampersand, execute it asynchronously.
1989 The output appears in the buffer `*Async Shell Command*'.
1990 That buffer is in shell mode.
1992 Otherwise, COMMAND is executed synchronously. The output appears in
1993 the buffer `*Shell Command Output*'. If the output is short enough to
1994 display in the echo area (which is determined by the variables
1995 `resize-mini-windows' and `max-mini-window-height'), it is shown
1996 there, but it is nonetheless available in buffer `*Shell Command
1997 Output*' even though that buffer is not automatically displayed.
1999 To specify a coding system for converting non-ASCII characters
2000 in the shell command output, use \\[universal-coding-system-argument]
2001 before this command.
2003 Noninteractive callers can specify coding systems by binding
2004 `coding-system-for-read' and `coding-system-for-write'.
2006 The optional second argument OUTPUT-BUFFER, if non-nil,
2007 says to put the output in some other buffer.
2008 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2009 If OUTPUT-BUFFER is not a buffer and not nil,
2010 insert output in current buffer. (This cannot be done asynchronously.)
2011 In either case, the output is inserted after point (leaving mark after it).
2013 If the command terminates without error, but generates output,
2014 and you did not specify \"insert it in the current buffer\",
2015 the output can be displayed in the echo area or in its buffer.
2016 If the output is short enough to display in the echo area
2017 \(determined by the variable `max-mini-window-height' if
2018 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
2019 the buffer containing the output is displayed.
2021 If there is output and an error, and you did not specify \"insert it
2022 in the current buffer\", a message about the error goes at the end
2025 If there is no output, or if output is inserted in the current buffer,
2026 then `*Shell Command Output*' is deleted.
2028 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2029 or buffer name to which to direct the command's standard error output.
2030 If it is nil, error output is mingled with regular output.
2031 In an interactive call, the variable `shell-command-default-error-buffer'
2032 specifies the value of ERROR-BUFFER."
2034 (interactive (list (read-shell-command "Shell command: ")
2036 shell-command-default-error-buffer
))
2037 ;; Look for a handler in case default-directory is a remote file name.
2039 (find-file-name-handler (directory-file-name default-directory
)
2042 (funcall handler
'shell-command command output-buffer error-buffer
)
2043 (if (and output-buffer
2044 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
2045 ;; Output goes in current buffer.
2049 (expand-file-name "scor"
2050 (or small-temporary-file-directory
2051 temporary-file-directory
)))
2053 (barf-if-buffer-read-only)
2055 ;; We do not use -f for csh; we will not support broken use of
2056 ;; .cshrcs. Even the BSD csh manual says to use
2057 ;; "if ($?prompt) exit" before things which are not useful
2058 ;; non-interactively. Besides, if someone wants their other
2059 ;; aliases for shell commands then they can still have them.
2060 (call-process shell-file-name nil
2064 nil shell-command-switch command
)
2065 (when (and error-file
(file-exists-p error-file
))
2066 (if (< 0 (nth 7 (file-attributes error-file
)))
2067 (with-current-buffer (get-buffer-create error-buffer
)
2068 (let ((pos-from-end (- (point-max) (point))))
2071 ;; Do no formatting while reading error file,
2072 ;; because that can run a shell command, and we
2073 ;; don't want that to cause an infinite recursion.
2074 (format-insert-file error-file nil
)
2075 ;; Put point after the inserted errors.
2076 (goto-char (- (point-max) pos-from-end
)))
2077 (display-buffer (current-buffer))))
2078 (delete-file error-file
))
2079 ;; This is like exchange-point-and-mark, but doesn't
2080 ;; activate the mark. It is cleaner to avoid activation,
2081 ;; even though the command loop would deactivate the mark
2082 ;; because we inserted text.
2083 (goto-char (prog1 (mark t
)
2084 (set-marker (mark-marker) (point)
2085 (current-buffer)))))
2086 ;; Output goes in a separate buffer.
2087 ;; Preserve the match data in case called from a program.
2089 (if (string-match "[ \t]*&[ \t]*\\'" command
)
2090 ;; Command ending with ampersand means asynchronous.
2091 (let ((buffer (get-buffer-create
2092 (or output-buffer
"*Async Shell Command*")))
2093 (directory default-directory
)
2095 ;; Remove the ampersand.
2096 (setq command
(substring command
0 (match-beginning 0)))
2097 ;; If will kill a process, query first.
2098 (setq proc
(get-buffer-process buffer
))
2100 (if (yes-or-no-p "A command is running. Kill it? ")
2102 (error "Shell command in progress")))
2103 (with-current-buffer buffer
2104 (setq buffer-read-only nil
)
2106 (display-buffer buffer
)
2107 (setq default-directory directory
)
2108 (setq proc
(start-process "Shell" buffer shell-file-name
2109 shell-command-switch command
))
2110 (setq mode-line-process
'(":%s"))
2111 (require 'shell
) (shell-mode)
2112 (set-process-sentinel proc
'shell-command-sentinel
)
2114 (shell-command-on-region (point) (point) command
2115 output-buffer nil error-buffer
)))))))
2117 (defun display-message-or-buffer (message
2118 &optional buffer-name not-this-window frame
)
2119 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2120 MESSAGE may be either a string or a buffer.
2122 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2123 the maximum height of the echo area, as defined by `max-mini-window-height'
2124 if `resize-mini-windows' is non-nil.
2126 Returns either the string shown in the echo area, or when a pop-up
2127 buffer is used, the window used to display it.
2129 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2130 name of the buffer used to display it in the case where a pop-up buffer
2131 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2132 string and it is displayed in the echo area, it is not specified whether
2133 the contents are inserted into the buffer anyway.
2135 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2136 and only used if a buffer is displayed."
2137 (cond ((and (stringp message
) (not (string-match "\n" message
)))
2138 ;; Trivial case where we can use the echo area
2139 (message "%s" message
))
2140 ((and (stringp message
)
2141 (= (string-match "\n" message
) (1- (length message
))))
2142 ;; Trivial case where we can just remove single trailing newline
2143 (message "%s" (substring message
0 (1- (length message
)))))
2146 (with-current-buffer
2147 (if (bufferp message
)
2149 (get-buffer-create (or buffer-name
"*Message*")))
2151 (unless (bufferp message
)
2156 (if (= (buffer-size) 0)
2158 (count-screen-lines nil nil nil
(minibuffer-window)))))
2160 ((and (or (<= lines
1)
2162 (if resize-mini-windows
2163 (cond ((floatp max-mini-window-height
)
2165 max-mini-window-height
))
2166 ((integerp max-mini-window-height
)
2167 max-mini-window-height
)
2171 ;; Don't use the echo area if the output buffer is
2172 ;; already dispayed in the selected frame.
2173 (not (get-buffer-window (current-buffer))))
2175 (goto-char (point-max))
2178 (message "%s" (buffer-substring (point-min) (point))))
2181 (goto-char (point-min))
2182 (display-buffer (current-buffer)
2183 not-this-window frame
))))))))
2186 ;; We have a sentinel to prevent insertion of a termination message
2187 ;; in the buffer itself.
2188 (defun shell-command-sentinel (process signal
)
2189 (if (memq (process-status process
) '(exit signal
))
2191 (car (cdr (cdr (process-command process
))))
2192 (substring signal
0 -
1))))
2194 (defun shell-command-on-region (start end command
2195 &optional output-buffer replace
2196 error-buffer display-error-buffer
)
2197 "Execute string COMMAND in inferior shell with region as input.
2198 Normally display output (if any) in temp buffer `*Shell Command Output*';
2199 Prefix arg means replace the region with it. Return the exit code of
2202 To specify a coding system for converting non-ASCII characters
2203 in the input and output to the shell command, use \\[universal-coding-system-argument]
2204 before this command. By default, the input (from the current buffer)
2205 is encoded in the same coding system that will be used to save the file,
2206 `buffer-file-coding-system'. If the output is going to replace the region,
2207 then it is decoded from that same coding system.
2209 The noninteractive arguments are START, END, COMMAND,
2210 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2211 Noninteractive callers can specify coding systems by binding
2212 `coding-system-for-read' and `coding-system-for-write'.
2214 If the command generates output, the output may be displayed
2215 in the echo area or in a buffer.
2216 If the output is short enough to display in the echo area
2217 \(determined by the variable `max-mini-window-height' if
2218 `resize-mini-windows' is non-nil), it is shown there. Otherwise
2219 it is displayed in the buffer `*Shell Command Output*'. The output
2220 is available in that buffer in both cases.
2222 If there is output and an error, a message about the error
2223 appears at the end of the output.
2225 If there is no output, or if output is inserted in the current buffer,
2226 then `*Shell Command Output*' is deleted.
2228 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2229 that says to put the output in some other buffer.
2230 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2231 If OUTPUT-BUFFER is not a buffer and not nil,
2232 insert output in the current buffer.
2233 In either case, the output is inserted after point (leaving mark after it).
2235 If REPLACE, the optional fifth argument, is non-nil, that means insert
2236 the output in place of text from START to END, putting point and mark
2239 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2240 or buffer name to which to direct the command's standard error output.
2241 If it is nil, error output is mingled with regular output.
2242 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2243 were any errors. (This is always t, interactively.)
2244 In an interactive call, the variable `shell-command-default-error-buffer'
2245 specifies the value of ERROR-BUFFER."
2246 (interactive (let (string)
2248 (error "The mark is not set now, so there is no region"))
2249 ;; Do this before calling region-beginning
2250 ;; and region-end, in case subprocess output
2251 ;; relocates them while we are in the minibuffer.
2252 (setq string
(read-shell-command "Shell command on region: "))
2253 ;; call-interactively recognizes region-beginning and
2254 ;; region-end specially, leaving them in the history.
2255 (list (region-beginning) (region-end)
2259 shell-command-default-error-buffer
2264 (expand-file-name "scor"
2265 (or small-temporary-file-directory
2266 temporary-file-directory
)))
2271 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
2272 ;; Replace specified region with output from command.
2273 (let ((swap (and replace
(< start end
))))
2274 ;; Don't muck with mark unless REPLACE says we should.
2276 (and replace
(push-mark (point) 'nomsg
))
2278 (call-process-region start end shell-file-name t
2282 nil shell-command-switch command
))
2283 ;; It is rude to delete a buffer which the command is not using.
2284 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2285 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2286 ;; (kill-buffer shell-buffer)))
2287 ;; Don't muck with mark unless REPLACE says we should.
2288 (and replace swap
(exchange-point-and-mark)))
2289 ;; No prefix argument: put the output in a temp buffer,
2290 ;; replacing its entire contents.
2291 (let ((buffer (get-buffer-create
2292 (or output-buffer
"*Shell Command Output*"))))
2294 (if (eq buffer
(current-buffer))
2295 ;; If the input is the same buffer as the output,
2296 ;; delete everything but the specified region,
2297 ;; then replace that region with the output.
2298 (progn (setq buffer-read-only nil
)
2299 (delete-region (max start end
) (point-max))
2300 (delete-region (point-min) (min start end
))
2302 (call-process-region (point-min) (point-max)
2307 nil shell-command-switch
2309 ;; Clear the output buffer, then run the command with
2311 (let ((directory default-directory
))
2314 (setq buffer-read-only nil
)
2315 (if (not output-buffer
)
2316 (setq default-directory directory
))
2319 (call-process-region start end shell-file-name nil
2321 (list buffer error-file
)
2323 nil shell-command-switch command
)))
2324 ;; Report the output.
2325 (with-current-buffer buffer
2326 (setq mode-line-process
2327 (cond ((null exit-status
)
2329 ((stringp exit-status
)
2330 (format " - Signal [%s]" exit-status
))
2331 ((not (equal 0 exit-status
))
2332 (format " - Exit [%d]" exit-status
)))))
2333 (if (with-current-buffer buffer
(> (point-max) (point-min)))
2334 ;; There's some output, display it
2335 (display-message-or-buffer buffer
)
2336 ;; No output; error?
2339 (< 0 (nth 7 (file-attributes error-file
))))
2342 (cond ((null exit-status
)
2343 (message "(Shell command failed with error)"))
2344 ((equal 0 exit-status
)
2345 (message "(Shell command succeeded with %s)"
2347 ((stringp exit-status
)
2348 (message "(Shell command killed by signal %s)"
2351 (message "(Shell command failed with code %d and %s)"
2352 exit-status output
))))
2353 ;; Don't kill: there might be useful info in the undo-log.
2354 ;; (kill-buffer buffer)
2357 (when (and error-file
(file-exists-p error-file
))
2358 (if (< 0 (nth 7 (file-attributes error-file
)))
2359 (with-current-buffer (get-buffer-create error-buffer
)
2360 (let ((pos-from-end (- (point-max) (point))))
2363 ;; Do no formatting while reading error file,
2364 ;; because that can run a shell command, and we
2365 ;; don't want that to cause an infinite recursion.
2366 (format-insert-file error-file nil
)
2367 ;; Put point after the inserted errors.
2368 (goto-char (- (point-max) pos-from-end
)))
2369 (and display-error-buffer
2370 (display-buffer (current-buffer)))))
2371 (delete-file error-file
))
2374 (defun shell-command-to-string (command)
2375 "Execute shell command COMMAND and return its output as a string."
2376 (with-output-to-string
2377 (with-current-buffer
2379 (call-process shell-file-name nil t nil shell-command-switch command
))))
2381 (defun process-file (program &optional infile buffer display
&rest args
)
2382 "Process files synchronously in a separate process.
2383 Similar to `call-process', but may invoke a file handler based on
2384 `default-directory'. The current working directory of the
2385 subprocess is `default-directory'.
2387 File names in INFILE and BUFFER are handled normally, but file
2388 names in ARGS should be relative to `default-directory', as they
2389 are passed to the process verbatim. \(This is a difference to
2390 `call-process' which does not support file handlers for INFILE
2393 Some file handlers might not support all variants, for example
2394 they might behave as if DISPLAY was nil, regardless of the actual
2396 (let ((fh (find-file-name-handler default-directory
'process-file
))
2399 (if fh
(apply fh
'process-file program infile buffer display args
)
2400 (when infile
(setq lc
(file-local-copy infile
)))
2401 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
2402 (make-temp-file "emacs")))
2404 (apply 'call-process program
2406 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
2408 (when stderr-file
(copy-file stderr-file
(cadr buffer
)))))
2409 (when stderr-file
(delete-file stderr-file
))
2410 (when lc
(delete-file lc
)))))
2412 (defun start-file-process (name buffer program
&rest program-args
)
2413 "Start a program in a subprocess. Return the process object for it.
2414 Similar to `start-process', but may invoke a file handler based on
2415 `default-directory'. The current working directory of the
2416 subprocess is `default-directory'.
2418 PROGRAM and PROGRAM-ARGS might be file names. They are not
2419 objects of file handler invocation."
2420 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
2421 (if fh
(apply fh
'start-file-process name buffer program program-args
)
2422 (apply 'start-process name buffer program program-args
))))
2426 (defvar universal-argument-map
2427 (let ((map (make-sparse-keymap)))
2428 (define-key map
[t] 'universal-argument-other-key)
2429 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2430 (define-key map [switch-frame] nil)
2431 (define-key map [?\C-u] 'universal-argument-more)
2432 (define-key map [?-] 'universal-argument-minus)
2433 (define-key map [?0] 'digit-argument)
2434 (define-key map [?1] 'digit-argument)
2435 (define-key map [?2] 'digit-argument)
2436 (define-key map [?3] 'digit-argument)
2437 (define-key map [?4] 'digit-argument)
2438 (define-key map [?5] 'digit-argument)
2439 (define-key map [?6] 'digit-argument)
2440 (define-key map [?7] 'digit-argument)
2441 (define-key map [?8] 'digit-argument)
2442 (define-key map [?9] 'digit-argument)
2443 (define-key map [kp-0] 'digit-argument)
2444 (define-key map [kp-1] 'digit-argument)
2445 (define-key map [kp-2] 'digit-argument)
2446 (define-key map [kp-3] 'digit-argument)
2447 (define-key map [kp-4] 'digit-argument)
2448 (define-key map [kp-5] 'digit-argument)
2449 (define-key map [kp-6] 'digit-argument)
2450 (define-key map [kp-7] 'digit-argument)
2451 (define-key map [kp-8] 'digit-argument)
2452 (define-key map [kp-9] 'digit-argument)
2453 (define-key map [kp-subtract] 'universal-argument-minus)
2455 "Keymap used while processing \\[universal-argument].")
2457 (defvar universal-argument-num-events nil
2458 "Number of argument-specifying events read by `universal-argument'.
2459 `universal-argument-other-key' uses this to discard those events
2460 from (this-command-keys), and reread only the final command.")
2462 (defvar overriding-map-is-bound nil
2463 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2465 (defvar saved-overriding-map nil
2466 "The saved value of `overriding-terminal-local-map'.
2467 That variable gets restored to this value on exiting \"universal
2470 (defun ensure-overriding-map-is-bound ()
2471 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2472 (unless overriding-map-is-bound
2473 (setq saved-overriding-map overriding-terminal-local-map)
2474 (setq overriding-terminal-local-map universal-argument-map)
2475 (setq overriding-map-is-bound t)))
2477 (defun restore-overriding-map ()
2478 "Restore `overriding-terminal-local-map' to its saved value."
2479 (setq overriding-terminal-local-map saved-overriding-map)
2480 (setq overriding-map-is-bound nil))
2482 (defun universal-argument ()
2483 "Begin a numeric argument for the following command.
2484 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2485 \\[universal-argument] following the digits or minus sign ends the argument.
2486 \\[universal-argument] without digits or minus sign provides 4 as argument.
2487 Repeating \\[universal-argument] without digits or minus sign
2488 multiplies the argument by 4 each time.
2489 For some commands, just \\[universal-argument] by itself serves as a flag
2490 which is different in effect from any particular numeric argument.
2491 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2493 (setq prefix-arg (list 4))
2494 (setq universal-argument-num-events (length (this-command-keys)))
2495 (ensure-overriding-map-is-bound))
2497 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2498 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2499 (defun universal-argument-more (arg)
2502 (setq prefix-arg (list (* 4 (car arg))))
2504 (setq prefix-arg (list -4))
2505 (setq prefix-arg arg)
2506 (restore-overriding-map)))
2507 (setq universal-argument-num-events (length (this-command-keys))))
2509 (defun negative-argument (arg)
2510 "Begin a negative numeric argument for the next command.
2511 \\[universal-argument] following digits or minus sign ends the argument."
2513 (cond ((integerp arg)
2514 (setq prefix-arg (- arg)))
2516 (setq prefix-arg nil))
2518 (setq prefix-arg '-)))
2519 (setq universal-argument-num-events (length (this-command-keys)))
2520 (ensure-overriding-map-is-bound))
2522 (defun digit-argument (arg)
2523 "Part of the numeric argument for the next command.
2524 \\[universal-argument] following digits or minus sign ends the argument."
2526 (let* ((char (if (integerp last-command-char)
2528 (get last-command-char 'ascii-character)))
2529 (digit (- (logand char ?\177) ?0)))
2530 (cond ((integerp arg)
2531 (setq prefix-arg (+ (* arg 10)
2532 (if (< arg 0) (- digit) digit))))
2534 ;; Treat -0 as just -, so that -01 will work.
2535 (setq prefix-arg (if (zerop digit) '- (- digit))))
2537 (setq prefix-arg digit))))
2538 (setq universal-argument-num-events (length (this-command-keys)))
2539 (ensure-overriding-map-is-bound))
2541 ;; For backward compatibility, minus with no modifiers is an ordinary
2542 ;; command if digits have already been entered.
2543 (defun universal-argument-minus (arg)
2546 (universal-argument-other-key arg)
2547 (negative-argument arg)))
2549 ;; Anything else terminates the argument and is left in the queue to be
2550 ;; executed as a command.
2551 (defun universal-argument-other-key (arg)
2553 (setq prefix-arg arg)
2554 (let* ((key (this-command-keys))
2555 (keylist (listify-key-sequence key)))
2556 (setq unread-command-events
2557 (append (nthcdr universal-argument-num-events keylist)
2558 unread-command-events)))
2559 (reset-this-command-lengths)
2560 (restore-overriding-map))
2562 (defvar buffer-substring-filters nil
2563 "List of filter functions for `filter-buffer-substring'.
2564 Each function must accept a single argument, a string, and return
2565 a string. The buffer substring is passed to the first function
2566 in the list, and the return value of each function is passed to
2567 the next. The return value of the last function is used as the
2568 return value of `filter-buffer-substring'.
2570 If this variable is nil, no filtering is performed.")
2572 (defun filter-buffer-substring (beg end &optional delete noprops)
2573 "Return the buffer substring between BEG and END, after filtering.
2574 The buffer substring is passed through each of the filter
2575 functions in `buffer-substring-filters', and the value from the
2576 last filter function is returned. If `buffer-substring-filters'
2577 is nil, the buffer substring is returned unaltered.
2579 If DELETE is non-nil, the text between BEG and END is deleted
2582 If NOPROPS is non-nil, final string returned does not include
2583 text properties, while the string passed to the filters still
2584 includes text properties from the buffer text.
2586 Point is temporarily set to BEG before calling
2587 `buffer-substring-filters', in case the functions need to know
2588 where the text came from.
2590 This function should be used instead of `buffer-substring',
2591 `buffer-substring-no-properties', or `delete-and-extract-region'
2592 when you want to allow filtering to take place. For example,
2593 major or minor modes can use `buffer-substring-filters' to
2594 extract characters that are special to a buffer, and should not
2595 be copied into other buffers."
2597 ((or delete buffer-substring-filters)
2600 (let ((string (if delete (delete-and-extract-region beg end)
2601 (buffer-substring beg end))))
2602 (dolist (filter buffer-substring-filters)
2603 (setq string (funcall filter string)))
2605 (set-text-properties 0 (length string) nil string))
2608 (buffer-substring-no-properties beg end))
2610 (buffer-substring beg end))))
2613 ;;;; Window system cut and paste hooks.
2615 (defvar interprogram-cut-function nil
2616 "Function to call to make a killed region available to other programs.
2618 Most window systems provide some sort of facility for cutting and
2619 pasting text between the windows of different programs.
2620 This variable holds a function that Emacs calls whenever text
2621 is put in the kill ring, to make the new kill available to other
2624 The function takes one or two arguments.
2625 The first argument, TEXT, is a string containing
2626 the text which should be made available.
2627 The second, optional, argument PUSH, has the same meaning as the
2628 similar argument to `x-set-cut-buffer', which see.")
2630 (defvar interprogram-paste-function nil
2631 "Function to call to get text cut from other programs.
2633 Most window systems provide some sort of facility for cutting and
2634 pasting text between the windows of different programs.
2635 This variable holds a function that Emacs calls to obtain
2636 text that other programs have provided for pasting.
2638 The function should be called with no arguments. If the function
2639 returns nil, then no other program has provided such text, and the top
2640 of the Emacs kill ring should be used. If the function returns a
2641 string, then the caller of the function \(usually `current-kill')
2642 should put this string in the kill ring as the latest kill.
2644 This function may also return a list of strings if the window
2645 system supports multiple selections. The first string will be
2646 used as the pasted text, but the other will be placed in the
2647 kill ring for easy access via `yank-pop'.
2649 Note that the function should return a string only if a program other
2650 than Emacs has provided a string for pasting; if Emacs provided the
2651 most recent string, the function should return nil. If it is
2652 difficult to tell whether Emacs or some other program provided the
2653 current string, it is probably good enough to return nil if the string
2654 is equal (according to `string=') to the last text Emacs provided.")
2658 ;;;; The kill ring data structure.
2660 (defvar kill-ring nil
2661 "List of killed text sequences.
2662 Since the kill ring is supposed to interact nicely with cut-and-paste
2663 facilities offered by window systems, use of this variable should
2664 interact nicely with `interprogram-cut-function' and
2665 `interprogram-paste-function'. The functions `kill-new',
2666 `kill-append', and `current-kill' are supposed to implement this
2667 interaction; you may want to use them instead of manipulating the kill
2670 (defcustom kill-ring-max 60
2671 "*Maximum length of kill ring before oldest elements are thrown away."
2675 (defvar kill-ring-yank-pointer nil
2676 "The tail of the kill ring whose car is the last thing yanked.")
2678 (defun kill-new (string &optional replace yank-handler)
2679 "Make STRING the latest kill in the kill ring.
2680 Set `kill-ring-yank-pointer' to point to it.
2681 If `interprogram-cut-function' is non-nil, apply it to STRING.
2682 Optional second argument REPLACE non-nil means that STRING will replace
2683 the front of the kill ring, rather than being added to the list.
2685 Optional third arguments YANK-HANDLER controls how the STRING is later
2686 inserted into a buffer; see `insert-for-yank' for details.
2687 When a yank handler is specified, STRING must be non-empty (the yank
2688 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2690 When the yank handler has a non-nil PARAM element, the original STRING
2691 argument is not used by `insert-for-yank'. However, since Lisp code
2692 may access and use elements from the kill ring directly, the STRING
2693 argument should still be a \"useful\" string for such uses."
2694 (if (> (length string) 0)
2696 (put-text-property 0 (length string)
2697 'yank-handler yank-handler string))
2699 (signal 'args-out-of-range
2700 (list string "yank-handler specified for empty string"))))
2701 (if (fboundp 'menu-bar-update-yank-menu)
2702 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2703 (if (and replace kill-ring)
2704 (setcar kill-ring string)
2705 (push string kill-ring)
2706 (if (> (length kill-ring) kill-ring-max)
2707 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2708 (setq kill-ring-yank-pointer kill-ring)
2709 (if interprogram-cut-function
2710 (funcall interprogram-cut-function string (not replace))))
2712 (defun kill-append (string before-p &optional yank-handler)
2713 "Append STRING to the end of the latest kill in the kill ring.
2714 If BEFORE-P is non-nil, prepend STRING to the kill.
2715 Optional third argument YANK-HANDLER, if non-nil, specifies the
2716 yank-handler text property to be set on the combined kill ring
2717 string. If the specified yank-handler arg differs from the
2718 yank-handler property of the latest kill string, this function
2719 adds the combined string to the kill ring as a new element,
2720 instead of replacing the last kill with it.
2721 If `interprogram-cut-function' is set, pass the resulting kill to it."
2722 (let* ((cur (car kill-ring)))
2723 (kill-new (if before-p (concat string cur) (concat cur string))
2724 (or (= (length cur) 0)
2725 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2728 (defcustom yank-pop-change-selection nil
2729 "If non-nil, rotating the kill ring changes the window system selection."
2734 (defun current-kill (n &optional do-not-move)
2735 "Rotate the yanking point by N places, and then return that kill.
2736 If N is zero, `interprogram-paste-function' is set, and calling it returns a
2737 string or list of strings, then that string (or list) is added to the front
2738 of the kill ring and the string (or first string in the list) is returned as
2741 If N is not zero, and if `yank-pop-change-selection' is
2742 non-nil, use `interprogram-cut-function' to transfer the
2743 kill at the new yank point into the window system selection.
2745 If optional arg DO-NOT-MOVE is non-nil, then don't actually
2746 move the yanking point; just return the Nth kill forward."
2748 (let ((interprogram-paste (and (= n 0)
2749 interprogram-paste-function
2750 (funcall interprogram-paste-function))))
2751 (if interprogram-paste
2753 ;; Disable the interprogram cut function when we add the new
2754 ;; text to the kill ring, so Emacs doesn't try to own the
2755 ;; selection, with identical text.
2756 (let ((interprogram-cut-function nil))
2757 (if (listp interprogram-paste)
2758 (mapc 'kill-new (nreverse interprogram-paste))
2759 (kill-new interprogram-paste)))
2761 (or kill-ring (error "Kill ring is empty"))
2762 (let ((ARGth-kill-element
2763 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2767 (setq kill-ring-yank-pointer ARGth-kill-element)
2768 (when (and yank-pop-change-selection
2770 interprogram-cut-function)
2771 (funcall interprogram-cut-function (car ARGth-kill-element))))
2772 (car ARGth-kill-element)))))
2776 ;;;; Commands for manipulating the kill ring.
2778 (defcustom kill-read-only-ok nil
2779 "*Non-nil means don't signal an error for killing read-only text."
2783 (put 'text-read-only 'error-conditions
2784 '(text-read-only buffer-read-only error))
2785 (put 'text-read-only 'error-message "Text is read-only")
2787 (defun kill-region (beg end &optional yank-handler)
2788 "Kill (\"cut\") text between point and mark.
2789 This deletes the text from the buffer and saves it in the kill ring.
2790 The command \\[yank] can retrieve it from there.
2791 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2793 If you want to append the killed region to the last killed text,
2794 use \\[append-next-kill] before \\[kill-region].
2796 If the buffer is read-only, Emacs will beep and refrain from deleting
2797 the text, but put the text in the kill ring anyway. This means that
2798 you can use the killing commands to copy text from a read-only buffer.
2800 This is the primitive for programs to kill text (as opposed to deleting it).
2801 Supply two arguments, character positions indicating the stretch of text
2803 Any command that calls this function is a \"kill command\".
2804 If the previous command was also a kill command,
2805 the text killed this time appends to the text killed last time
2806 to make one entry in the kill ring.
2808 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2809 specifies the yank-handler text property to be set on the killed
2810 text. See `insert-for-yank'."
2811 ;; Pass point first, then mark, because the order matters
2812 ;; when calling kill-append.
2813 (interactive (list (point) (mark)))
2814 (unless (and beg end)
2815 (error "The mark is not set now, so there is no region"))
2817 (let ((string (filter-buffer-substring beg end t)))
2818 (when string ;STRING is nil if BEG = END
2819 ;; Add that string to the kill ring, one way or another.
2820 (if (eq last-command 'kill-region)
2821 (kill-append string (< end beg) yank-handler)
2822 (kill-new string nil yank-handler)))
2823 (when (or string (eq last-command 'kill-region))
2824 (setq this-command 'kill-region))
2826 ((buffer-read-only text-read-only)
2827 ;; The code above failed because the buffer, or some of the characters
2828 ;; in the region, are read-only.
2829 ;; We should beep, in case the user just isn't aware of this.
2830 ;; However, there's no harm in putting
2831 ;; the region's text in the kill ring, anyway.
2832 (copy-region-as-kill beg end)
2833 ;; Set this-command now, so it will be set even if we get an error.
2834 (setq this-command 'kill-region)
2835 ;; This should barf, if appropriate, and give us the correct error.
2836 (if kill-read-only-ok
2837 (progn (message "Read only text copied to kill ring") nil)
2838 ;; Signal an error if the buffer is read-only.
2839 (barf-if-buffer-read-only)
2840 ;; If the buffer isn't read-only, the text is.
2841 (signal 'text-read-only (list (current-buffer)))))))
2843 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2844 ;; to get two copies of the text when the user accidentally types M-w and
2845 ;; then corrects it with the intended C-w.
2846 (defun copy-region-as-kill (beg end)
2847 "Save the region as if killed, but don't kill it.
2848 In Transient Mark mode, deactivate the mark.
2849 If `interprogram-cut-function' is non-nil, also save the text for a window
2850 system cut and paste.
2852 This command's old key binding has been given to `kill-ring-save'."
2854 (if (eq last-command 'kill-region)
2855 (kill-append (filter-buffer-substring beg end) (< end beg))
2856 (kill-new (filter-buffer-substring beg end)))
2857 (setq deactivate-mark t)
2860 (defun kill-ring-save (beg end)
2861 "Save the region as if killed, but don't kill it.
2862 In Transient Mark mode, deactivate the mark.
2863 If `interprogram-cut-function' is non-nil, also save the text for a window
2864 system cut and paste.
2866 If you want to append the killed line to the last killed text,
2867 use \\[append-next-kill] before \\[kill-ring-save].
2869 This command is similar to `copy-region-as-kill', except that it gives
2870 visual feedback indicating the extent of the region being copied."
2872 (copy-region-as-kill beg end)
2873 ;; This use of interactive-p is correct
2874 ;; because the code it controls just gives the user visual feedback.
2876 (let ((other-end (if (= (point) beg) end beg))
2878 ;; Inhibit quitting so we can make a quit here
2879 ;; look like a C-g typed as a command.
2881 (if (pos-visible-in-window-p other-end (selected-window))
2882 ;; Swap point-and-mark quickly so as to show the region that
2883 ;; was selected. Don't do it if the region is highlighted.
2884 (unless (and (region-active-p)
2885 (face-background 'region))
2886 ;; Swap point and mark.
2887 (set-marker (mark-marker) (point) (current-buffer))
2888 (goto-char other-end)
2889 (sit-for blink-matching-delay)
2891 (set-marker (mark-marker) other-end (current-buffer))
2893 ;; If user quit, deactivate the mark
2894 ;; as C-g would as a command.
2895 (and quit-flag mark-active
2897 (let* ((killed-text (current-kill 0))
2898 (message-len (min (length killed-text) 40)))
2900 ;; Don't say "killed"; that is misleading.
2901 (message "Saved text until \"%s\""
2902 (substring killed-text (- message-len)))
2903 (message "Saved text from \"%s\""
2904 (substring killed-text 0 message-len))))))))
2906 (defun append-next-kill (&optional interactive)
2907 "Cause following command, if it kills, to append to previous kill.
2908 The argument is used for internal purposes; do not supply one."
2910 ;; We don't use (interactive-p), since that breaks kbd macros.
2913 (setq this-command 'kill-region)
2914 (message "If the next command is a kill, it will append"))
2915 (setq last-command 'kill-region)))
2919 ;; This is actually used in subr.el but defcustom does not work there.
2920 (defcustom yank-excluded-properties
2921 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2922 yank-handler follow-link fontified)
2923 "Text properties to discard when yanking.
2924 The value should be a list of text properties to discard or t,
2925 which means to discard all text properties."
2926 :type '(choice (const :tag "All" t) (repeat symbol))
2930 (defvar yank-window-start nil)
2931 (defvar yank-undo-function nil
2932 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2933 Function is called with two parameters, START and END corresponding to
2934 the value of the mark and point; it is guaranteed that START <= END.
2935 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2937 (defun yank-pop (&optional arg)
2938 "Replace just-yanked stretch of killed text with a different stretch.
2939 This command is allowed only immediately after a `yank' or a `yank-pop'.
2940 At such a time, the region contains a stretch of reinserted
2941 previously-killed text. `yank-pop' deletes that text and inserts in its
2942 place a different stretch of killed text.
2944 With no argument, the previous kill is inserted.
2945 With argument N, insert the Nth previous kill.
2946 If N is negative, this is a more recent kill.
2948 The sequence of kills wraps around, so that after the oldest one
2949 comes the newest one.
2951 When this command inserts killed text into the buffer, it honors
2952 `yank-excluded-properties' and `yank-handler' as described in the
2953 doc string for `insert-for-yank-1', which see."
2955 (if (not (eq last-command 'yank))
2956 (error "Previous command was not a yank"))
2957 (setq this-command 'yank)
2958 (unless arg (setq arg 1))
2959 (let ((inhibit-read-only t)
2960 (before (< (point) (mark t))))
2962 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2963 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2964 (setq yank-undo-function nil)
2965 (set-marker (mark-marker) (point) (current-buffer))
2966 (insert-for-yank (current-kill arg))
2967 ;; Set the window start back where it was in the yank command,
2969 (set-window-start (selected-window) yank-window-start t)
2971 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2972 ;; It is cleaner to avoid activation, even though the command
2973 ;; loop would deactivate the mark because we inserted text.
2974 (goto-char (prog1 (mark t)
2975 (set-marker (mark-marker) (point) (current-buffer))))))
2978 (defun yank (&optional arg)
2979 "Reinsert (\"paste\") the last stretch of killed text.
2980 More precisely, reinsert the stretch of killed text most recently
2981 killed OR yanked. Put point at end, and set mark at beginning.
2982 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2983 With argument N, reinsert the Nth most recently killed stretch of killed
2986 When this command inserts killed text into the buffer, it honors
2987 `yank-excluded-properties' and `yank-handler' as described in the
2988 doc string for `insert-for-yank-1', which see.
2990 See also the command `yank-pop' (\\[yank-pop])."
2992 (setq yank-window-start (window-start))
2993 ;; If we don't get all the way thru, make last-command indicate that
2994 ;; for the following command.
2995 (setq this-command t)
2997 (insert-for-yank (current-kill (cond
3002 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3003 ;; It is cleaner to avoid activation, even though the command
3004 ;; loop would deactivate the mark because we inserted text.
3005 (goto-char (prog1 (mark t)
3006 (set-marker (mark-marker) (point) (current-buffer)))))
3007 ;; If we do get all the way thru, make this-command indicate that.
3008 (if (eq this-command t)
3009 (setq this-command 'yank))
3012 (defun rotate-yank-pointer (arg)
3013 "Rotate the yanking point in the kill ring.
3014 With argument, rotate that many kills forward (or backward, if negative)."
3018 ;; Some kill commands.
3020 ;; Internal subroutine of delete-char
3021 (defun kill-forward-chars (arg)
3022 (if (listp arg) (setq arg (car arg)))
3023 (if (eq arg '-) (setq arg -1))
3024 (kill-region (point) (forward-point arg)))
3026 ;; Internal subroutine of backward-delete-char
3027 (defun kill-backward-chars (arg)
3028 (if (listp arg) (setq arg (car arg)))
3029 (if (eq arg '-) (setq arg -1))
3030 (kill-region (point) (forward-point (- arg))))
3032 (defcustom backward-delete-char-untabify-method 'untabify
3033 "*The method for untabifying when deleting backward.
3034 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3035 `hungry' -- delete all whitespace, both tabs and spaces;
3036 `all' -- delete all whitespace, including tabs, spaces and newlines;
3037 nil -- just delete one character."
3038 :type '(choice (const untabify) (const hungry) (const all) (const nil))
3042 (defun backward-delete-char-untabify (arg &optional killp)
3043 "Delete characters backward, changing tabs into spaces.
3044 The exact behavior depends on `backward-delete-char-untabify-method'.
3045 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3046 Interactively, ARG is the prefix arg (default 1)
3047 and KILLP is t if a prefix arg was specified."
3048 (interactive "*p\nP")
3049 (when (eq backward-delete-char-untabify-method 'untabify)
3052 (while (and (> count 0) (not (bobp)))
3053 (if (= (preceding-char) ?\t)
3054 (let ((col (current-column)))
3056 (setq col (- col (current-column)))
3057 (insert-char ?\s col)
3060 (setq count (1- count))))))
3061 (delete-backward-char
3062 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3063 ((eq backward-delete-char-untabify-method 'all)
3066 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
3068 (+ arg (if (zerop wh) 0 (1- wh))))
3072 (defun zap-to-char (arg char)
3073 "Kill up to and including ARG'th occurrence of CHAR.
3074 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3075 Goes backward if ARG is negative; error if CHAR not found."
3076 (interactive "p\ncZap to char: ")
3077 (if (char-table-p translation-table-for-input)
3078 (setq char (or (aref translation-table-for-input char) char)))
3079 (kill-region (point) (progn
3080 (search-forward (char-to-string char) nil nil arg)
3081 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3084 ;; kill-line and its subroutines.
3086 (defcustom kill-whole-line nil
3087 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
3091 (defun kill-line (&optional arg)
3092 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3093 With prefix argument, kill that many lines from point.
3094 Negative arguments kill lines backward.
3095 With zero argument, kills the text before point on the current line.
3097 When calling from a program, nil means \"no arg\",
3098 a number counts as a prefix arg.
3100 To kill a whole line, when point is not at the beginning, type \
3101 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3103 If `kill-whole-line' is non-nil, then this command kills the whole line
3104 including its terminating newline, when used at the beginning of a line
3105 with no argument. As a consequence, you can always kill a whole line
3106 by typing \\[move-beginning-of-line] \\[kill-line].
3108 If you want to append the killed line to the last killed text,
3109 use \\[append-next-kill] before \\[kill-line].
3111 If the buffer is read-only, Emacs will beep and refrain from deleting
3112 the line, but put the line in the kill ring anyway. This means that
3113 you can use this command to copy text from a read-only buffer.
3114 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3117 (kill-region (point)
3118 ;; It is better to move point to the other end of the kill
3119 ;; before killing. That way, in a read-only buffer, point
3120 ;; moves across the text that is copied to the kill ring.
3121 ;; The choice has no effect on undo now that undo records
3122 ;; the value of point from before the command was run.
3125 (forward-visible-line (prefix-numeric-value arg))
3127 (signal 'end-of-buffer nil))
3130 (end-of-visible-line) (point))))
3131 (if (or (save-excursion
3132 ;; If trailing whitespace is visible,
3133 ;; don't treat it as nothing.
3134 (unless show-trailing-whitespace
3135 (skip-chars-forward " \t" end))
3137 (and kill-whole-line (bolp)))
3138 (forward-visible-line 1)
3142 (defun kill-whole-line (&optional arg)
3144 With prefix arg, kill that many lines starting from the current line.
3145 If arg is negative, kill backward. Also kill the preceding newline.
3146 \(This is meant to make \\[repeat] work well with negative arguments.\)
3147 If arg is zero, kill current line but exclude the trailing newline."
3149 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3150 (signal 'end-of-buffer nil))
3151 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3152 (signal 'beginning-of-buffer nil))
3153 (unless (eq last-command 'kill-region)
3155 (setq last-command 'kill-region))
3157 ;; We need to kill in two steps, because the previous command
3158 ;; could have been a kill command, in which case the text
3159 ;; before point needs to be prepended to the current kill
3160 ;; ring entry and the text after point appended. Also, we
3161 ;; need to use save-excursion to avoid copying the same text
3162 ;; twice to the kill ring in read-only buffers.
3164 (kill-region (point) (progn (forward-visible-line 0) (point))))
3165 (kill-region (point) (progn (end-of-visible-line) (point))))
3168 (kill-region (point) (progn (end-of-visible-line) (point))))
3169 (kill-region (point)
3170 (progn (forward-visible-line (1+ arg))
3171 (unless (bobp) (backward-char))
3175 (kill-region (point) (progn (forward-visible-line 0) (point))))
3176 (kill-region (point)
3177 (progn (forward-visible-line arg) (point))))))
3179 (defun forward-visible-line (arg)
3180 "Move forward by ARG lines, ignoring currently invisible newlines only.
3181 If ARG is negative, move backward -ARG lines.
3182 If ARG is zero, move to the beginning of the current line."
3187 (or (zerop (forward-line 1))
3188 (signal 'end-of-buffer nil))
3189 ;; If the newline we just skipped is invisible,
3192 (get-char-property (1- (point)) 'invisible)))
3193 (if (if (eq buffer-invisibility-spec t)
3195 (or (memq prop buffer-invisibility-spec)
3196 (assq prop buffer-invisibility-spec)))
3197 (setq arg (1+ arg))))
3198 (setq arg (1- arg)))
3199 ;; If invisible text follows, and it is a number of complete lines,
3201 (let ((opoint (point)))
3202 (while (and (not (eobp))
3204 (get-char-property (point) 'invisible)))
3205 (if (eq buffer-invisibility-spec t)
3207 (or (memq prop buffer-invisibility-spec)
3208 (assq prop buffer-invisibility-spec)))))
3210 (if (get-text-property (point) 'invisible)
3211 (or (next-single-property-change (point) 'invisible)
3213 (next-overlay-change (point)))))
3215 (goto-char opoint))))
3217 (while (or first (<= arg 0))
3220 (or (zerop (forward-line -1))
3221 (signal 'beginning-of-buffer nil)))
3222 ;; If the newline we just moved to is invisible,
3226 (get-char-property (1- (point)) 'invisible)))
3227 (unless (if (eq buffer-invisibility-spec t)
3229 (or (memq prop buffer-invisibility-spec)
3230 (assq prop buffer-invisibility-spec)))
3231 (setq arg (1+ arg)))))
3233 ;; If invisible text follows, and it is a number of complete lines,
3235 (let ((opoint (point)))
3236 (while (and (not (bobp))
3238 (get-char-property (1- (point)) 'invisible)))
3239 (if (eq buffer-invisibility-spec t)
3241 (or (memq prop buffer-invisibility-spec)
3242 (assq prop buffer-invisibility-spec)))))
3244 (if (get-text-property (1- (point)) 'invisible)
3245 (or (previous-single-property-change (point) 'invisible)
3247 (previous-overlay-change (point)))))
3249 (goto-char opoint)))))
3250 ((beginning-of-buffer end-of-buffer)
3253 (defun end-of-visible-line ()
3254 "Move to end of current visible line."
3256 ;; If the following character is currently invisible,
3257 ;; skip all characters with that same `invisible' property value,
3258 ;; then find the next newline.
3259 (while (and (not (eobp))
3261 (skip-chars-forward "^\n")
3263 (get-char-property (point) 'invisible)))
3264 (if (eq buffer-invisibility-spec t)
3266 (or (memq prop buffer-invisibility-spec)
3267 (assq prop buffer-invisibility-spec))))))
3268 (skip-chars-forward "^\n")
3269 (if (get-text-property (point) 'invisible)
3270 (goto-char (next-single-property-change (point) 'invisible))
3271 (goto-char (next-overlay-change (point))))
3274 (defun insert-buffer (buffer)
3275 "Insert after point the contents of BUFFER.
3276 Puts mark after the inserted text.
3277 BUFFER may be a buffer or a buffer name.
3279 This function is meant for the user to run interactively.
3280 Don't call it from programs: use `insert-buffer-substring' instead!"
3284 (barf-if-buffer-read-only)
3285 (read-buffer "Insert buffer: "
3286 (if (eq (selected-window) (next-window (selected-window)))
3287 (other-buffer (current-buffer))
3288 (window-buffer (next-window (selected-window))))
3292 (insert-buffer-substring (get-buffer buffer))
3296 (defun append-to-buffer (buffer start end)
3297 "Append to specified buffer the text of the region.
3298 It is inserted into that buffer before its point.
3300 When calling from a program, give three arguments:
3301 BUFFER (or buffer name), START and END.
3302 START and END specify the portion of the current buffer to be copied."
3304 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3305 (region-beginning) (region-end)))
3306 (let ((oldbuf (current-buffer)))
3308 (let* ((append-to (get-buffer-create buffer))
3309 (windows (get-buffer-window-list append-to t t))
3311 (set-buffer append-to)
3312 (setq point (point))
3313 (barf-if-buffer-read-only)
3314 (insert-buffer-substring oldbuf start end)
3315 (dolist (window windows)
3316 (when (= (window-point window) point)
3317 (set-window-point window (point))))))))
3319 (defun prepend-to-buffer (buffer start end)
3320 "Prepend to specified buffer the text of the region.
3321 It is inserted into that buffer after its point.
3323 When calling from a program, give three arguments:
3324 BUFFER (or buffer name), START and END.
3325 START and END specify the portion of the current buffer to be copied."
3326 (interactive "BPrepend to buffer: \nr")
3327 (let ((oldbuf (current-buffer)))
3329 (set-buffer (get-buffer-create buffer))
3330 (barf-if-buffer-read-only)
3332 (insert-buffer-substring oldbuf start end)))))
3334 (defun copy-to-buffer (buffer start end)
3335 "Copy to specified buffer the text of the region.
3336 It is inserted into that buffer, replacing existing text there.
3338 When calling from a program, give three arguments:
3339 BUFFER (or buffer name), START and END.
3340 START and END specify the portion of the current buffer to be copied."
3341 (interactive "BCopy to buffer: \nr")
3342 (let ((oldbuf (current-buffer)))
3343 (with-current-buffer (get-buffer-create buffer)
3344 (barf-if-buffer-read-only)
3347 (insert-buffer-substring oldbuf start end)))))
3349 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3350 (put 'mark-inactive 'error-message "The mark is not active now")
3352 (defvar activate-mark-hook nil
3353 "Hook run when the mark becomes active.
3354 It is also run at the end of a command, if the mark is active and
3355 it is possible that the region may have changed.")
3357 (defvar deactivate-mark-hook nil
3358 "Hook run when the mark becomes inactive.")
3360 (defun mark (&optional force)
3361 "Return this buffer's mark value as integer, or nil if never set.
3363 In Transient Mark mode, this function signals an error if
3364 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3365 or the argument FORCE is non-nil, it disregards whether the mark
3366 is active, and returns an integer or nil in the usual way.
3368 If you are using this in an editing command, you are most likely making
3369 a mistake; see the documentation of `set-mark'."
3370 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3371 (marker-position (mark-marker))
3372 (signal 'mark-inactive nil)))
3374 ;; Many places set mark-active directly, and several of them failed to also
3375 ;; run deactivate-mark-hook. This shorthand should simplify.
3376 (defsubst deactivate-mark ()
3377 "Deactivate the mark by setting `mark-active' to nil.
3378 \(That makes a difference only in Transient Mark mode.)
3379 Also runs the hook `deactivate-mark-hook'."
3380 (when transient-mark-mode
3381 (if (or (eq transient-mark-mode 'lambda)
3382 (and (eq (car-safe transient-mark-mode) 'only)
3383 (null (cdr transient-mark-mode))))
3384 (setq transient-mark-mode nil)
3385 (if (eq (car-safe transient-mark-mode) 'only)
3386 (setq transient-mark-mode (cdr transient-mark-mode)))
3387 (setq mark-active nil)
3388 (run-hooks 'deactivate-mark-hook))))
3390 (defun activate-mark ()
3391 "Activate the mark."
3393 (setq mark-active t)
3394 (unless transient-mark-mode
3395 (setq transient-mark-mode 'lambda))))
3397 (defcustom select-active-regions nil
3398 "If non-nil, an active region automatically becomes the window selection."
3403 (defun set-mark (pos)
3404 "Set this buffer's mark to POS. Don't use this function!
3405 That is to say, don't use this function unless you want
3406 the user to see that the mark has moved, and you want the previous
3407 mark position to be lost.
3409 Normally, when a new mark is set, the old one should go on the stack.
3410 This is why most applications should use `push-mark', not `set-mark'.
3412 Novice Emacs Lisp programmers often try to use the mark for the wrong
3413 purposes. The mark saves a location for the user's convenience.
3414 Most editing commands should not alter the mark.
3415 To remember a location for internal use in the Lisp program,
3416 store it in a Lisp variable. Example:
3418 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3422 (setq mark-active t)
3423 (run-hooks 'activate-mark-hook)
3424 (and select-active-regions
3426 nil (buffer-substring (region-beginning) (region-end))))
3427 (set-marker (mark-marker) pos (current-buffer)))
3428 ;; Normally we never clear mark-active except in Transient Mark mode.
3429 ;; But when we actually clear out the mark value too,
3430 ;; we must clear mark-active in any mode.
3431 (setq mark-active nil)
3432 (run-hooks 'deactivate-mark-hook)
3433 (set-marker (mark-marker) nil)))
3435 (defcustom use-empty-active-region nil
3436 "If non-nil, an active region takes control even if empty.
3437 This applies to certain commands which, in Transient Mark mode,
3438 apply to the active region if there is one. If the setting is t,
3439 these commands apply to an empty active region if there is one.
3440 If the setting is nil, these commands treat an empty active
3441 region as if it were not active."
3444 :group 'editing-basics)
3446 (defun use-region-p ()
3447 "Return t if certain commands should apply to the region.
3448 Certain commands normally apply to text near point,
3449 but in Transient Mark mode when the mark is active they apply
3450 to the region instead. Such commands should use this subroutine to
3451 test whether to do that.
3453 This function also obeys `use-empty-active-region'."
3454 (and (region-active-p)
3455 (or use-empty-active-region (> (region-end) (region-beginning)))))
3457 (defun region-active-p ()
3458 "Return t if Transient Mark mode is enabled and the mark is active.
3459 This is NOT the best function to use to test whether a command should
3460 operate on the region instead of the usual behavior -- for that,
3461 use `use-region-p'."
3462 (and transient-mark-mode mark-active))
3464 (defvar mark-ring nil
3465 "The list of former marks of the current buffer, most recent first.")
3466 (make-variable-buffer-local 'mark-ring)
3467 (put 'mark-ring 'permanent-local t)
3469 (defcustom mark-ring-max 16
3470 "*Maximum size of mark ring. Start discarding off end if gets this big."
3472 :group 'editing-basics)
3474 (defvar global-mark-ring nil
3475 "The list of saved global marks, most recent first.")
3477 (defcustom global-mark-ring-max 16
3478 "*Maximum size of global mark ring. \
3479 Start discarding off end if gets this big."
3481 :group 'editing-basics)
3483 (defun pop-to-mark-command ()
3484 "Jump to mark, and pop a new position for mark off the ring
3485 \(does not affect global mark ring\)."
3488 (error "No mark set in this buffer")
3489 (if (= (point) (mark t))
3490 (message "Mark popped"))
3491 (goto-char (mark t))
3494 (defun push-mark-command (arg &optional nomsg)
3495 "Set mark at where point is.
3496 If no prefix arg and mark is already set there, just activate it.
3497 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3499 (let ((mark (marker-position (mark-marker))))
3500 (if (or arg (null mark) (/= mark (point)))
3501 (push-mark nil nomsg t)
3502 (setq mark-active t)
3503 (run-hooks 'activate-mark-hook)
3505 (message "Mark activated")))))
3507 (defcustom set-mark-command-repeat-pop nil
3508 "*Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3509 That means that C-u \\[set-mark-command] \\[set-mark-command]
3510 will pop the mark twice, and
3511 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3512 will pop the mark three times.
3514 A value of nil means \\[set-mark-command]'s behavior does not change
3515 after C-u \\[set-mark-command]."
3517 :group 'editing-basics)
3519 (defun set-mark-command (arg)
3520 "Set the mark where point is, or jump to the mark.
3521 Setting the mark also alters the region, which is the text
3522 between point and mark; this is the closest equivalent in
3523 Emacs to what some editors call the \"selection\".
3525 With no prefix argument, set the mark at point, and push the
3526 old mark position on local mark ring. Also push the old mark on
3527 global mark ring, if the previous mark was set in another buffer.
3529 When Transient Mark Mode is off, immediately repeating this
3530 command activates `transient-mark-mode' temporarily.
3532 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3533 jump to the mark, and set the mark from
3534 position popped off the local mark ring \(this does not affect the global
3535 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3536 mark ring \(see `pop-global-mark'\).
3538 If `set-mark-command-repeat-pop' is non-nil, repeating
3539 the \\[set-mark-command] command with no prefix argument pops the next position
3540 off the local (or global) mark ring and jumps there.
3542 With \\[universal-argument] \\[universal-argument] as prefix
3543 argument, unconditionally set mark where point is, even if
3544 `set-mark-command-repeat-pop' is non-nil.
3546 Novice Emacs Lisp programmers often try to use the mark for the wrong
3547 purposes. See the documentation of `set-mark' for more information."
3549 (cond ((eq transient-mark-mode 'lambda)
3550 (setq transient-mark-mode nil))
3551 ((eq (car-safe transient-mark-mode) 'only)
3554 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3555 (push-mark-command nil))
3556 ((not (eq this-command 'set-mark-command))
3558 (pop-to-mark-command)
3559 (push-mark-command t)))
3560 ((and set-mark-command-repeat-pop
3561 (eq last-command 'pop-to-mark-command))
3562 (setq this-command 'pop-to-mark-command)
3563 (pop-to-mark-command))
3564 ((and set-mark-command-repeat-pop
3565 (eq last-command 'pop-global-mark)
3567 (setq this-command 'pop-global-mark)
3570 (setq this-command 'pop-to-mark-command)
3571 (pop-to-mark-command))
3572 ((eq last-command 'set-mark-command)
3573 (if (region-active-p)
3576 (message "Mark deactivated"))
3578 (message "Mark activated")))
3580 (push-mark-command nil))))
3582 (defun push-mark (&optional location nomsg activate)
3583 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3584 If the last global mark pushed was not in the current buffer,
3585 also push LOCATION on the global mark ring.
3586 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3588 Novice Emacs Lisp programmers often try to use the mark for the wrong
3589 purposes. See the documentation of `set-mark' for more information.
3591 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
3592 (unless (null (mark t))
3593 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3594 (when (> (length mark-ring) mark-ring-max)
3595 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3596 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3597 (set-marker (mark-marker) (or location (point)) (current-buffer))
3598 ;; Now push the mark on the global mark ring.
3599 (if (and global-mark-ring
3600 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3601 ;; The last global mark pushed was in this same buffer.
3602 ;; Don't push another one.
3604 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3605 (when (> (length global-mark-ring) global-mark-ring-max)
3606 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3607 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3608 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3609 (message "Mark set"))
3610 (if (or activate (not transient-mark-mode))
3611 (set-mark (mark t)))
3615 "Pop off mark ring into the buffer's actual mark.
3616 Does not set point. Does nothing if mark ring is empty."
3618 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3619 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3620 (move-marker (car mark-ring) nil)
3621 (if (null (mark t)) (ding))
3622 (setq mark-ring (cdr mark-ring)))
3625 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3626 (defun exchange-point-and-mark (&optional arg)
3627 "Put the mark where point is now, and point where the mark is now.
3628 This command works even when the mark is not active,
3629 and it reactivates the mark.
3631 If Transient Mark mode is on, a prefix arg deactivates the mark
3632 if it is active, and otherwise avoids reactivating it. If
3633 Transient Mark mode is off, a prefix arg enables Transient Mark
3636 (let ((omark (mark t))
3637 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
3639 (error "No mark set in this buffer"))
3643 (cond (temp-highlight
3644 (setq transient-mark-mode (cons 'only transient-mark-mode)))
3645 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
3646 (not (or arg (region-active-p))))
3648 (t (activate-mark)))
3651 (defun handle-shift-selection (&optional deactivate)
3652 "Check for shift translation, and operate on the mark accordingly.
3653 This is called whenever a command with a `^' character in its
3654 `interactive' spec is invoked while `shift-select-mode' is
3657 If the command was invoked through shift-translation, set the
3658 mark and activate the region temporarily, unless it was already
3659 set in this way. If the command was invoked without
3660 shift-translation and a region is temporarily active, deactivate
3663 With optional arg DEACTIVATE, only perform region deactivation."
3664 (cond ((and this-command-keys-shift-translated
3666 (unless (and mark-active
3667 (eq (car-safe transient-mark-mode) 'only))
3668 (setq transient-mark-mode
3670 (unless (eq transient-mark-mode 'lambda)
3671 transient-mark-mode)))
3672 (push-mark nil nil t)))
3673 ((eq (car-safe transient-mark-mode) 'only)
3674 (setq transient-mark-mode (cdr transient-mark-mode))
3675 (deactivate-mark))))
3677 (define-minor-mode transient-mark-mode
3678 "Toggle Transient Mark mode.
3679 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
3681 In Transient Mark mode, when the mark is active, the region is highlighted.
3682 Changing the buffer \"deactivates\" the mark.
3683 So do certain other operations that set the mark
3684 but whose main purpose is something else--for example,
3685 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3687 You can also deactivate the mark by typing \\[keyboard-quit] or
3688 \\[keyboard-escape-quit].
3690 Many commands change their behavior when Transient Mark mode is in effect
3691 and the mark is active, by acting on the region instead of their usual
3692 default part of the buffer's text. Examples of such commands include
3693 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3694 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3695 Invoke \\[apropos-documentation] and type \"transient\" or
3696 \"mark.*active\" at the prompt, to see the documentation of
3697 commands which are sensitive to the Transient Mark mode."
3699 :init-value (not noninteractive)
3700 :group 'editing-basics)
3702 ;; The variable transient-mark-mode is ugly: it can take on special
3703 ;; values. Document these here.
3704 (defvar transient-mark-mode t
3705 "*Non-nil if Transient Mark mode is enabled.
3706 See the command `transient-mark-mode' for a description of this minor mode.
3708 Non-nil also enables highlighting of the region whenever the mark is active.
3709 The variable `highlight-nonselected-windows' controls whether to highlight
3710 all windows or just the selected window.
3712 If the value is `lambda', that enables Transient Mark mode
3713 temporarily. After any subsequent action that would normally
3714 deactivate the mark (such as buffer modification), Transient Mark mode
3717 If the value is (only . OLDVAL), that enables Transient Mark mode
3718 temporarily. After any subsequent point motion command that is not
3719 shift-translated, or any other action that would normally deactivate
3720 the mark (such as buffer modification), the value of
3721 `transient-mark-mode' is set to OLDVAL.")
3723 (defvar widen-automatically t
3724 "Non-nil means it is ok for commands to call `widen' when they want to.
3725 Some commands will do this in order to go to positions outside
3726 the current accessible part of the buffer.
3728 If `widen-automatically' is nil, these commands will do something else
3729 as a fallback, and won't change the buffer bounds.")
3731 (defun pop-global-mark ()
3732 "Pop off global mark ring and jump to the top location."
3734 ;; Pop entries which refer to non-existent buffers.
3735 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3736 (setq global-mark-ring (cdr global-mark-ring)))
3737 (or global-mark-ring
3738 (error "No global mark set"))
3739 (let* ((marker (car global-mark-ring))
3740 (buffer (marker-buffer marker))
3741 (position (marker-position marker)))
3742 (setq global-mark-ring (nconc (cdr global-mark-ring)
3743 (list (car global-mark-ring))))
3745 (or (and (>= position (point-min))
3746 (<= position (point-max)))
3747 (if widen-automatically
3749 (error "Global mark position is outside accessible part of buffer")))
3750 (goto-char position)
3751 (switch-to-buffer buffer)))
3753 (defcustom next-line-add-newlines nil
3754 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3757 :group 'editing-basics)
3759 (defun next-line (&optional arg try-vscroll)
3760 "Move cursor vertically down ARG lines.
3761 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3762 If there is no character in the target line exactly under the current column,
3763 the cursor is positioned after the character in that line which spans this
3764 column, or at the end of the line if it is not long enough.
3765 If there is no line in the buffer after this one, behavior depends on the
3766 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3767 to create a line, and moves the cursor to that line. Otherwise it moves the
3768 cursor to the end of the buffer.
3770 The command \\[set-goal-column] can be used to create
3771 a semipermanent goal column for this command.
3772 Then instead of trying to move exactly vertically (or as close as possible),
3773 this command moves to the specified goal column (or as close as possible).
3774 The goal column is stored in the variable `goal-column', which is nil
3775 when there is no goal column.
3777 If you are thinking of using this in a Lisp program, consider
3778 using `forward-line' instead. It is usually easier to use
3779 and more reliable (no dependence on goal column, etc.)."
3780 (interactive "^p\np")
3781 (or arg (setq arg 1))
3782 (if (and next-line-add-newlines (= arg 1))
3783 (if (save-excursion (end-of-line) (eobp))
3784 ;; When adding a newline, don't expand an abbrev.
3785 (let ((abbrev-mode nil))
3787 (insert (if use-hard-newlines hard-newline "\n")))
3788 (line-move arg nil nil try-vscroll))
3791 (line-move arg nil nil try-vscroll)
3792 ((beginning-of-buffer end-of-buffer) (ding)))
3793 (line-move arg nil nil try-vscroll)))
3796 (defun previous-line (&optional arg try-vscroll)
3797 "Move cursor vertically up ARG lines.
3798 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3799 If there is no character in the target line exactly over the current column,
3800 the cursor is positioned after the character in that line which spans this
3801 column, or at the end of the line if it is not long enough.
3803 The command \\[set-goal-column] can be used to create
3804 a semipermanent goal column for this command.
3805 Then instead of trying to move exactly vertically (or as close as possible),
3806 this command moves to the specified goal column (or as close as possible).
3807 The goal column is stored in the variable `goal-column', which is nil
3808 when there is no goal column.
3810 If you are thinking of using this in a Lisp program, consider using
3811 `forward-line' with a negative argument instead. It is usually easier
3812 to use and more reliable (no dependence on goal column, etc.)."
3813 (interactive "^p\np")
3814 (or arg (setq arg 1))
3817 (line-move (- arg) nil nil try-vscroll)
3818 ((beginning-of-buffer end-of-buffer) (ding)))
3819 (line-move (- arg) nil nil try-vscroll))
3822 (defcustom track-eol nil
3823 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
3824 This means moving to the end of each line moved onto.
3825 The beginning of a blank line does not count as the end of a line."
3827 :group 'editing-basics)
3829 (defcustom goal-column nil
3830 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3831 :type '(choice integer
3832 (const :tag "None" nil))
3833 :group 'editing-basics)
3834 (make-variable-buffer-local 'goal-column)
3836 (defvar temporary-goal-column 0
3837 "Current goal column for vertical motion.
3838 It is the column where point was
3839 at the start of current run of vertical motion commands.
3840 When the `track-eol' feature is doing its job, the value is `most-positive-fixnum'.")
3842 (defcustom line-move-ignore-invisible t
3843 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3844 Outline mode sets this."
3846 :group 'editing-basics)
3848 ;; Returns non-nil if partial move was done.
3849 (defun line-move-partial (arg noerror to-end)
3851 ;; Move backward (up).
3852 ;; If already vscrolled, reduce vscroll
3853 (let ((vs (window-vscroll nil t)))
3854 (when (> vs (frame-char-height))
3855 (set-window-vscroll nil (- vs (frame-char-height)) t)))
3857 ;; Move forward (down).
3858 (let* ((lh (window-line-height -1))
3864 (>= rbot (frame-char-height))
3865 (<= ypos (- (frame-char-height))))
3867 (let ((wend (pos-visible-in-window-p t nil t)))
3868 (setq rbot (nth 3 wend)
3869 vpos (nth 5 wend))))
3871 ;; If last line of window is fully visible, move forward.
3872 ((or (null rbot) (= rbot 0))
3874 ;; If cursor is not in the bottom scroll margin, move forward.
3877 (or (nth 1 (window-line-height))
3878 (let ((ppos (posn-at-point)))
3879 (cdr (or (posn-actual-col-row ppos)
3880 (posn-col-row ppos))))))
3881 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
3883 ;; When already vscrolled, we vscroll some more if we can,
3884 ;; or clear vscroll and move forward at end of tall image.
3885 ((> (setq vs (window-vscroll nil t)) 0)
3887 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
3888 ;; If cursor just entered the bottom scroll margin, move forward,
3889 ;; but also vscroll one line so redisplay wont recenter.
3891 (= py (min (- (window-text-height) scroll-margin 1)
3893 (set-window-vscroll nil (frame-char-height) t)
3894 (line-move-1 arg noerror to-end)
3896 ;; If there are lines above the last line, scroll-up one line.
3900 ;; Finally, start vscroll.
3902 (set-window-vscroll nil (frame-char-height) t)))))))
3905 ;; This is like line-move-1 except that it also performs
3906 ;; vertical scrolling of tall images if appropriate.
3907 ;; That is not really a clean thing to do, since it mixes
3908 ;; scrolling with cursor motion. But so far we don't have
3909 ;; a cleaner solution to the problem of making C-n do something
3910 ;; useful given a tall image.
3911 (defun line-move (arg &optional noerror to-end try-vscroll)
3912 (unless (and auto-window-vscroll try-vscroll
3913 ;; Only vscroll for single line moves
3915 ;; But don't vscroll in a keyboard macro.
3916 (not defining-kbd-macro)
3917 (not executing-kbd-macro)
3918 (line-move-partial arg noerror to-end))
3919 (set-window-vscroll nil 0 t)
3920 (line-move-1 arg noerror to-end)))
3922 ;; This is the guts of next-line and previous-line.
3923 ;; Arg says how many lines to move.
3924 ;; The value is t if we can move the specified number of lines.
3925 (defun line-move-1 (arg &optional noerror to-end)
3926 ;; Don't run any point-motion hooks, and disregard intangibility,
3927 ;; for intermediate positions.
3928 (let ((inhibit-point-motion-hooks t)
3933 (if (not (memq last-command '(next-line previous-line)))
3934 (setq temporary-goal-column
3935 (if (and track-eol (eolp)
3936 ;; Don't count beg of empty line as end of line
3937 ;; unless we just did explicit end-of-line.
3938 (or (not (bolp)) (eq last-command 'move-end-of-line)))
3939 most-positive-fixnum
3942 (if (not (or (integerp selective-display)
3943 line-move-ignore-invisible))
3944 ;; Use just newline characters.
3945 ;; Set ARG to 0 if we move as many lines as requested.
3947 (progn (if (> arg 1) (forward-line (1- arg)))
3948 ;; This way of moving forward ARG lines
3949 ;; verifies that we have a newline after the last one.
3950 ;; It doesn't get confused by intangible text.
3952 (if (zerop (forward-line 1))
3954 (and (zerop (forward-line arg))
3958 (signal (if (< arg 0)
3959 'beginning-of-buffer
3962 ;; Move by arg lines, but ignore invisible ones.
3964 (while (and (> arg 0) (not done))
3965 ;; If the following character is currently invisible,
3966 ;; skip all characters with that same `invisible' property value.
3967 (while (and (not (eobp)) (invisible-p (point)))
3968 (goto-char (next-char-property-change (point))))
3970 ;; We don't use `end-of-line', since we want to escape
3971 ;; from field boundaries ocurring exactly at point.
3972 (goto-char (constrain-to-field
3973 (let ((inhibit-field-text-motion t))
3974 (line-end-position))
3976 'inhibit-line-move-field-capture))
3977 ;; If there's no invisibility here, move over the newline.
3981 (signal 'end-of-buffer nil)
3983 ((and (> arg 1) ;; Use vertical-motion for last move
3984 (not (integerp selective-display))
3985 (not (invisible-p (point))))
3986 ;; We avoid vertical-motion when possible
3987 ;; because that has to fontify.
3989 ;; Otherwise move a more sophisticated way.
3990 ((zerop (vertical-motion 1))
3992 (signal 'end-of-buffer nil)
3995 (setq arg (1- arg))))
3996 ;; The logic of this is the same as the loop above,
3997 ;; it just goes in the other direction.
3998 (while (and (< arg 0) (not done))
3999 ;; For completely consistency with the forward-motion
4000 ;; case, we should call beginning-of-line here.
4001 ;; However, if point is inside a field and on a
4002 ;; continued line, the call to (vertical-motion -1)
4003 ;; below won't move us back far enough; then we return
4004 ;; to the same column in line-move-finish, and point
4005 ;; gets stuck -- cyd
4010 (signal 'beginning-of-buffer nil)
4012 ((and (< arg -1) ;; Use vertical-motion for last move
4013 (not (integerp selective-display))
4014 (not (invisible-p (1- (point)))))
4016 ((zerop (vertical-motion -1))
4018 (signal 'beginning-of-buffer nil)
4022 (while (and ;; Don't move over previous invis lines
4023 ;; if our target is the middle of this line.
4024 (or (zerop (or goal-column temporary-goal-column))
4026 (not (bobp)) (invisible-p (1- (point))))
4027 (goto-char (previous-char-property-change (point))))))))
4028 ;; This is the value the function returns.
4032 ;; If we did not move down as far as desired,
4033 ;; at least go to end of line.
4036 ;; If we did not move up as far as desired,
4037 ;; at least go to beginning of line.
4038 (beginning-of-line))
4040 (line-move-finish (or goal-column temporary-goal-column)
4041 opoint (> orig-arg 0)))))))
4043 (defun line-move-finish (column opoint forward)
4046 ;; Set REPEAT to t to repeat the whole thing.
4051 (line-beg (save-excursion (beginning-of-line) (point)))
4053 ;; Compute the end of the line
4054 ;; ignoring effectively invisible newlines.
4056 ;; Like end-of-line but ignores fields.
4057 (skip-chars-forward "^\n")
4058 (while (and (not (eobp)) (invisible-p (point)))
4059 (goto-char (next-char-property-change (point)))
4060 (skip-chars-forward "^\n"))
4063 ;; Move to the desired column.
4064 (line-move-to-column column)
4066 ;; Corner case: suppose we start out in a field boundary in
4067 ;; the middle of a continued line. When we get to
4068 ;; line-move-finish, point is at the start of a new *screen*
4069 ;; line but the same text line; then line-move-to-column would
4070 ;; move us backwards. Test using C-n with point on the "x" in
4071 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4078 ;; Process intangibility within a line.
4079 ;; With inhibit-point-motion-hooks bound to nil, a call to
4080 ;; goto-char moves point past intangible text.
4082 ;; However, inhibit-point-motion-hooks controls both the
4083 ;; intangibility and the point-entered/point-left hooks. The
4084 ;; following hack avoids calling the point-* hooks
4085 ;; unnecessarily. Note that we move *forward* past intangible
4086 ;; text when the initial and final points are the same.
4088 (let ((inhibit-point-motion-hooks nil))
4091 ;; If intangibility moves us to a different (later) place
4092 ;; in the same line, use that as the destination.
4093 (if (<= (point) line-end)
4095 ;; If that position is "too late",
4096 ;; try the previous allowable position.
4100 ;; If going forward, don't accept the previous
4101 ;; allowable position if it is before the target line.
4102 (< line-beg (point))
4103 ;; If going backward, don't accept the previous
4104 ;; allowable position if it is still after the target line.
4105 (<= (point) line-end))
4107 ;; As a last resort, use the end of the line.
4108 (setq new line-end))))
4110 ;; Now move to the updated destination, processing fields
4111 ;; as well as intangibility.
4113 (let ((inhibit-point-motion-hooks nil))
4115 ;; Ignore field boundaries if the initial and final
4116 ;; positions have the same `field' property, even if the
4117 ;; fields are non-contiguous. This seems to be "nicer"
4118 ;; behavior in many situations.
4119 (if (eq (get-char-property new 'field)
4120 (get-char-property opoint 'field))
4122 (constrain-to-field new opoint t t
4123 'inhibit-line-move-field-capture))))
4125 ;; If all this moved us to a different line,
4126 ;; retry everything within that new line.
4127 (when (or (< (point) line-beg) (> (point) line-end))
4128 ;; Repeat the intangibility and field processing.
4129 (setq repeat t))))))
4131 (defun line-move-to-column (col)
4132 "Try to find column COL, considering invisibility.
4133 This function works only in certain cases,
4134 because what we really need is for `move-to-column'
4135 and `current-column' to be able to ignore invisible text."
4138 (move-to-column col))
4140 (when (and line-move-ignore-invisible
4141 (not (bolp)) (invisible-p (1- (point))))
4142 (let ((normal-location (point))
4143 (normal-column (current-column)))
4144 ;; If the following character is currently invisible,
4145 ;; skip all characters with that same `invisible' property value.
4146 (while (and (not (eobp))
4147 (invisible-p (point)))
4148 (goto-char (next-char-property-change (point))))
4149 ;; Have we advanced to a larger column position?
4150 (if (> (current-column) normal-column)
4151 ;; We have made some progress towards the desired column.
4152 ;; See if we can make any further progress.
4153 (line-move-to-column (+ (current-column) (- col normal-column)))
4154 ;; Otherwise, go to the place we originally found
4155 ;; and move back over invisible text.
4156 ;; that will get us to the same place on the screen
4157 ;; but with a more reasonable buffer position.
4158 (goto-char normal-location)
4159 (let ((line-beg (save-excursion (beginning-of-line) (point))))
4160 (while (and (not (bolp)) (invisible-p (1- (point))))
4161 (goto-char (previous-char-property-change (point) line-beg))))))))
4163 (defun move-end-of-line (arg)
4164 "Move point to end of current line as displayed.
4165 \(If there's an image in the line, this disregards newlines
4166 which are part of the text that the image rests on.)
4168 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4169 If point reaches the beginning or end of buffer, it stops there.
4170 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4172 (or arg (setq arg 1))
4177 (let ((goal-column 0))
4178 (and (line-move arg t)
4181 (while (and (not (bobp)) (invisible-p (1- (point))))
4182 (goto-char (previous-single-char-property-change
4183 (point) 'invisible)))
4187 (if (and (> (point) newpos)
4188 (eq (preceding-char) ?\n))
4190 (if (and (> (point) newpos) (not (eobp))
4191 (not (eq (following-char) ?\n)))
4192 ;; If we skipped something intangible
4193 ;; and now we're not really at eol,
4198 (defun move-beginning-of-line (arg)
4199 "Move point to beginning of current line as displayed.
4200 \(If there's an image in the line, this disregards newlines
4201 which are part of the text that the image rests on.)
4203 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4204 If point reaches the beginning or end of buffer, it stops there.
4205 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4207 (or arg (setq arg 1))
4209 (let ((orig (point))
4210 first-vis first-vis-field-value)
4212 ;; Move by lines, if ARG is not 1 (the default).
4214 (line-move (1- arg) t))
4216 ;; Move to beginning-of-line, ignoring fields and invisibles.
4217 (skip-chars-backward "^\n")
4218 (while (and (not (bobp)) (invisible-p (1- (point))))
4219 (goto-char (previous-char-property-change (point)))
4220 (skip-chars-backward "^\n"))
4222 ;; Now find first visible char in the line
4223 (while (and (not (eobp)) (invisible-p (point)))
4224 (goto-char (next-char-property-change (point))))
4225 (setq first-vis (point))
4227 ;; See if fields would stop us from reaching FIRST-VIS.
4228 (setq first-vis-field-value
4229 (constrain-to-field first-vis orig (/= arg 1) t nil))
4231 (goto-char (if (/= first-vis-field-value first-vis)
4232 ;; If yes, obey them.
4233 first-vis-field-value
4234 ;; Otherwise, move to START with attention to fields.
4235 ;; (It is possible that fields never matter in this case.)
4236 (constrain-to-field (point) orig
4237 (/= arg 1) t nil)))))
4240 ;;; Many people have said they rarely use this feature, and often type
4241 ;;; it by accident. Maybe it shouldn't even be on a key.
4242 (put 'set-goal-column 'disabled t)
4244 (defun set-goal-column (arg)
4245 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4246 Those commands will move to this position in the line moved to
4247 rather than trying to keep the same horizontal position.
4248 With a non-nil argument, clears out the goal column
4249 so that \\[next-line] and \\[previous-line] resume vertical motion.
4250 The goal column is stored in the variable `goal-column'."
4254 (setq goal-column nil)
4255 (message "No goal column"))
4256 (setq goal-column (current-column))
4257 ;; The older method below can be erroneous if `set-goal-column' is bound
4258 ;; to a sequence containing %
4259 ;;(message (substitute-command-keys
4260 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4264 (format "Goal column %d " goal-column)
4265 (substitute-command-keys
4266 "(use \\[set-goal-column] with an arg to unset it)")))
4272 (defun scroll-other-window-down (lines)
4273 "Scroll the \"other window\" down.
4274 For more details, see the documentation for `scroll-other-window'."
4276 (scroll-other-window
4277 ;; Just invert the argument's meaning.
4278 ;; We can do that without knowing which window it will be.
4279 (if (eq lines '-) nil
4281 (- (prefix-numeric-value lines))))))
4283 (defun beginning-of-buffer-other-window (arg)
4284 "Move point to the beginning of the buffer in the other window.
4285 Leave mark at previous position.
4286 With arg N, put point N/10 of the way from the true beginning."
4288 (let ((orig-window (selected-window))
4289 (window (other-window-for-scrolling)))
4290 ;; We use unwind-protect rather than save-window-excursion
4291 ;; because the latter would preserve the things we want to change.
4294 (select-window window)
4295 ;; Set point and mark in that window's buffer.
4297 (beginning-of-buffer arg))
4298 ;; Set point accordingly.
4300 (select-window orig-window))))
4302 (defun end-of-buffer-other-window (arg)
4303 "Move point to the end of the buffer in the other window.
4304 Leave mark at previous position.
4305 With arg N, put point N/10 of the way from the true end."
4307 ;; See beginning-of-buffer-other-window for comments.
4308 (let ((orig-window (selected-window))
4309 (window (other-window-for-scrolling)))
4312 (select-window window)
4314 (end-of-buffer arg))
4316 (select-window orig-window))))
4318 (defun transpose-chars (arg)
4319 "Interchange characters around point, moving forward one character.
4320 With prefix arg ARG, effect is to take character before point
4321 and drag it forward past ARG other characters (backward if ARG negative).
4322 If no argument and at end of line, the previous two chars are exchanged."
4324 (and (null arg) (eolp) (forward-char -1))
4325 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4327 (defun transpose-words (arg)
4328 "Interchange words around point, leaving point at end of them.
4329 With prefix arg ARG, effect is to take word before or around point
4330 and drag it forward past ARG other words (backward if ARG negative).
4331 If ARG is zero, the words around or after point and around or after mark
4333 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
4335 (transpose-subr 'forward-word arg))
4337 (defun transpose-sexps (arg)
4338 "Like \\[transpose-words] but applies to sexps.
4339 Does not work on a sexp that point is in the middle of
4340 if it is a list or string."
4344 ;; Here we should try to simulate the behavior of
4345 ;; (cons (progn (forward-sexp x) (point))
4346 ;; (progn (forward-sexp (- x)) (point)))
4347 ;; Except that we don't want to rely on the second forward-sexp
4348 ;; putting us back to where we want to be, since forward-sexp-function
4349 ;; might do funny things like infix-precedence.
4351 (looking-at "\\sw\\|\\s_")
4353 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4354 ;; Jumping over a symbol. We might be inside it, mind you.
4355 (progn (funcall (if (> arg 0)
4356 'skip-syntax-backward 'skip-syntax-forward)
4358 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4359 ;; Otherwise, we're between sexps. Take a step back before jumping
4360 ;; to make sure we'll obey the same precedence no matter which direction
4362 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4363 (cons (save-excursion (forward-sexp arg) (point))
4364 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4365 (not (zerop (funcall (if (> arg 0)
4366 'skip-syntax-forward
4367 'skip-syntax-backward)
4372 (defun transpose-lines (arg)
4373 "Exchange current line and previous line, leaving point after both.
4374 With argument ARG, takes previous line and moves it past ARG lines.
4375 With argument 0, interchanges line point is in with line mark is in."
4377 (transpose-subr (function
4381 ;; Move forward over ARG lines,
4382 ;; but create newlines if necessary.
4383 (setq arg (forward-line arg))
4384 (if (/= (preceding-char) ?\n)
4385 (setq arg (1+ arg)))
4388 (forward-line arg))))
4391 (defun transpose-subr (mover arg &optional special)
4392 (let ((aux (if special mover
4394 (cons (progn (funcall mover x) (point))
4395 (progn (funcall mover (- x)) (point))))))
4400 (setq pos1 (funcall aux 1))
4402 (setq pos2 (funcall aux 1))
4403 (transpose-subr-1 pos1 pos2))
4404 (exchange-point-and-mark))
4406 (setq pos1 (funcall aux -1))
4407 (setq pos2 (funcall aux arg))
4408 (transpose-subr-1 pos1 pos2)
4409 (goto-char (car pos2)))
4411 (setq pos1 (funcall aux -1))
4412 (goto-char (car pos1))
4413 (setq pos2 (funcall aux arg))
4414 (transpose-subr-1 pos1 pos2)))))
4416 (defun transpose-subr-1 (pos1 pos2)
4417 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
4418 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
4419 (when (> (car pos1) (car pos2))
4421 (setq pos1 pos2 pos2 swap)))
4422 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
4423 (atomic-change-group
4425 ;; FIXME: We first delete the two pieces of text, so markers that
4426 ;; used to point to after the text end up pointing to before it :-(
4427 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
4428 (goto-char (car pos2))
4429 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
4430 (goto-char (car pos1))
4433 (defun backward-word (&optional arg)
4434 "Move backward until encountering the beginning of a word.
4435 With argument, do this that many times."
4437 (forward-word (- (or arg 1))))
4439 (defun mark-word (&optional arg allow-extend)
4440 "Set mark ARG words away from point.
4441 The place mark goes is the same place \\[forward-word] would
4442 move to with the same argument.
4443 Interactively, if this command is repeated
4444 or (in Transient Mark mode) if the mark is active,
4445 it marks the next ARG words after the ones already marked."
4446 (interactive "P\np")
4447 (cond ((and allow-extend
4448 (or (and (eq last-command this-command) (mark t))
4450 (setq arg (if arg (prefix-numeric-value arg)
4451 (if (< (mark) (point)) -1 1)))
4460 (forward-word (prefix-numeric-value arg))
4464 (defun kill-word (arg)
4465 "Kill characters forward until encountering the end of a word.
4466 With argument, do this that many times."
4468 (kill-region (point) (progn (forward-word arg) (point))))
4470 (defun backward-kill-word (arg)
4471 "Kill characters backward until encountering the beginning of a word.
4472 With argument, do this that many times."
4474 (kill-word (- arg)))
4476 (defun current-word (&optional strict really-word)
4477 "Return the symbol or word that point is on (or a nearby one) as a string.
4478 The return value includes no text properties.
4479 If optional arg STRICT is non-nil, return nil unless point is within
4480 or adjacent to a symbol or word. In all cases the value can be nil
4481 if there is no word nearby.
4482 The function, belying its name, normally finds a symbol.
4483 If optional arg REALLY-WORD is non-nil, it finds just a word."
4485 (let* ((oldpoint (point)) (start (point)) (end (point))
4486 (syntaxes (if really-word "w" "w_"))
4487 (not-syntaxes (concat "^" syntaxes)))
4488 (skip-syntax-backward syntaxes) (setq start (point))
4489 (goto-char oldpoint)
4490 (skip-syntax-forward syntaxes) (setq end (point))
4491 (when (and (eq start oldpoint) (eq end oldpoint)
4492 ;; Point is neither within nor adjacent to a word.
4494 ;; Look for preceding word in same line.
4495 (skip-syntax-backward not-syntaxes
4496 (save-excursion (beginning-of-line)
4499 ;; No preceding word in same line.
4500 ;; Look for following word in same line.
4502 (skip-syntax-forward not-syntaxes
4503 (save-excursion (end-of-line)
4505 (setq start (point))
4506 (skip-syntax-forward syntaxes)
4509 (skip-syntax-backward syntaxes)
4510 (setq start (point))))
4511 ;; If we found something nonempty, return it as a string.
4512 (unless (= start end)
4513 (buffer-substring-no-properties start end)))))
4515 (defcustom fill-prefix nil
4516 "*String for filling to insert at front of new line, or nil for none."
4517 :type '(choice (const :tag "None" nil)
4520 (make-variable-buffer-local 'fill-prefix)
4521 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
4523 (defcustom auto-fill-inhibit-regexp nil
4524 "*Regexp to match lines which should not be auto-filled."
4525 :type '(choice (const :tag "None" nil)
4529 ;; This function is used as the auto-fill-function of a buffer
4530 ;; when Auto-Fill mode is enabled.
4531 ;; It returns t if it really did any work.
4532 ;; (Actually some major modes use a different auto-fill function,
4533 ;; but this one is the default one.)
4534 (defun do-auto-fill ()
4535 (let (fc justify give-up
4536 (fill-prefix fill-prefix))
4537 (if (or (not (setq justify (current-justification)))
4538 (null (setq fc (current-fill-column)))
4539 (and (eq justify 'left)
4540 (<= (current-column) fc))
4541 (and auto-fill-inhibit-regexp
4542 (save-excursion (beginning-of-line)
4543 (looking-at auto-fill-inhibit-regexp))))
4544 nil ;; Auto-filling not required
4545 (if (memq justify '(full center right))
4546 (save-excursion (unjustify-current-line)))
4548 ;; Choose a fill-prefix automatically.
4549 (when (and adaptive-fill-mode
4550 (or (null fill-prefix) (string= fill-prefix "")))
4552 (fill-context-prefix
4553 (save-excursion (backward-paragraph 1) (point))
4554 (save-excursion (forward-paragraph 1) (point)))))
4555 (and prefix (not (equal prefix ""))
4556 ;; Use auto-indentation rather than a guessed empty prefix.
4557 (not (and fill-indent-according-to-mode
4558 (string-match "\\`[ \t]*\\'" prefix)))
4559 (setq fill-prefix prefix))))
4561 (while (and (not give-up) (> (current-column) fc))
4562 ;; Determine where to split the line.
4567 (setq after-prefix (point))
4569 (looking-at (regexp-quote fill-prefix))
4570 (setq after-prefix (match-end 0)))
4571 (move-to-column (1+ fc))
4572 (fill-move-to-break-point after-prefix)
4575 ;; See whether the place we found is any good.
4577 (goto-char fill-point)
4579 ;; There is no use breaking at end of line.
4580 (save-excursion (skip-chars-forward " ") (eolp))
4581 ;; It is futile to split at the end of the prefix
4582 ;; since we would just insert the prefix again.
4583 (and after-prefix (<= (point) after-prefix))
4584 ;; Don't split right after a comment starter
4585 ;; since we would just make another comment starter.
4586 (and comment-start-skip
4587 (let ((limit (point)))
4589 (and (re-search-forward comment-start-skip
4591 (eq (point) limit))))))
4592 ;; No good place to break => stop trying.
4594 ;; Ok, we have a useful place to break the line. Do it.
4595 (let ((prev-column (current-column)))
4596 ;; If point is at the fill-point, do not `save-excursion'.
4597 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4598 ;; point will end up before it rather than after it.
4600 (skip-chars-backward " \t")
4601 (= (point) fill-point))
4602 (default-indent-new-line t)
4604 (goto-char fill-point)
4605 (default-indent-new-line t)))
4606 ;; Now do justification, if required
4607 (if (not (eq justify 'left))
4610 (justify-current-line justify nil t)))
4611 ;; If making the new line didn't reduce the hpos of
4612 ;; the end of the line, then give up now;
4613 ;; trying again will not help.
4614 (if (>= (current-column) prev-column)
4615 (setq give-up t))))))
4616 ;; Justify last line.
4617 (justify-current-line justify t t)
4620 (defvar comment-line-break-function 'comment-indent-new-line
4621 "*Mode-specific function which line breaks and continues a comment.
4622 This function is called during auto-filling when a comment syntax
4624 The function should take a single optional argument, which is a flag
4625 indicating whether it should use soft newlines.")
4627 (defun default-indent-new-line (&optional soft)
4628 "Break line at point and indent.
4629 If a comment syntax is defined, call `comment-indent-new-line'.
4631 The inserted newline is marked hard if variable `use-hard-newlines' is true,
4632 unless optional argument SOFT is non-nil."
4635 (funcall comment-line-break-function soft)
4636 ;; Insert the newline before removing empty space so that markers
4637 ;; get preserved better.
4638 (if soft (insert-and-inherit ?\n) (newline 1))
4639 (save-excursion (forward-char -1) (delete-horizontal-space))
4640 (delete-horizontal-space)
4642 (if (and fill-prefix (not adaptive-fill-mode))
4643 ;; Blindly trust a non-adaptive fill-prefix.
4645 (indent-to-left-margin)
4646 (insert-before-markers-and-inherit fill-prefix))
4649 ;; If there's an adaptive prefix, use it unless we're inside
4650 ;; a comment and the prefix is not a comment starter.
4652 (indent-to-left-margin)
4653 (insert-and-inherit fill-prefix))
4654 ;; If we're not inside a comment, just try to indent.
4655 (t (indent-according-to-mode))))))
4657 (defvar normal-auto-fill-function 'do-auto-fill
4658 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4659 Some major modes set this.")
4661 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
4662 ;; FIXME: turn into a proper minor mode.
4663 ;; Add a global minor mode version of it.
4664 (defun auto-fill-mode (&optional arg)
4665 "Toggle Auto Fill mode.
4666 With arg, turn Auto Fill mode on if and only if arg is positive.
4667 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4668 automatically breaks the line at a previous space.
4670 The value of `normal-auto-fill-function' specifies the function to use
4671 for `auto-fill-function' when turning Auto Fill mode on."
4673 (prog1 (setq auto-fill-function
4675 (not auto-fill-function)
4676 (> (prefix-numeric-value arg) 0))
4677 normal-auto-fill-function
4679 (force-mode-line-update)))
4681 ;; This holds a document string used to document auto-fill-mode.
4682 (defun auto-fill-function ()
4683 "Automatically break line at a previous space, in insertion of text."
4686 (defun turn-on-auto-fill ()
4687 "Unconditionally turn on Auto Fill mode."
4690 (defun turn-off-auto-fill ()
4691 "Unconditionally turn off Auto Fill mode."
4692 (auto-fill-mode -1))
4694 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
4696 (defun set-fill-column (arg)
4697 "Set `fill-column' to specified argument.
4698 Use \\[universal-argument] followed by a number to specify a column.
4699 Just \\[universal-argument] as argument means to use the current column."
4701 (list (or current-prefix-arg
4702 ;; We used to use current-column silently, but C-x f is too easily
4703 ;; typed as a typo for C-x C-f, so we turned it into an error and
4704 ;; now an interactive prompt.
4705 (read-number "Set fill-column to: " (current-column)))))
4707 (setq arg (current-column)))
4708 (if (not (integerp arg))
4709 ;; Disallow missing argument; it's probably a typo for C-x C-f.
4710 (error "set-fill-column requires an explicit argument")
4711 (message "Fill column set to %d (was %d)" arg fill-column)
4712 (setq fill-column arg)))
4714 (defun set-selective-display (arg)
4715 "Set `selective-display' to ARG; clear it if no arg.
4716 When the value of `selective-display' is a number > 0,
4717 lines whose indentation is >= that value are not displayed.
4718 The variable `selective-display' has a separate value for each buffer."
4720 (if (eq selective-display t)
4721 (error "selective-display already in use for marked lines"))
4724 (narrow-to-region (point-min) (point))
4725 (goto-char (window-start))
4726 (vertical-motion (window-height)))))
4727 (setq selective-display
4728 (and arg (prefix-numeric-value arg)))
4729 (recenter current-vpos))
4730 (set-window-start (selected-window) (window-start (selected-window)))
4731 (princ "selective-display set to " t)
4732 (prin1 selective-display t)
4735 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
4737 (defun toggle-truncate-lines (&optional arg)
4738 "Toggle whether to fold or truncate long lines for the current buffer.
4739 With prefix argument ARG, truncate long lines if ARG is positive,
4740 otherwise don't truncate them. Note that in side-by-side
4741 windows, truncation is always enabled."
4743 (setq truncate-lines
4745 (not truncate-lines)
4746 (> (prefix-numeric-value arg) 0)))
4747 (force-mode-line-update)
4748 (unless truncate-lines
4749 (let ((buffer (current-buffer)))
4750 (walk-windows (lambda (window)
4751 (if (eq buffer (window-buffer window))
4752 (set-window-hscroll window 0)))
4754 (message "Truncate long lines %s"
4755 (if truncate-lines "enabled" "disabled")))
4757 (defvar overwrite-mode-textual " Ovwrt"
4758 "The string displayed in the mode line when in overwrite mode.")
4759 (defvar overwrite-mode-binary " Bin Ovwrt"
4760 "The string displayed in the mode line when in binary overwrite mode.")
4762 (defun overwrite-mode (arg)
4763 "Toggle overwrite mode.
4764 With prefix argument ARG, turn overwrite mode on if ARG is positive,
4765 otherwise turn it off. In overwrite mode, printing characters typed
4766 in replace existing text on a one-for-one basis, rather than pushing
4767 it to the right. At the end of a line, such characters extend the line.
4768 Before a tab, such characters insert until the tab is filled in.
4769 \\[quoted-insert] still inserts characters in overwrite mode; this
4770 is supposed to make it easier to insert characters when necessary."
4772 (setq overwrite-mode
4773 (if (if (null arg) (not overwrite-mode)
4774 (> (prefix-numeric-value arg) 0))
4775 'overwrite-mode-textual))
4776 (force-mode-line-update))
4778 (defun binary-overwrite-mode (arg)
4779 "Toggle binary overwrite mode.
4780 With prefix argument ARG, turn binary overwrite mode on if ARG is
4781 positive, otherwise turn it off. In binary overwrite mode, printing
4782 characters typed in replace existing text. Newlines are not treated
4783 specially, so typing at the end of a line joins the line to the next,
4784 with the typed character between them. Typing before a tab character
4785 simply replaces the tab with the character typed. \\[quoted-insert]
4786 replaces the text at the cursor, just as ordinary typing characters do.
4788 Note that binary overwrite mode is not its own minor mode; it is a
4789 specialization of overwrite mode, entered by setting the
4790 `overwrite-mode' variable to `overwrite-mode-binary'."
4792 (setq overwrite-mode
4794 (not (eq overwrite-mode 'overwrite-mode-binary))
4795 (> (prefix-numeric-value arg) 0))
4796 'overwrite-mode-binary))
4797 (force-mode-line-update))
4799 (define-minor-mode line-number-mode
4800 "Toggle Line Number mode.
4801 With arg, turn Line Number mode on if arg is positive, otherwise
4802 turn it off. When Line Number mode is enabled, the line number
4803 appears in the mode line.
4805 Line numbers do not appear for very large buffers and buffers
4806 with very long lines; see variables `line-number-display-limit'
4807 and `line-number-display-limit-width'."
4808 :init-value t :global t :group 'mode-line)
4810 (define-minor-mode column-number-mode
4811 "Toggle Column Number mode.
4812 With arg, turn Column Number mode on if arg is positive,
4813 otherwise turn it off. When Column Number mode is enabled, the
4814 column number appears in the mode line."
4815 :global t :group 'mode-line)
4817 (define-minor-mode size-indication-mode
4818 "Toggle Size Indication mode.
4819 With arg, turn Size Indication mode on if arg is positive,
4820 otherwise turn it off. When Size Indication mode is enabled, the
4821 size of the accessible part of the buffer appears in the mode line."
4822 :global t :group 'mode-line)
4824 (defgroup paren-blinking nil
4825 "Blinking matching of parens and expressions."
4826 :prefix "blink-matching-"
4827 :group 'paren-matching)
4829 (defcustom blink-matching-paren t
4830 "*Non-nil means show matching open-paren when close-paren is inserted."
4832 :group 'paren-blinking)
4834 (defcustom blink-matching-paren-on-screen t
4835 "*Non-nil means show matching open-paren when it is on screen.
4836 If nil, don't show it (but the open-paren can still be shown
4837 when it is off screen).
4839 This variable has no effect if `blink-matching-paren' is nil.
4840 \(In that case, the open-paren is never shown.)
4841 It is also ignored if `show-paren-mode' is enabled."
4843 :group 'paren-blinking)
4845 (defcustom blink-matching-paren-distance (* 25 1024)
4846 "*If non-nil, maximum distance to search backwards for matching open-paren.
4847 If nil, search stops at the beginning of the accessible portion of the buffer."
4848 :type '(choice (const nil) integer)
4849 :group 'paren-blinking)
4851 (defcustom blink-matching-delay 1
4852 "*Time in seconds to delay after showing a matching paren."
4854 :group 'paren-blinking)
4856 (defcustom blink-matching-paren-dont-ignore-comments nil
4857 "*If nil, `blink-matching-paren' ignores comments.
4858 More precisely, when looking for the matching parenthesis,
4859 it skips the contents of comments that end before point."
4861 :group 'paren-blinking)
4863 (defun blink-matching-open ()
4864 "Move cursor momentarily to the beginning of the sexp before point."
4866 (when (and (> (point) (point-min))
4867 blink-matching-paren
4868 ;; Verify an even number of quoting characters precede the close.
4869 (= 1 (logand 1 (- (point)
4872 (skip-syntax-backward "/\\")
4874 (let* ((oldpos (point))
4875 (message-log-max nil) ; Don't log messages about paren matching.
4876 (atdollar (eq (syntax-class (syntax-after (1- oldpos))) 8))
4881 (if blink-matching-paren-distance
4883 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
4884 (- (point) blink-matching-paren-distance))
4886 (let ((parse-sexp-ignore-comments
4887 (and parse-sexp-ignore-comments
4888 (not blink-matching-paren-dont-ignore-comments))))
4890 (scan-sexps oldpos -1)
4896 (eq (syntax-class (syntax-after blinkpos)) 8)))
4897 (let ((syntax (syntax-after blinkpos)))
4899 (eq (syntax-class syntax) 4)
4903 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-10/msg00871.html
4904 ((not (or (and isdollar blinkpos)
4905 (and atdollar (not blinkpos)) ; see below
4906 (eq matching-paren (char-before oldpos))
4907 ;; The cdr might hold a new paren-class info rather than
4908 ;; a matching-char info, in which case the two CDRs
4910 (eq matching-paren (cdr (syntax-after (1- oldpos))))))
4911 (message "Mismatched parentheses"))
4913 (or blink-matching-paren-distance
4914 ;; Don't complain when `$' with no blinkpos, because it
4915 ;; could just be the first one typed in the buffer.
4917 (message "Unmatched parenthesis")))
4918 ((pos-visible-in-window-p blinkpos)
4919 ;; Matching open within window, temporarily move to blinkpos but only
4920 ;; if `blink-matching-paren-on-screen' is non-nil.
4921 (and blink-matching-paren-on-screen
4922 (not show-paren-mode)
4924 (goto-char blinkpos)
4925 (sit-for blink-matching-delay))))
4928 (goto-char blinkpos)
4929 (let ((open-paren-line-string
4930 ;; Show what precedes the open in its line, if anything.
4932 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
4933 (buffer-substring (line-beginning-position)
4935 ;; Show what follows the open in its line, if anything.
4938 (skip-chars-forward " \t")
4940 (buffer-substring blinkpos
4941 (line-end-position)))
4942 ;; Otherwise show the previous nonblank line,
4944 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
4946 (buffer-substring (progn
4947 (skip-chars-backward "\n \t")
4948 (line-beginning-position))
4949 (progn (end-of-line)
4950 (skip-chars-backward " \t")
4952 ;; Replace the newline and other whitespace with `...'.
4954 (buffer-substring blinkpos (1+ blinkpos))))
4955 ;; There is nothing to show except the char itself.
4956 (t (buffer-substring blinkpos (1+ blinkpos))))))
4957 (message "Matches %s"
4958 (substring-no-properties open-paren-line-string)))))))))
4960 ;; Turned off because it makes dbx bomb out.
4961 (setq blink-paren-function 'blink-matching-open)
4963 ;; This executes C-g typed while Emacs is waiting for a command.
4964 ;; Quitting out of a program does not go through here;
4965 ;; that happens in the QUIT macro at the C code level.
4966 (defun keyboard-quit ()
4967 "Signal a `quit' condition.
4968 During execution of Lisp code, this character causes a quit directly.
4969 At top-level, as an editor command, this simply beeps."
4972 (if (fboundp 'kmacro-keyboard-quit)
4973 (kmacro-keyboard-quit))
4974 (setq defining-kbd-macro nil)
4977 (defvar buffer-quit-function nil
4978 "Function to call to \"quit\" the current buffer, or nil if none.
4979 \\[keyboard-escape-quit] calls this function when its more local actions
4980 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4982 (defun keyboard-escape-quit ()
4983 "Exit the current \"mode\" (in a generalized sense of the word).
4984 This command can exit an interactive command such as `query-replace',
4985 can clear out a prefix argument or a region,
4986 can get out of the minibuffer or other recursive edit,
4987 cancel the use of the current buffer (for special-purpose buffers),
4988 or go back to just one window (by deleting all but the selected window)."
4990 (cond ((eq last-command 'mode-exited) nil)
4991 ((> (minibuffer-depth) 0)
4992 (abort-recursive-edit))
4997 ((> (recursion-depth) 0)
4998 (exit-recursive-edit))
4999 (buffer-quit-function
5000 (funcall buffer-quit-function))
5001 ((not (one-window-p t))
5002 (delete-other-windows))
5003 ((string-match "^ \\*" (buffer-name (current-buffer)))
5006 (defun play-sound-file (file &optional volume device)
5007 "Play sound stored in FILE.
5008 VOLUME and DEVICE correspond to the keywords of the sound
5009 specification for `play-sound'."
5010 (interactive "fPlay sound file: ")
5011 (let ((sound (list :file file)))
5013 (plist-put sound :volume volume))
5015 (plist-put sound :device device))
5017 (play-sound sound)))
5020 (defcustom read-mail-command 'rmail
5021 "*Your preference for a mail reading package.
5022 This is used by some keybindings which support reading mail.
5023 See also `mail-user-agent' concerning sending mail."
5024 :type '(choice (function-item rmail)
5025 (function-item gnus)
5026 (function-item mh-rmail)
5027 (function :tag "Other"))
5031 (defcustom mail-user-agent 'sendmail-user-agent
5032 "*Your preference for a mail composition package.
5033 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
5034 outgoing email message. This variable lets you specify which
5035 mail-sending package you prefer.
5037 Valid values include:
5039 `sendmail-user-agent' -- use the default Emacs Mail package.
5040 See Info node `(emacs)Sending Mail'.
5041 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5042 See Info node `(mh-e)'.
5043 `message-user-agent' -- use the Gnus Message package.
5044 See Info node `(message)'.
5045 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5046 paraphernalia, particularly the Gcc: header for
5049 Additional valid symbols may be available; check with the author of
5050 your package for details. The function should return non-nil if it
5053 See also `read-mail-command' concerning reading mail."
5054 :type '(radio (function-item :tag "Default Emacs mail"
5056 sendmail-user-agent)
5057 (function-item :tag "Emacs interface to MH"
5060 (function-item :tag "Gnus Message package"
5063 (function-item :tag "Gnus Message with full Gnus features"
5066 (function :tag "Other"))
5069 (define-mail-user-agent 'sendmail-user-agent
5070 'sendmail-user-agent-compose
5071 'mail-send-and-exit)
5073 (defun rfc822-goto-eoh ()
5074 ;; Go to header delimiter line in a mail message, following RFC822 rules
5075 (goto-char (point-min))
5076 (when (re-search-forward
5077 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5078 (goto-char (match-beginning 0))))
5080 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
5081 switch-function yank-action
5084 (let ((special-display-buffer-names nil)
5085 (special-display-regexps nil)
5086 (same-window-buffer-names nil)
5087 (same-window-regexps nil))
5088 (funcall switch-function "*mail*")))
5089 (let ((cc (cdr (assoc-string "cc" other-headers t)))
5090 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
5091 (body (cdr (assoc-string "body" other-headers t))))
5092 (or (mail continue to subject in-reply-to cc yank-action send-actions)
5094 (error "Message aborted"))
5097 (while other-headers
5098 (unless (member-ignore-case (car (car other-headers))
5099 '("in-reply-to" "cc" "body"))
5100 (insert (car (car other-headers)) ": "
5101 (cdr (car other-headers))
5102 (if use-hard-newlines hard-newline "\n")))
5103 (setq other-headers (cdr other-headers)))
5109 (defun compose-mail (&optional to subject other-headers continue
5110 switch-function yank-action send-actions)
5111 "Start composing a mail message to send.
5112 This uses the user's chosen mail composition package
5113 as selected with the variable `mail-user-agent'.
5114 The optional arguments TO and SUBJECT specify recipients
5115 and the initial Subject field, respectively.
5117 OTHER-HEADERS is an alist specifying additional
5118 header fields. Elements look like (HEADER . VALUE) where both
5119 HEADER and VALUE are strings.
5121 CONTINUE, if non-nil, says to continue editing a message already
5124 SWITCH-FUNCTION, if non-nil, is a function to use to
5125 switch to and display the buffer used for mail composition.
5127 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
5128 to insert the raw text of the message being replied to.
5129 It has the form (FUNCTION . ARGS). The user agent will apply
5130 FUNCTION to ARGS, to insert the raw text of the original message.
5131 \(The user agent will also run `mail-citation-hook', *after* the
5132 original text has been inserted in this way.)
5134 SEND-ACTIONS is a list of actions to call when the message is sent.
5135 Each action has the form (FUNCTION . ARGS)."
5137 (list nil nil nil current-prefix-arg))
5138 (let ((function (get mail-user-agent 'composefunc)))
5139 (funcall function to subject other-headers continue
5140 switch-function yank-action send-actions)))
5142 (defun compose-mail-other-window (&optional to subject other-headers continue
5143 yank-action send-actions)
5144 "Like \\[compose-mail], but edit the outgoing message in another window."
5146 (list nil nil nil current-prefix-arg))
5147 (compose-mail to subject other-headers continue
5148 'switch-to-buffer-other-window yank-action send-actions))
5151 (defun compose-mail-other-frame (&optional to subject other-headers continue
5152 yank-action send-actions)
5153 "Like \\[compose-mail], but edit the outgoing message in another frame."
5155 (list nil nil nil current-prefix-arg))
5156 (compose-mail to subject other-headers continue
5157 'switch-to-buffer-other-frame yank-action send-actions))
5159 (defvar set-variable-value-history nil
5160 "History of values entered with `set-variable'.
5162 Maximum length of the history list is determined by the value
5163 of `history-length', which see.")
5165 (defun set-variable (variable value &optional make-local)
5166 "Set VARIABLE to VALUE. VALUE is a Lisp object.
5167 VARIABLE should be a user option variable name, a Lisp variable
5168 meant to be customized by users. You should enter VALUE in Lisp syntax,
5169 so if you want VALUE to be a string, you must surround it with doublequotes.
5170 VALUE is used literally, not evaluated.
5172 If VARIABLE has a `variable-interactive' property, that is used as if
5173 it were the arg to `interactive' (which see) to interactively read VALUE.
5175 If VARIABLE has been defined with `defcustom', then the type information
5176 in the definition is used to check that VALUE is valid.
5178 With a prefix argument, set VARIABLE to VALUE buffer-locally."
5180 (let* ((default-var (variable-at-point))
5181 (var (if (user-variable-p default-var)
5182 (read-variable (format "Set variable (default %s): " default-var)
5184 (read-variable "Set variable: ")))
5185 (minibuffer-help-form '(describe-variable var))
5186 (prop (get var 'variable-interactive))
5187 (obsolete (car (get var 'byte-obsolete-variable)))
5188 (prompt (format "Set %s %s to value: " var
5189 (cond ((local-variable-p var)
5191 ((or current-prefix-arg
5192 (local-variable-if-set-p var))
5197 (message (concat "`%S' is obsolete; "
5198 (if (symbolp obsolete) "use `%S' instead" "%s"))
5202 ;; Use VAR's `variable-interactive' property
5203 ;; as an interactive spec for prompting.
5204 (call-interactively `(lambda (arg)
5208 (read-string prompt nil
5209 'set-variable-value-history
5210 (format "%S" (symbol-value var))))))))
5211 (list var val current-prefix-arg)))
5213 (and (custom-variable-p variable)
5214 (not (get variable 'custom-type))
5215 (custom-load-symbol variable))
5216 (let ((type (get variable 'custom-type)))
5218 ;; Match with custom type.
5220 (setq type (widget-convert type))
5221 (unless (widget-apply type :match value)
5222 (error "Value `%S' does not match type %S of %S"
5223 value (car type) variable))))
5226 (make-local-variable variable))
5228 (set variable value)
5230 ;; Force a thorough redisplay for the case that the variable
5231 ;; has an effect on the display, like `tab-width' has.
5232 (force-mode-line-update))
5234 ;; Define the major mode for lists of completions.
5236 (defvar completion-list-mode-map nil
5237 "Local map for completion list buffers.")
5238 (or completion-list-mode-map
5239 (let ((map (make-sparse-keymap)))
5240 (define-key map [mouse-2] 'mouse-choose-completion)
5241 (define-key map [follow-link] 'mouse-face)
5242 (define-key map [down-mouse-2] nil)
5243 (define-key map "\C-m" 'choose-completion)
5244 (define-key map "\e\e\e" 'delete-completion-window)
5245 (define-key map [left] 'previous-completion)
5246 (define-key map [right] 'next-completion)
5247 (setq completion-list-mode-map map)))
5249 ;; Completion mode is suitable only for specially formatted data.
5250 (put 'completion-list-mode 'mode-class 'special)
5252 (defvar completion-reference-buffer nil
5253 "Record the buffer that was current when the completion list was requested.
5254 This is a local variable in the completion list buffer.
5255 Initial value is nil to avoid some compiler warnings.")
5257 (defvar completion-no-auto-exit nil
5258 "Non-nil means `choose-completion-string' should never exit the minibuffer.
5259 This also applies to other functions such as `choose-completion'
5260 and `mouse-choose-completion'.")
5262 (defvar completion-base-size nil
5263 "Number of chars at beginning of minibuffer not involved in completion.
5264 This is a local variable in the completion list buffer
5265 but it talks about the buffer in `completion-reference-buffer'.
5266 If this is nil, it means to compare text to determine which part
5267 of the tail end of the buffer's text is involved in completion.")
5269 (defun delete-completion-window ()
5270 "Delete the completion list window.
5271 Go to the window from which completion was requested."
5273 (let ((buf completion-reference-buffer))
5274 (if (one-window-p t)
5275 (if (window-dedicated-p (selected-window))
5276 (delete-frame (selected-frame)))
5277 (delete-window (selected-window))
5278 (if (get-buffer-window buf)
5279 (select-window (get-buffer-window buf))))))
5281 (defun previous-completion (n)
5282 "Move to the previous item in the completion list."
5284 (next-completion (- n)))
5286 (defun next-completion (n)
5287 "Move to the next item in the completion list.
5288 With prefix argument N, move N items (negative N means move backward)."
5290 (let ((beg (point-min)) (end (point-max)))
5291 (while (and (> n 0) (not (eobp)))
5292 ;; If in a completion, move to the end of it.
5293 (when (get-text-property (point) 'mouse-face)
5294 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5295 ;; Move to start of next one.
5296 (unless (get-text-property (point) 'mouse-face)
5297 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5299 (while (and (< n 0) (not (bobp)))
5300 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
5301 ;; If in a completion, move to the start of it.
5302 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
5303 (goto-char (previous-single-property-change
5304 (point) 'mouse-face nil beg)))
5305 ;; Move to end of the previous completion.
5306 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
5307 (goto-char (previous-single-property-change
5308 (point) 'mouse-face nil beg)))
5309 ;; Move to the start of that one.
5310 (goto-char (previous-single-property-change
5311 (point) 'mouse-face nil beg))
5314 (defun choose-completion ()
5315 "Choose the completion that point is in or next to."
5317 (let (beg end completion (buffer completion-reference-buffer)
5318 (base-size completion-base-size))
5319 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
5320 (setq end (point) beg (1+ (point))))
5321 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
5322 (setq end (1- (point)) beg (point)))
5324 (error "No completion here"))
5325 (setq beg (previous-single-property-change beg 'mouse-face))
5326 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
5327 (setq completion (buffer-substring-no-properties beg end))
5328 (let ((owindow (selected-window)))
5329 (if (and (one-window-p t 'selected-frame)
5330 (window-dedicated-p (selected-window)))
5331 ;; This is a special buffer's frame
5332 (iconify-frame (selected-frame))
5333 (or (window-dedicated-p (selected-window))
5335 (select-window owindow))
5336 (choose-completion-string completion buffer base-size)))
5338 ;; Delete the longest partial match for STRING
5339 ;; that can be found before POINT.
5340 (defun choose-completion-delete-max-match (string)
5341 (let ((opoint (point))
5343 ;; Try moving back by the length of the string.
5344 (goto-char (max (- (point) (length string))
5345 (minibuffer-prompt-end)))
5346 ;; See how far back we were actually able to move. That is the
5347 ;; upper bound on how much we can match and delete.
5348 (setq len (- opoint (point)))
5349 (if completion-ignore-case
5350 (setq string (downcase string)))
5351 (while (and (> len 0)
5352 (let ((tail (buffer-substring (point) opoint)))
5353 (if completion-ignore-case
5354 (setq tail (downcase tail)))
5355 (not (string= tail (substring string 0 len)))))
5360 (defvar choose-completion-string-functions nil
5361 "Functions that may override the normal insertion of a completion choice.
5362 These functions are called in order with four arguments:
5363 CHOICE - the string to insert in the buffer,
5364 BUFFER - the buffer in which the choice should be inserted,
5365 MINI-P - non-nil if BUFFER is a minibuffer, and
5366 BASE-SIZE - the number of characters in BUFFER before
5367 the string being completed.
5369 If a function in the list returns non-nil, that function is supposed
5370 to have inserted the CHOICE in the BUFFER, and possibly exited
5371 the minibuffer; no further functions will be called.
5373 If all functions in the list return nil, that means to use
5374 the default method of inserting the completion in BUFFER.")
5376 (defun choose-completion-string (choice &optional buffer base-size)
5377 "Switch to BUFFER and insert the completion choice CHOICE.
5378 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
5379 to keep. If it is nil, we call `choose-completion-delete-max-match'
5380 to decide what to delete."
5382 ;; If BUFFER is the minibuffer, exit the minibuffer
5383 ;; unless it is reading a file name and CHOICE is a directory,
5384 ;; or completion-no-auto-exit is non-nil.
5386 (let* ((buffer (or buffer completion-reference-buffer))
5387 (mini-p (minibufferp buffer)))
5388 ;; If BUFFER is a minibuffer, barf unless it's the currently
5389 ;; active minibuffer.
5391 (or (not (active-minibuffer-window))
5393 (window-buffer (active-minibuffer-window))))))
5394 (error "Minibuffer is not active for completion")
5395 ;; Set buffer so buffer-local choose-completion-string-functions works.
5397 (unless (run-hook-with-args-until-success
5398 'choose-completion-string-functions
5399 choice buffer mini-p base-size)
5400 ;; Insert the completion into the buffer where it was requested.
5402 (delete-region (+ base-size (if mini-p
5403 (minibuffer-prompt-end)
5406 (choose-completion-delete-max-match choice))
5408 (remove-text-properties (- (point) (length choice)) (point)
5410 ;; Update point in the window that BUFFER is showing in.
5411 (let ((window (get-buffer-window buffer t)))
5412 (set-window-point window (point)))
5413 ;; If completing for the minibuffer, exit it with this choice.
5414 (and (not completion-no-auto-exit)
5415 (equal buffer (window-buffer (minibuffer-window)))
5416 minibuffer-completion-table
5417 ;; If this is reading a file name, and the file name chosen
5418 ;; is a directory, don't exit the minibuffer.
5419 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
5420 (file-directory-p (field-string (point-max))))
5421 (let ((mini (active-minibuffer-window)))
5422 (select-window mini)
5423 (when minibuffer-auto-raise
5424 (raise-frame (window-frame mini))))
5425 (exit-minibuffer)))))))
5427 (defun completion-list-mode ()
5428 "Major mode for buffers showing lists of possible completions.
5429 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
5430 to select the completion near point.
5431 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
5434 \\{completion-list-mode-map}"
5437 (kill-all-local-variables)
5438 (use-local-map completion-list-mode-map)
5439 (setq mode-name "Completion List")
5440 (setq major-mode 'completion-list-mode)
5441 (make-local-variable 'completion-base-size)
5442 (setq completion-base-size nil)
5443 (run-mode-hooks 'completion-list-mode-hook))
5445 (defun completion-list-mode-finish ()
5446 "Finish setup of the completions buffer.
5447 Called from `temp-buffer-show-hook'."
5448 (when (eq major-mode 'completion-list-mode)
5449 (toggle-read-only 1)))
5451 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
5453 (defvar completion-setup-hook nil
5454 "Normal hook run at the end of setting up a completion list buffer.
5455 When this hook is run, the current buffer is the one in which the
5456 command to display the completion list buffer was run.
5457 The completion list buffer is available as the value of `standard-output'.
5458 The common prefix substring for completion may be available as the
5459 value of `completion-common-substring'. See also `display-completion-list'.")
5462 ;; Variables and faces used in `completion-setup-function'.
5464 (defcustom completion-show-help t
5465 "Non-nil means show help message in *Completions* buffer."
5470 (defface completions-first-difference
5471 '((t (:inherit bold)))
5472 "Face put on the first uncommon character in completions in *Completions* buffer."
5475 (defface completions-common-part
5476 '((t (:inherit default)))
5477 "Face put on the common prefix substring in completions in *Completions* buffer.
5478 The idea of `completions-common-part' is that you can use it to
5479 make the common parts less visible than normal, so that the rest
5480 of the differing parts is, by contrast, slightly highlighted."
5483 ;; This is for packages that need to bind it to a non-default regexp
5484 ;; in order to make the first-differing character highlight work
5486 (defvar completion-root-regexp "^/"
5487 "Regexp to use in `completion-setup-function' to find the root directory.")
5489 (defvar completion-common-substring nil
5490 "Common prefix substring to use in `completion-setup-function' to put faces.
5491 The value is set by `display-completion-list' during running `completion-setup-hook'.
5493 To put faces `completions-first-difference' and `completions-common-part'
5494 in the `*Completions*' buffer, the common prefix substring in completions
5495 is needed as a hint. (The minibuffer is a special case. The content
5496 of the minibuffer before point is always the common substring.)")
5498 ;; This function goes in completion-setup-hook, so that it is called
5499 ;; after the text of the completion list buffer is written.
5500 (defun completion-setup-function ()
5501 (let* ((mainbuf (current-buffer))
5502 (mbuf-contents (minibuffer-completion-contents))
5503 common-string-length)
5504 ;; When reading a file name in the minibuffer,
5505 ;; set default-directory in the minibuffer
5506 ;; so it will get copied into the completion list buffer.
5507 (if minibuffer-completing-file-name
5508 (with-current-buffer mainbuf
5509 (setq default-directory
5510 (file-name-directory (expand-file-name mbuf-contents)))))
5511 (with-current-buffer standard-output
5512 (completion-list-mode)
5513 (set (make-local-variable 'completion-reference-buffer) mainbuf)
5514 (setq completion-base-size
5516 ((and (symbolp minibuffer-completion-table)
5517 (get minibuffer-completion-table 'completion-base-size-function))
5518 ;; To compute base size, a function can use the global value of
5519 ;; completion-common-substring or minibuffer-completion-contents.
5520 (with-current-buffer mainbuf
5521 (funcall (get minibuffer-completion-table
5522 'completion-base-size-function))))
5523 (minibuffer-completing-file-name
5524 ;; For file name completion, use the number of chars before
5525 ;; the start of the file name component at point.
5526 (with-current-buffer mainbuf
5528 (skip-chars-backward completion-root-regexp)
5529 (- (point) (minibuffer-prompt-end)))))
5530 (minibuffer-completing-symbol nil)
5531 ;; Otherwise, in minibuffer, the base size is 0.
5532 ((minibufferp mainbuf) 0)))
5533 (setq common-string-length
5535 (completion-common-substring
5536 (length completion-common-substring))
5537 (completion-base-size
5538 (- (length mbuf-contents) completion-base-size))))
5539 ;; Put faces on first uncommon characters and common parts.
5540 (when (and (integerp common-string-length) (>= common-string-length 0))
5541 (let ((element-start (point-min))
5544 (while (and (setq element-start
5545 (next-single-property-change
5546 element-start 'mouse-face))
5547 (< (setq element-common-end
5548 (+ element-start common-string-length))
5550 (when (get-char-property element-start 'mouse-face)
5551 (if (and (> common-string-length 0)
5552 (get-char-property (1- element-common-end) 'mouse-face))
5553 (put-text-property element-start element-common-end
5554 'font-lock-face 'completions-common-part))
5555 (if (get-char-property element-common-end 'mouse-face)
5556 (put-text-property element-common-end (1+ element-common-end)
5557 'font-lock-face 'completions-first-difference))))))
5558 ;; Maybe insert help string.
5559 (when completion-show-help
5560 (goto-char (point-min))
5561 (if (display-mouse-p)
5562 (insert (substitute-command-keys
5563 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
5564 (insert (substitute-command-keys
5565 "In this buffer, type \\[choose-completion] to \
5566 select the completion near point.\n\n"))))))
5568 (add-hook 'completion-setup-hook 'completion-setup-function)
5570 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
5571 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
5573 (defun switch-to-completions ()
5574 "Select the completion list window."
5576 ;; Make sure we have a completions window.
5577 (or (get-buffer-window "*Completions*")
5578 (minibuffer-completion-help))
5579 (let ((window (get-buffer-window "*Completions*")))
5581 (select-window window)
5582 (goto-char (point-min))
5583 (search-forward "\n\n" nil t)
5586 ;;; Support keyboard commands to turn on various modifiers.
5588 ;; These functions -- which are not commands -- each add one modifier
5589 ;; to the following event.
5591 (defun event-apply-alt-modifier (ignore-prompt)
5592 "\\<function-key-map>Add the Alt modifier to the following event.
5593 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
5594 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
5595 (defun event-apply-super-modifier (ignore-prompt)
5596 "\\<function-key-map>Add the Super modifier to the following event.
5597 For example, type \\[event-apply-super-modifier] & to enter Super-&."
5598 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
5599 (defun event-apply-hyper-modifier (ignore-prompt)
5600 "\\<function-key-map>Add the Hyper modifier to the following event.
5601 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
5602 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
5603 (defun event-apply-shift-modifier (ignore-prompt)
5604 "\\<function-key-map>Add the Shift modifier to the following event.
5605 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
5606 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
5607 (defun event-apply-control-modifier (ignore-prompt)
5608 "\\<function-key-map>Add the Ctrl modifier to the following event.
5609 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
5610 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
5611 (defun event-apply-meta-modifier (ignore-prompt)
5612 "\\<function-key-map>Add the Meta modifier to the following event.
5613 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
5614 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
5616 (defun event-apply-modifier (event symbol lshiftby prefix)
5617 "Apply a modifier flag to event EVENT.
5618 SYMBOL is the name of this modifier, as a symbol.
5619 LSHIFTBY is the numeric value of this modifier, in keyboard events.
5620 PREFIX is the string that represents this modifier in an event type symbol."
5622 (cond ((eq symbol 'control)
5623 (if (and (<= (downcase event) ?z)
5624 (>= (downcase event) ?a))
5625 (- (downcase event) ?a -1)
5626 (if (and (<= (downcase event) ?Z)
5627 (>= (downcase event) ?A))
5628 (- (downcase event) ?A -1)
5629 (logior (lsh 1 lshiftby) event))))
5631 (if (and (<= (downcase event) ?z)
5632 (>= (downcase event) ?a))
5634 (logior (lsh 1 lshiftby) event)))
5636 (logior (lsh 1 lshiftby) event)))
5637 (if (memq symbol (event-modifiers event))
5639 (let ((event-type (if (symbolp event) event (car event))))
5640 (setq event-type (intern (concat prefix (symbol-name event-type))))
5643 (cons event-type (cdr event)))))))
5645 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
5646 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
5647 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
5648 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
5649 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
5650 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
5652 ;;;; Keypad support.
5654 ;; Make the keypad keys act like ordinary typing keys. If people add
5655 ;; bindings for the function key symbols, then those bindings will
5656 ;; override these, so this shouldn't interfere with any existing
5659 ;; Also tell read-char how to handle these keys.
5661 (lambda (keypad-normal)
5662 (let ((keypad (nth 0 keypad-normal))
5663 (normal (nth 1 keypad-normal)))
5664 (put keypad 'ascii-character normal)
5665 (define-key function-key-map (vector keypad) (vector normal))))
5666 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
5667 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
5680 ;;;; forking a twin copy of a buffer.
5683 (defvar clone-buffer-hook nil
5684 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5686 (defvar clone-indirect-buffer-hook nil
5687 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
5689 (defun clone-process (process &optional newname)
5690 "Create a twin copy of PROCESS.
5691 If NEWNAME is nil, it defaults to PROCESS' name;
5692 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5693 If PROCESS is associated with a buffer, the new process will be associated
5694 with the current buffer instead.
5695 Returns nil if PROCESS has already terminated."
5696 (setq newname (or newname (process-name process)))
5697 (if (string-match "<[0-9]+>\\'" newname)
5698 (setq newname (substring newname 0 (match-beginning 0))))
5699 (when (memq (process-status process) '(run stop open))
5700 (let* ((process-connection-type (process-tty-name process))
5702 (if (memq (process-status process) '(open))
5703 (let ((args (process-contact process t)))
5704 (setq args (plist-put args :name newname))
5705 (setq args (plist-put args :buffer
5706 (if (process-buffer process)
5708 (apply 'make-network-process args))
5709 (apply 'start-process newname
5710 (if (process-buffer process) (current-buffer))
5711 (process-command process)))))
5712 (set-process-query-on-exit-flag
5713 new-process (process-query-on-exit-flag process))
5714 (set-process-inherit-coding-system-flag
5715 new-process (process-inherit-coding-system-flag process))
5716 (set-process-filter new-process (process-filter process))
5717 (set-process-sentinel new-process (process-sentinel process))
5718 (set-process-plist new-process (copy-sequence (process-plist process)))
5721 ;; things to maybe add (currently partly covered by `funcall mode'):
5724 (defun clone-buffer (&optional newname display-flag)
5725 "Create and return a twin copy of the current buffer.
5726 Unlike an indirect buffer, the new buffer can be edited
5727 independently of the old one (if it is not read-only).
5728 NEWNAME is the name of the new buffer. It may be modified by
5729 adding or incrementing <N> at the end as necessary to create a
5730 unique buffer name. If nil, it defaults to the name of the
5731 current buffer, with the proper suffix. If DISPLAY-FLAG is
5732 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
5733 clone a file-visiting buffer, or a buffer whose major mode symbol
5734 has a non-nil `no-clone' property, results in an error.
5736 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
5737 current buffer with appropriate suffix. However, if a prefix
5738 argument is given, then the command prompts for NEWNAME in the
5741 This runs the normal hook `clone-buffer-hook' in the new buffer
5742 after it has been set up properly in other respects."
5745 (if buffer-file-name
5746 (error "Cannot clone a file-visiting buffer"))
5747 (if (get major-mode 'no-clone)
5748 (error "Cannot clone a buffer in %s mode" mode-name))
5749 (list (if current-prefix-arg
5750 (read-buffer "Name of new cloned buffer: " (current-buffer)))
5752 (if buffer-file-name
5753 (error "Cannot clone a file-visiting buffer"))
5754 (if (get major-mode 'no-clone)
5755 (error "Cannot clone a buffer in %s mode" mode-name))
5756 (setq newname (or newname (buffer-name)))
5757 (if (string-match "<[0-9]+>\\'" newname)
5758 (setq newname (substring newname 0 (match-beginning 0))))
5759 (let ((buf (current-buffer))
5763 (mk (if mark-active (mark t)))
5764 (modified (buffer-modified-p))
5766 (lvars (buffer-local-variables))
5767 (process (get-buffer-process (current-buffer)))
5768 (new (generate-new-buffer (or newname (buffer-name)))))
5771 (with-current-buffer new
5772 (insert-buffer-substring buf)))
5773 (with-current-buffer new
5774 (narrow-to-region ptmin ptmax)
5776 (if mk (set-mark mk))
5777 (set-buffer-modified-p modified)
5779 ;; Clone the old buffer's process, if any.
5780 (when process (clone-process process))
5782 ;; Now set up the major mode.
5785 ;; Set up other local variables.
5787 (condition-case () ;in case var is read-only
5790 (set (make-local-variable (car v)) (cdr v)))
5794 ;; Run any hooks (typically set up by the major mode
5795 ;; for cloning to work properly).
5796 (run-hooks 'clone-buffer-hook))
5798 ;; Presumably the current buffer is shown in the selected frame, so
5799 ;; we want to display the clone elsewhere.
5800 (let ((same-window-regexps nil)
5801 (same-window-buffer-names))
5802 (pop-to-buffer new)))
5806 (defun clone-indirect-buffer (newname display-flag &optional norecord)
5807 "Create an indirect buffer that is a twin copy of the current buffer.
5809 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
5810 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
5811 or if not called with a prefix arg, NEWNAME defaults to the current
5812 buffer's name. The name is modified by adding a `<N>' suffix to it
5813 or by incrementing the N in an existing suffix.
5815 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
5816 This is always done when called interactively.
5818 Optional third arg NORECORD non-nil means do not put this buffer at the
5819 front of the list of recently selected ones."
5822 (if (get major-mode 'no-clone-indirect)
5823 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5824 (list (if current-prefix-arg
5825 (read-buffer "Name of indirect buffer: " (current-buffer)))
5827 (if (get major-mode 'no-clone-indirect)
5828 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5829 (setq newname (or newname (buffer-name)))
5830 (if (string-match "<[0-9]+>\\'" newname)
5831 (setq newname (substring newname 0 (match-beginning 0))))
5832 (let* ((name (generate-new-buffer-name newname))
5833 (buffer (make-indirect-buffer (current-buffer) name t)))
5834 (with-current-buffer buffer
5835 (run-hooks 'clone-indirect-buffer-hook))
5837 (pop-to-buffer buffer norecord))
5841 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
5842 "Like `clone-indirect-buffer' but display in another window."
5845 (if (get major-mode 'no-clone-indirect)
5846 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5847 (list (if current-prefix-arg
5848 (read-buffer "Name of indirect buffer: " (current-buffer)))
5850 (let ((pop-up-windows t))
5851 (clone-indirect-buffer newname display-flag norecord)))
5854 ;;; Handling of Backspace and Delete keys.
5856 (defcustom normal-erase-is-backspace 'maybe
5857 "Set the default behavior of the Delete and Backspace keys.
5859 If set to t, Delete key deletes forward and Backspace key deletes
5862 If set to nil, both Delete and Backspace keys delete backward.
5864 If set to 'maybe (which is the default), Emacs automatically
5865 selects a behavior. On window systems, the behavior depends on
5866 the keyboard used. If the keyboard has both a Backspace key and
5867 a Delete key, and both are mapped to their usual meanings, the
5868 option's default value is set to t, so that Backspace can be used
5869 to delete backward, and Delete can be used to delete forward.
5871 If not running under a window system, customizing this option
5872 accomplishes a similar effect by mapping C-h, which is usually
5873 generated by the Backspace key, to DEL, and by mapping DEL to C-d
5874 via `keyboard-translate'. The former functionality of C-h is
5875 available on the F1 key. You should probably not use this
5876 setting if you don't have both Backspace, Delete and F1 keys.
5878 Setting this variable with setq doesn't take effect. Programmatically,
5879 call `normal-erase-is-backspace-mode' (which see) instead."
5880 :type '(choice (const :tag "Off" nil)
5881 (const :tag "Maybe" maybe)
5882 (other :tag "On" t))
5883 :group 'editing-basics
5885 :set (lambda (symbol value)
5886 ;; The fboundp is because of a problem with :set when
5887 ;; dumping Emacs. It doesn't really matter.
5888 (if (fboundp 'normal-erase-is-backspace-mode)
5889 (normal-erase-is-backspace-mode (or value 0))
5890 (set-default symbol value))))
5892 (defun normal-erase-is-backspace-setup-frame (&optional frame)
5893 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
5894 (unless frame (setq frame (selected-frame)))
5895 (with-selected-frame frame
5896 (unless (terminal-parameter nil 'normal-erase-is-backspace)
5897 (normal-erase-is-backspace-mode
5898 (if (if (eq normal-erase-is-backspace 'maybe)
5899 (and (not noninteractive)
5900 (or (memq system-type '(ms-dos windows-nt))
5901 (eq window-system 'mac)
5902 (and (memq window-system '(x))
5903 (fboundp 'x-backspace-delete-keys-p)
5904 (x-backspace-delete-keys-p))
5905 ;; If the terminal Emacs is running on has erase char
5906 ;; set to ^H, use the Backspace key for deleting
5907 ;; backward, and the Delete key for deleting forward.
5908 (and (null window-system)
5909 (eq tty-erase-char ?\^H))))
5910 normal-erase-is-backspace)
5913 (defun normal-erase-is-backspace-mode (&optional arg)
5914 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5916 With numeric arg, turn the mode on if and only if ARG is positive.
5918 On window systems, when this mode is on, Delete is mapped to C-d
5919 and Backspace is mapped to DEL; when this mode is off, both
5920 Delete and Backspace are mapped to DEL. (The remapping goes via
5921 `local-function-key-map', so binding Delete or Backspace in the
5922 global or local keymap will override that.)
5924 In addition, on window systems, the bindings of C-Delete, M-Delete,
5925 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5926 the global keymap in accordance with the functionality of Delete and
5927 Backspace. For example, if Delete is remapped to C-d, which deletes
5928 forward, C-Delete is bound to `kill-word', but if Delete is remapped
5929 to DEL, which deletes backward, C-Delete is bound to
5930 `backward-kill-word'.
5932 If not running on a window system, a similar effect is accomplished by
5933 remapping C-h (normally produced by the Backspace key) and DEL via
5934 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5935 to C-d; if it's off, the keys are not remapped.
5937 When not running on a window system, and this mode is turned on, the
5938 former functionality of C-h is available on the F1 key. You should
5939 probably not turn on this mode on a text-only terminal if you don't
5940 have both Backspace, Delete and F1 keys.
5942 See also `normal-erase-is-backspace'."
5944 (let ((enabled (or (and arg (> (prefix-numeric-value arg) 0))
5946 (not (eq 1 (terminal-parameter
5947 nil 'normal-erase-is-backspace)))))))
5948 (set-terminal-parameter nil 'normal-erase-is-backspace
5951 (cond ((or (memq window-system '(x w32 mac pc))
5952 (memq system-type '(ms-dos windows-nt)))
5954 `(([C-delete] [C-backspace])
5955 ([M-delete] [M-backspace])
5956 ([C-M-delete] [C-M-backspace])
5958 [C-delete] [C-backspace])))
5959 (old-state (lookup-key local-function-key-map [delete])))
5963 (define-key local-function-key-map [delete] [?\C-d])
5964 (define-key local-function-key-map [kp-delete] [?\C-d])
5965 (define-key local-function-key-map [backspace] [?\C-?]))
5966 (define-key local-function-key-map [delete] [?\C-?])
5967 (define-key local-function-key-map [kp-delete] [?\C-?])
5968 (define-key local-function-key-map [backspace] [?\C-?]))
5970 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5971 (unless (equal old-state (lookup-key local-function-key-map [delete]))
5972 (dolist (binding bindings)
5973 (let ((map global-map))
5974 (when (keymapp (car binding))
5975 (setq map (car binding) binding (cdr binding)))
5976 (let* ((key1 (nth 0 binding))
5977 (key2 (nth 1 binding))
5978 (binding1 (lookup-key map key1))
5979 (binding2 (lookup-key map key2)))
5980 (define-key map key1 binding2)
5981 (define-key map key2 binding1)))))))
5985 (keyboard-translate ?\C-h ?\C-?)
5986 (keyboard-translate ?\C-? ?\C-d))
5987 (keyboard-translate ?\C-h ?\C-h)
5988 (keyboard-translate ?\C-? ?\C-?))))
5990 (run-hooks 'normal-erase-is-backspace-hook)
5992 (message "Delete key deletes %s"
5993 (if (terminal-parameter nil 'normal-erase-is-backspace)
5994 "forward" "backward")))))
5996 (defvar vis-mode-saved-buffer-invisibility-spec nil
5997 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
5999 (define-minor-mode visible-mode
6000 "Toggle Visible mode.
6001 With argument ARG turn Visible mode on if ARG is positive, otherwise
6004 Enabling Visible mode makes all invisible text temporarily visible.
6005 Disabling Visible mode turns off that effect. Visible mode
6006 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
6008 :group 'editing-basics
6009 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6010 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6011 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
6013 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6014 buffer-invisibility-spec)
6015 (setq buffer-invisibility-spec nil)))
6017 ;; Minibuffer prompt stuff.
6019 ;(defun minibuffer-prompt-modification (start end)
6020 ; (error "You cannot modify the prompt"))
6023 ;(defun minibuffer-prompt-insertion (start end)
6024 ; (let ((inhibit-modification-hooks t))
6025 ; (delete-region start end)
6026 ; ;; Discard undo information for the text insertion itself
6027 ; ;; and for the text deletion.above.
6028 ; (when (consp buffer-undo-list)
6029 ; (setq buffer-undo-list (cddr buffer-undo-list)))
6030 ; (message "You cannot modify the prompt")))
6033 ;(setq minibuffer-prompt-properties
6034 ; (list 'modification-hooks '(minibuffer-prompt-modification)
6035 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
6039 ;;;; Problematic external packages.
6041 ;; rms says this should be done by specifying symbols that define
6042 ;; versions together with bad values. This is therefore not as
6043 ;; flexible as it could be. See the thread:
6044 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6045 (defconst bad-packages-alist
6046 ;; Not sure exactly which semantic versions have problems.
6047 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
6048 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
6049 "The version of `semantic' loaded does not work in Emacs 22.
6050 It can cause constant high CPU load.
6051 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
6052 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6053 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6054 ;; provided the `CUA-mode' feature. Since this is no longer true,
6055 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6057 "CUA-mode is now part of the standard GNU Emacs distribution,
6058 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6060 You have loaded an older version of CUA-mode which does not work
6061 correctly with this version of Emacs. You should remove the old
6062 version and use the one distributed with Emacs."))
6063 "Alist of packages known to cause problems in this version of Emacs.
6064 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6065 PACKAGE is either a regular expression to match file names, or a
6066 symbol (a feature name); see the documentation of
6067 `after-load-alist', to which this variable adds functions.
6068 SYMBOL is either the name of a string variable, or `t'. Upon
6069 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6070 warning using STRING as the message.")
6072 (defun bad-package-check (package)
6073 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6075 (let* ((list (assoc package bad-packages-alist))
6076 (symbol (nth 1 list)))
6080 (and (stringp (setq symbol (eval symbol)))
6081 (string-match (nth 2 list) symbol)))
6082 (display-warning :warning (nth 3 list))))
6085 (mapc (lambda (elem)
6086 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6092 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
6093 ;;; simple.el ends here