1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 ;; 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
5 ;; Free Software Foundation, Inc.
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; A grab-bag of basic Emacs commands not specifically related to some
28 ;; major mode or to file-handling.
32 ;; This is for lexical-let in apply-partially.
33 (eval-when-compile (require 'cl
))
35 (declare-function widget-convert
"wid-edit" (type &rest args
))
36 (declare-function shell-mode
"shell" ())
38 (defvar compilation-current-error
)
40 (defcustom idle-update-delay
0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
49 "Killing and yanking commands."
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
56 (defun get-next-valid-buffer (list &optional buffer visible-ok frame
)
57 "Search LIST for a valid buffer to display in FRAME.
58 Return nil when all buffers in LIST are undesirable for display,
59 otherwise return the first suitable buffer in LIST.
61 Buffers not visible in windows are preferred to visible buffers,
62 unless VISIBLE-OK is non-nil.
63 If the optional argument FRAME is nil, it defaults to the selected frame.
64 If BUFFER is non-nil, ignore occurrences of that buffer in LIST."
65 ;; This logic is more or less copied from other-buffer.
66 (setq frame
(or frame
(selected-frame)))
67 (let ((pred (frame-parameter frame
'buffer-predicate
))
69 (while (and (not found
) list
)
71 (if (and (not (eq buffer buf
))
73 (or (null pred
) (funcall pred buf
))
74 (not (eq (aref (buffer-name buf
) 0) ?\s
))
75 (or visible-ok
(null (get-buffer-window buf
'visible
))))
77 (setq list
(cdr list
))))
80 (defun last-buffer (&optional buffer visible-ok frame
)
81 "Return the last buffer in FRAME's buffer list.
82 If BUFFER is the last buffer, return the preceding buffer instead.
83 Buffers not visible in windows are preferred to visible buffers,
84 unless optional argument VISIBLE-OK is non-nil.
85 Optional third argument FRAME nil or omitted means use the
86 selected frame's buffer list.
87 If no such buffer exists, return the buffer `*scratch*', creating
89 (setq frame
(or frame
(selected-frame)))
90 (or (get-next-valid-buffer (nreverse (buffer-list frame
))
91 buffer visible-ok frame
)
92 (get-buffer "*scratch*")
93 (let ((scratch (get-buffer-create "*scratch*")))
94 (set-buffer-major-mode scratch
)
98 "Switch to the next buffer in cyclic order."
100 (let ((buffer (current-buffer)))
101 (switch-to-buffer (other-buffer buffer t
))
102 (bury-buffer buffer
)))
104 (defun previous-buffer ()
105 "Switch to the previous buffer in cyclic order."
107 (switch-to-buffer (last-buffer (current-buffer) t
)))
110 ;;; next-error support framework
112 (defgroup next-error nil
113 "`next-error' support framework."
118 '((t (:inherit region
)))
119 "Face used to highlight next error locus."
123 (defcustom next-error-highlight
0.5
124 "Highlighting of locations in selected source buffers.
125 If a number, highlight the locus in `next-error' face for the given time
126 in seconds, or until the next command is executed.
127 If t, highlight the locus until the next command is executed, or until
128 some other locus replaces it.
129 If nil, don't highlight the locus in the source buffer.
130 If `fringe-arrow', indicate the locus by the fringe arrow."
131 :type
'(choice (number :tag
"Highlight for specified time")
132 (const :tag
"Semipermanent highlighting" t
)
133 (const :tag
"No highlighting" nil
)
134 (const :tag
"Fringe arrow" fringe-arrow
))
138 (defcustom next-error-highlight-no-select
0.5
139 "Highlighting of locations in `next-error-no-select'.
140 If number, highlight the locus in `next-error' face for given time in seconds.
141 If t, highlight the locus indefinitely until some other locus replaces it.
142 If nil, don't highlight the locus in the source buffer.
143 If `fringe-arrow', indicate the locus by the fringe arrow."
144 :type
'(choice (number :tag
"Highlight for specified time")
145 (const :tag
"Semipermanent highlighting" t
)
146 (const :tag
"No highlighting" nil
)
147 (const :tag
"Fringe arrow" fringe-arrow
))
151 (defcustom next-error-recenter nil
152 "Display the line in the visited source file recentered as specified.
153 If non-nil, the value is passed directly to `recenter'."
154 :type
'(choice (integer :tag
"Line to recenter to")
155 (const :tag
"Center of window" (4))
156 (const :tag
"No recentering" nil
))
160 (defcustom next-error-hook nil
161 "List of hook functions run by `next-error' after visiting source file."
165 (defvar next-error-highlight-timer nil
)
167 (defvar next-error-overlay-arrow-position nil
)
168 (put 'next-error-overlay-arrow-position
'overlay-arrow-string
"=>")
169 (add-to-list 'overlay-arrow-variable-list
'next-error-overlay-arrow-position
)
171 (defvar next-error-last-buffer nil
172 "The most recent `next-error' buffer.
173 A buffer becomes most recent when its compilation, grep, or
174 similar mode is started, or when it is used with \\[next-error]
175 or \\[compile-goto-error].")
177 (defvar next-error-function nil
178 "Function to use to find the next error in the current buffer.
179 The function is called with 2 parameters:
180 ARG is an integer specifying by how many errors to move.
181 RESET is a boolean which, if non-nil, says to go back to the beginning
182 of the errors before moving.
183 Major modes providing compile-like functionality should set this variable
184 to indicate to `next-error' that this is a candidate buffer and how
187 (make-variable-buffer-local 'next-error-function
)
189 (defsubst next-error-buffer-p
(buffer
190 &optional avoid-current
192 extra-test-exclusive
)
193 "Test if BUFFER is a `next-error' capable buffer.
195 If AVOID-CURRENT is non-nil, treat the current buffer
196 as an absolute last resort only.
198 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
199 that normally would not qualify. If it returns t, the buffer
200 in question is treated as usable.
202 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
203 that would normally be considered usable. If it returns nil,
204 that buffer is rejected."
205 (and (buffer-name buffer
) ;First make sure it's live.
206 (not (and avoid-current
(eq buffer
(current-buffer))))
207 (with-current-buffer buffer
208 (if next-error-function
; This is the normal test.
209 ;; Optionally reject some buffers.
210 (if extra-test-exclusive
211 (funcall extra-test-exclusive
)
213 ;; Optionally accept some other buffers.
214 (and extra-test-inclusive
215 (funcall extra-test-inclusive
))))))
217 (defun next-error-find-buffer (&optional avoid-current
219 extra-test-exclusive
)
220 "Return a `next-error' capable buffer.
222 If AVOID-CURRENT is non-nil, treat the current buffer
223 as an absolute last resort only.
225 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
226 that normally would not qualify. If it returns t, the buffer
227 in question is treated as usable.
229 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
230 that would normally be considered usable. If it returns nil,
231 that buffer is rejected."
233 ;; 1. If one window on the selected frame displays such buffer, return it.
234 (let ((window-buffers
236 (delq nil
(mapcar (lambda (w)
237 (if (next-error-buffer-p
240 extra-test-inclusive extra-test-exclusive
)
243 (if (eq (length window-buffers
) 1)
244 (car window-buffers
)))
245 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
246 (if (and next-error-last-buffer
247 (next-error-buffer-p next-error-last-buffer avoid-current
248 extra-test-inclusive extra-test-exclusive
))
249 next-error-last-buffer
)
250 ;; 3. If the current buffer is acceptable, choose it.
251 (if (next-error-buffer-p (current-buffer) avoid-current
252 extra-test-inclusive extra-test-exclusive
)
254 ;; 4. Look for any acceptable buffer.
255 (let ((buffers (buffer-list)))
257 (not (next-error-buffer-p
258 (car buffers
) avoid-current
259 extra-test-inclusive extra-test-exclusive
)))
260 (setq buffers
(cdr buffers
)))
262 ;; 5. Use the current buffer as a last resort if it qualifies,
263 ;; even despite AVOID-CURRENT.
265 (next-error-buffer-p (current-buffer) nil
266 extra-test-inclusive extra-test-exclusive
)
268 (message "This is the only buffer with error message locations")
271 (error "No buffers contain error message locations")))
273 (defun next-error (&optional arg reset
)
274 "Visit next `next-error' message and corresponding source code.
276 If all the error messages parsed so far have been processed already,
277 the message buffer is checked for new ones.
279 A prefix ARG specifies how many error messages to move;
280 negative means move back to previous error messages.
281 Just \\[universal-argument] as a prefix means reparse the error message buffer
282 and start at the first error.
284 The RESET argument specifies that we should restart from the beginning.
286 \\[next-error] normally uses the most recently started
287 compilation, grep, or occur buffer. It can also operate on any
288 buffer with output from the \\[compile], \\[grep] commands, or,
289 more generally, on any buffer in Compilation mode or with
290 Compilation Minor mode enabled, or any buffer in which
291 `next-error-function' is bound to an appropriate function.
292 To specify use of a particular buffer for error messages, type
293 \\[next-error] in that buffer when it is the only one displayed
294 in the current frame.
296 Once \\[next-error] has chosen the buffer for error messages, it
297 runs `next-error-hook' with `run-hooks', and stays with that buffer
298 until you use it in some other buffer which uses Compilation mode
299 or Compilation Minor mode.
301 See variables `compilation-parse-errors-function' and
302 \`compilation-error-regexp-alist' for customization ideas."
304 (if (consp arg
) (setq reset t arg nil
))
305 (when (setq next-error-last-buffer
(next-error-find-buffer))
306 ;; we know here that next-error-function is a valid symbol we can funcall
307 (with-current-buffer next-error-last-buffer
308 (funcall next-error-function
(prefix-numeric-value arg
) reset
)
309 (when next-error-recenter
310 (recenter next-error-recenter
))
311 (run-hooks 'next-error-hook
))))
313 (defun next-error-internal ()
314 "Visit the source code corresponding to the `next-error' message at point."
315 (setq next-error-last-buffer
(current-buffer))
316 ;; we know here that next-error-function is a valid symbol we can funcall
317 (with-current-buffer next-error-last-buffer
318 (funcall next-error-function
0 nil
)
319 (when next-error-recenter
320 (recenter next-error-recenter
))
321 (run-hooks 'next-error-hook
)))
323 (defalias 'goto-next-locus
'next-error
)
324 (defalias 'next-match
'next-error
)
326 (defun previous-error (&optional n
)
327 "Visit previous `next-error' message and corresponding source code.
329 Prefix arg N says how many error messages to move backwards (or
330 forwards, if negative).
332 This operates on the output from the \\[compile] and \\[grep] commands."
334 (next-error (- (or n
1))))
336 (defun first-error (&optional n
)
337 "Restart at the first error.
338 Visit corresponding source code.
339 With prefix arg N, visit the source code of the Nth error.
340 This operates on the output from the \\[compile] command, for instance."
344 (defun next-error-no-select (&optional n
)
345 "Move point to the next error in the `next-error' buffer and highlight match.
346 Prefix arg N says how many error messages to move forwards (or
347 backwards, if negative).
348 Finds and highlights the source line like \\[next-error], but does not
349 select the source buffer."
351 (let ((next-error-highlight next-error-highlight-no-select
))
353 (pop-to-buffer next-error-last-buffer
))
355 (defun previous-error-no-select (&optional n
)
356 "Move point to the previous error in the `next-error' buffer and highlight match.
357 Prefix arg N says how many error messages to move backwards (or
358 forwards, if negative).
359 Finds and highlights the source line like \\[previous-error], but does not
360 select the source buffer."
362 (next-error-no-select (- (or n
1))))
364 ;;; Internal variable for `next-error-follow-mode-post-command-hook'.
365 (defvar next-error-follow-last-line nil
)
367 (define-minor-mode next-error-follow-minor-mode
368 "Minor mode for compilation, occur and diff modes.
369 When turned on, cursor motion in the compilation, grep, occur or diff
370 buffer causes automatic display of the corresponding source code
372 :group
'next-error
:init-value nil
:lighter
" Fol"
373 (if (not next-error-follow-minor-mode
)
374 (remove-hook 'post-command-hook
'next-error-follow-mode-post-command-hook t
)
375 (add-hook 'post-command-hook
'next-error-follow-mode-post-command-hook nil t
)
376 (make-local-variable 'next-error-follow-last-line
)))
378 ;;; Used as a `post-command-hook' by `next-error-follow-mode'
379 ;;; for the *Compilation* *grep* and *Occur* buffers.
380 (defun next-error-follow-mode-post-command-hook ()
381 (unless (equal next-error-follow-last-line
(line-number-at-pos))
382 (setq next-error-follow-last-line
(line-number-at-pos))
384 (let ((compilation-context-lines nil
))
385 (setq compilation-current-error
(point))
386 (next-error-no-select 0))
392 (defun fundamental-mode ()
393 "Major mode not specialized for anything in particular.
394 Other major modes are defined by comparison with this one."
396 (kill-all-local-variables)
397 (unless delay-mode-hooks
398 (run-hooks 'after-change-major-mode-hook
)))
400 ;; Special major modes to view specially formatted data rather than files.
402 (defvar special-mode-map
403 (let ((map (make-sparse-keymap)))
404 (suppress-keymap map
)
405 (define-key map
"q" 'quit-window
)
406 (define-key map
" " 'scroll-up
)
407 (define-key map
"\C-?" 'scroll-down
)
408 (define-key map
"?" 'describe-mode
)
409 (define-key map
">" 'end-of-buffer
)
410 (define-key map
"<" 'beginning-of-buffer
)
411 (define-key map
"g" 'revert-buffer
)
414 (put 'special-mode
'mode-class
'special
)
415 (define-derived-mode special-mode nil
"Special"
416 "Parent major mode from which special major modes should inherit."
417 (setq buffer-read-only t
))
419 ;; Making and deleting lines.
421 (defvar hard-newline
(propertize "\n" 'hard t
'rear-nonsticky
'(hard)))
423 (defun newline (&optional arg
)
424 "Insert a newline, and move to left margin of the new line if it's blank.
425 If `use-hard-newlines' is non-nil, the newline is marked with the
426 text-property `hard'.
427 With ARG, insert that many newlines.
428 Call `auto-fill-function' if the current column number is greater
429 than the value of `fill-column' and ARG is nil."
431 (barf-if-buffer-read-only)
432 ;; Inserting a newline at the end of a line produces better redisplay in
433 ;; try_window_id than inserting at the beginning of a line, and the textual
434 ;; result is the same. So, if we're at beginning of line, pretend to be at
435 ;; the end of the previous line.
436 (let ((flag (and (not (bobp))
438 ;; Make sure no functions want to be told about
439 ;; the range of the changes.
440 (not after-change-functions
)
441 (not before-change-functions
)
442 ;; Make sure there are no markers here.
443 (not (buffer-has-markers-at (1- (point))))
444 (not (buffer-has-markers-at (point)))
445 ;; Make sure no text properties want to know
446 ;; where the change was.
447 (not (get-char-property (1- (point)) 'modification-hooks
))
448 (not (get-char-property (1- (point)) 'insert-behind-hooks
))
450 (not (get-char-property (point) 'insert-in-front-hooks
)))
451 ;; Make sure the newline before point isn't intangible.
452 (not (get-char-property (1- (point)) 'intangible
))
453 ;; Make sure the newline before point isn't read-only.
454 (not (get-char-property (1- (point)) 'read-only
))
455 ;; Make sure the newline before point isn't invisible.
456 (not (get-char-property (1- (point)) 'invisible
))
457 ;; Make sure the newline before point has the same
458 ;; properties as the char before it (if any).
459 (< (or (previous-property-change (point)) -
2)
461 (was-page-start (and (bolp)
462 (looking-at page-delimiter
)))
464 (if flag
(backward-char 1))
465 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
466 ;; Set last-command-event to tell self-insert what to insert.
467 (let ((last-command-event ?
\n)
468 ;; Don't auto-fill if we have a numeric argument.
469 ;; Also not if flag is true (it would fill wrong line);
470 ;; there is no need to since we're at BOL.
471 (auto-fill-function (if (or arg flag
) nil auto-fill-function
)))
473 (self-insert-command (prefix-numeric-value arg
))
474 ;; If we get an error in self-insert-command, put point at right place.
475 (if flag
(forward-char 1))))
476 ;; Even if we did *not* get an error, keep that forward-char;
477 ;; all further processing should apply to the newline that the user
478 ;; thinks he inserted.
480 ;; Mark the newline(s) `hard'.
481 (if use-hard-newlines
482 (set-hard-newline-properties
483 (- (point) (prefix-numeric-value arg
)) (point)))
484 ;; If the newline leaves the previous line blank,
485 ;; and we have a left margin, delete that from the blank line.
488 (goto-char beforepos
)
490 (and (looking-at "[ \t]$")
491 (> (current-left-margin) 0)
492 (delete-region (point) (progn (end-of-line) (point))))))
493 ;; Indent the line after the newline, except in one case:
494 ;; when we added the newline at the beginning of a line
495 ;; which starts a page.
497 (move-to-left-margin nil t
)))
500 (defun set-hard-newline-properties (from to
)
501 (let ((sticky (get-text-property from
'rear-nonsticky
)))
502 (put-text-property from to
'hard
't
)
503 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
504 (if (and (listp sticky
) (not (memq 'hard sticky
)))
505 (put-text-property from
(point) 'rear-nonsticky
506 (cons 'hard sticky
)))))
509 "Insert a newline and leave point before it.
510 If there is a fill prefix and/or a `left-margin', insert them
511 on the new line if the line would have been blank.
512 With arg N, insert N newlines."
514 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
515 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
517 ;; Don't expand an abbrev before point.
523 (if do-left-margin
(indent-to (current-left-margin)))
524 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
530 (defun split-line (&optional arg
)
531 "Split current line, moving portion beyond point vertically down.
532 If the current line starts with `fill-prefix', insert it on the new
533 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
535 When called from Lisp code, ARG may be a prefix string to copy."
537 (skip-chars-forward " \t")
538 (let* ((col (current-column))
540 ;; What prefix should we check for (nil means don't).
541 (prefix (cond ((stringp arg
) arg
)
544 ;; Does this line start with it?
545 (have-prfx (and prefix
548 (looking-at (regexp-quote prefix
))))))
550 (if have-prfx
(insert-and-inherit prefix
))
554 (defun delete-indentation (&optional arg
)
555 "Join this line to previous and fix up whitespace at join.
556 If there is a fill prefix, delete it from the beginning of this line.
557 With argument, join this line to following line."
560 (if arg
(forward-line 1))
561 (if (eq (preceding-char) ?
\n)
563 (delete-region (point) (1- (point)))
564 ;; If the second line started with the fill prefix,
565 ;; delete the prefix.
567 (<= (+ (point) (length fill-prefix
)) (point-max))
569 (buffer-substring (point)
570 (+ (point) (length fill-prefix
)))))
571 (delete-region (point) (+ (point) (length fill-prefix
))))
572 (fixup-whitespace))))
574 (defalias 'join-line
#'delete-indentation
) ; easier to find
576 (defun delete-blank-lines ()
577 "On blank line, delete all surrounding blank lines, leaving just one.
578 On isolated blank line, delete that one.
579 On nonblank line, delete any immediately following blank lines."
581 (let (thisblank singleblank
)
584 (setq thisblank
(looking-at "[ \t]*$"))
585 ;; Set singleblank if there is just one blank line here.
588 (not (looking-at "[ \t]*\n[ \t]*$"))
590 (progn (forward-line -
1)
591 (not (looking-at "[ \t]*$")))))))
592 ;; Delete preceding blank lines, and this one too if it's the only one.
596 (if singleblank
(forward-line 1))
597 (delete-region (point)
598 (if (re-search-backward "[^ \t\n]" nil t
)
599 (progn (forward-line 1) (point))
601 ;; Delete following blank lines, unless the current line is blank
602 ;; and there are no following blank lines.
603 (if (not (and thisblank singleblank
))
607 (delete-region (point)
608 (if (re-search-forward "[^ \t\n]" nil t
)
609 (progn (beginning-of-line) (point))
611 ;; Handle the special case where point is followed by newline and eob.
612 ;; Delete the line, leaving point at eob.
613 (if (looking-at "^[ \t]*\n\\'")
614 (delete-region (point) (point-max)))))
616 (defun delete-trailing-whitespace ()
617 "Delete all the trailing whitespace across the current buffer.
618 All whitespace after the last non-whitespace character in a line is deleted.
619 This respects narrowing, created by \\[narrow-to-region] and friends.
620 A formfeed is not considered whitespace by this function."
624 (goto-char (point-min))
625 (while (re-search-forward "\\s-$" nil t
)
626 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
627 ;; Don't delete formfeeds, even if they are considered whitespace.
629 (if (looking-at ".*\f")
630 (goto-char (match-end 0))))
631 (delete-region (point) (match-end 0))))))
633 (defun newline-and-indent ()
634 "Insert a newline, then indent according to major mode.
635 Indentation is done using the value of `indent-line-function'.
636 In programming language modes, this is the same as TAB.
637 In some text modes, where TAB inserts a tab, this command indents to the
638 column specified by the function `current-left-margin'."
640 (delete-horizontal-space t
)
642 (indent-according-to-mode))
644 (defun reindent-then-newline-and-indent ()
645 "Reindent current line, insert newline, then indent the new line.
646 Indentation of both lines is done according to the current major mode,
647 which means calling the current value of `indent-line-function'.
648 In programming language modes, this is the same as TAB.
649 In some text modes, where TAB inserts a tab, this indents to the
650 column specified by the function `current-left-margin'."
653 ;; Be careful to insert the newline before indenting the line.
654 ;; Otherwise, the indentation might be wrong.
658 ;; We are at EOL before the call to indent-according-to-mode, and
659 ;; after it we usually are as well, but not always. We tried to
660 ;; address it with `save-excursion' but that uses a normal marker
661 ;; whereas we need `move after insertion', so we do the save/restore
663 (setq pos
(copy-marker pos t
))
664 (indent-according-to-mode)
666 ;; Remove the trailing white-space after indentation because
667 ;; indentation may introduce the whitespace.
668 (delete-horizontal-space t
))
669 (indent-according-to-mode)))
671 (defun quoted-insert (arg)
672 "Read next input character and insert it.
673 This is useful for inserting control characters.
674 With argument, insert ARG copies of the character.
676 If the first character you type after this command is an octal digit,
677 you should type a sequence of octal digits which specify a character code.
678 Any nondigit terminates the sequence. If the terminator is a RET,
679 it is discarded; any other terminator is used itself as input.
680 The variable `read-quoted-char-radix' specifies the radix for this feature;
681 set it to 10 or 16 to use decimal or hex instead of octal.
683 In overwrite mode, this function inserts the character anyway, and
684 does not handle octal digits specially. This means that if you use
685 overwrite as your normal editing mode, you can use this function to
686 insert characters when necessary.
688 In binary overwrite mode, this function does overwrite, and octal
689 digits are interpreted as a character code. This is intended to be
690 useful for editing binary files."
692 (let* ((char (let (translation-table-for-input input-method-function
)
693 (if (or (not overwrite-mode
)
694 (eq overwrite-mode
'overwrite-mode-binary
))
697 ;; This used to assume character codes 0240 - 0377 stand for
698 ;; characters in some single-byte character set, and converted them
699 ;; to Emacs characters. But in 23.1 this feature is deprecated
700 ;; in favor of inserting the corresponding Unicode characters.
701 ;; (if (and enable-multibyte-characters
704 ;; (setq char (unibyte-char-to-multibyte char)))
706 (if (eq overwrite-mode
'overwrite-mode-binary
)
709 (insert-and-inherit char
)
710 (setq arg
(1- arg
)))))
712 (defun forward-to-indentation (&optional arg
)
713 "Move forward ARG lines and position at first nonblank character."
715 (forward-line (or arg
1))
716 (skip-chars-forward " \t"))
718 (defun backward-to-indentation (&optional arg
)
719 "Move backward ARG lines and position at first nonblank character."
721 (forward-line (- (or arg
1)))
722 (skip-chars-forward " \t"))
724 (defun back-to-indentation ()
725 "Move point to the first non-whitespace character on this line."
727 (beginning-of-line 1)
728 (skip-syntax-forward " " (line-end-position))
729 ;; Move back over chars that have whitespace syntax but have the p flag.
730 (backward-prefix-chars))
732 (defun fixup-whitespace ()
733 "Fixup white space between objects around point.
734 Leave one space or none, according to the context."
737 (delete-horizontal-space)
738 (if (or (looking-at "^\\|\\s)")
739 (save-excursion (forward-char -
1)
740 (looking-at "$\\|\\s(\\|\\s'")))
744 (defun delete-horizontal-space (&optional backward-only
)
745 "Delete all spaces and tabs around point.
746 If BACKWARD-ONLY is non-nil, only delete them before point."
748 (let ((orig-pos (point)))
753 (skip-chars-forward " \t")
754 (constrain-to-field nil orig-pos t
)))
756 (skip-chars-backward " \t")
757 (constrain-to-field nil orig-pos
)))))
759 (defun just-one-space (&optional n
)
760 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
762 (let ((orig-pos (point)))
763 (skip-chars-backward " \t")
764 (constrain-to-field nil orig-pos
)
765 (dotimes (i (or n
1))
766 (if (= (following-char) ?\s
)
772 (skip-chars-forward " \t")
773 (constrain-to-field nil orig-pos t
)))))
775 (defun beginning-of-buffer (&optional arg
)
776 "Move point to the beginning 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 beginning.
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-min)) is faster and avoids clobbering the mark."
789 (let ((size (- (point-max) (point-min))))
790 (goto-char (if (and arg
(not (consp arg
)))
793 ;; Avoid overflow for large buffer sizes!
794 (* (prefix-numeric-value arg
)
796 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
798 (if (and arg
(not (consp arg
))) (forward-line 1)))
800 (defun end-of-buffer (&optional arg
)
801 "Move point to the end of the buffer; leave mark at previous position.
802 With \\[universal-argument] prefix, do not set mark at previous position.
803 With numeric arg N, put point N/10 of the way from the end.
805 If the buffer is narrowed, this command uses the beginning and size
806 of the accessible part of the buffer.
808 Don't use this command in Lisp programs!
809 \(goto-char (point-max)) is faster and avoids clobbering the mark."
811 (or (consp arg
) (region-active-p) (push-mark))
812 (let ((size (- (point-max) (point-min))))
813 (goto-char (if (and arg
(not (consp arg
)))
816 ;; Avoid overflow for large buffer sizes!
817 (* (prefix-numeric-value arg
)
819 (/ (* size
(prefix-numeric-value arg
)) 10)))
821 ;; If we went to a place in the middle of the buffer,
822 ;; adjust it to the beginning of a line.
823 (cond ((and arg
(not (consp arg
))) (forward-line 1))
824 ((> (point) (window-end nil t
))
825 ;; If the end of the buffer is not already on the screen,
826 ;; then scroll specially to put it near, but not at, the bottom.
827 (overlay-recenter (point))
830 (defun mark-whole-buffer ()
831 "Put point at beginning and mark at end of buffer.
832 You probably should not use this function in Lisp programs;
833 it is usually a mistake for a Lisp function to use any subroutine
834 that uses or sets the mark."
837 (push-mark (point-max) nil t
)
838 (goto-char (point-min)))
841 ;; Counting lines, one way or another.
843 (defun goto-line (line &optional buffer
)
844 "Goto LINE, counting from line 1 at beginning of buffer.
845 Normally, move point in the current buffer, and leave mark at the
846 previous position. With just \\[universal-argument] as argument,
847 move point in the most recently selected other buffer, and switch
848 to it. When called from Lisp code, the optional argument BUFFER
849 specifies a buffer to switch to.
851 If there's a number in the buffer at point, it is the default for
854 (if (and current-prefix-arg
(not (consp current-prefix-arg
)))
855 (list (prefix-numeric-value current-prefix-arg
))
856 ;; Look for a default, a number in the buffer at point.
859 (skip-chars-backward "0-9")
860 (if (looking-at "[0-9]")
861 (buffer-substring-no-properties
863 (progn (skip-chars-forward "0-9")
865 ;; Decide if we're switching buffers.
867 (if (consp current-prefix-arg
)
868 (other-buffer (current-buffer) t
)))
871 (concat " in " (buffer-name buffer
))
873 ;; Read the argument, offering that number (if any) as default.
874 (list (read-from-minibuffer (format (if default
"Goto line%s (%s): "
882 ;; Switch to the desired buffer, one way or another.
884 (let ((window (get-buffer-window buffer
)))
885 (if window
(select-window window
)
886 (switch-to-buffer-other-window buffer
))))
887 ;; Leave mark at previous position
888 (or (region-active-p) (push-mark))
889 ;; Move to the specified line number in that buffer.
893 (if (eq selective-display t
)
894 (re-search-forward "[\n\C-m]" nil
'end
(1- line
))
895 (forward-line (1- line
)))))
897 (defun count-lines-region (start end
)
898 "Print number of lines and characters in the region."
900 (message "Region has %d lines, %d characters"
901 (count-lines start end
) (- end start
)))
904 "Print the current buffer line number and narrowed line number of point."
906 (let ((start (point-min))
907 (n (line-number-at-pos)))
909 (message "Line %d" n
)
913 (message "line %d (narrowed line %d)"
914 (+ n
(line-number-at-pos start
) -
1) n
))))))
916 (defun count-lines (start end
)
917 "Return number of lines between START and END.
918 This is usually the number of newlines between them,
919 but can be one more if START is not equal to END
920 and the greater of them is not at the start of a line."
923 (narrow-to-region start end
)
924 (goto-char (point-min))
925 (if (eq selective-display t
)
928 (while (re-search-forward "[\n\C-m]" nil t
40)
929 (setq done
(+ 40 done
)))
930 (while (re-search-forward "[\n\C-m]" nil t
1)
931 (setq done
(+ 1 done
)))
932 (goto-char (point-max))
933 (if (and (/= start end
)
937 (- (buffer-size) (forward-line (buffer-size)))))))
939 (defun line-number-at-pos (&optional pos
)
940 "Return (narrowed) buffer line number at position POS.
941 If POS is nil, use current buffer location.
942 Counting starts at (point-min), so the value refers
943 to the contents of the accessible portion of the buffer."
944 (let ((opoint (or pos
(point))) start
)
946 (goto-char (point-min))
950 (1+ (count-lines start
(point))))))
952 (defun what-cursor-position (&optional detail
)
953 "Print info on cursor position (on screen and within buffer).
954 Also describe the character after point, and give its character code
955 in octal, decimal and hex.
957 For a non-ASCII multibyte character, also give its encoding in the
958 buffer's selected coding system if the coding system encodes the
959 character safely. If the character is encoded into one byte, that
960 code is shown in hex. If the character is encoded into more than one
961 byte, just \"...\" is shown.
963 In addition, with prefix argument, show details about that character
964 in *Help* buffer. See also the command `describe-char'."
966 (let* ((char (following-char))
970 (total (buffer-size))
971 (percent (if (> total
50000)
972 ;; Avoid overflow from multiplying by 100!
973 (/ (+ (/ total
200) (1- pos
)) (max (/ total
100) 1))
974 (/ (+ (/ total
2) (* 100 (1- pos
))) (max total
1))))
975 (hscroll (if (= (window-hscroll) 0)
977 (format " Hscroll=%d" (window-hscroll))))
978 (col (current-column)))
980 (if (or (/= beg
1) (/= end
(1+ total
)))
981 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
982 pos total percent beg end col hscroll
)
983 (message "point=%d of %d (EOB) column=%d%s"
984 pos total col hscroll
))
985 (let ((coding buffer-file-coding-system
)
986 encoded encoding-msg display-prop under-display
)
988 (eq (coding-system-type coding
) t
))
989 (setq coding default-buffer-file-coding-system
))
990 (if (eq (char-charset char
) 'eight-bit
)
992 (format "(%d, #o%o, #x%x, raw-byte)" char char char
))
993 ;; Check if the character is displayed with some `display'
994 ;; text property. In that case, set under-display to the
995 ;; buffer substring covered by that property.
996 (setq display-prop
(get-text-property pos
'display
))
998 (let ((to (or (next-single-property-change pos
'display
)
1000 (if (< to
(+ pos
4))
1001 (setq under-display
"")
1002 (setq under-display
"..."
1005 (concat (buffer-substring-no-properties pos to
)
1007 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
1010 (if (not (stringp display-prop
))
1011 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1012 char char char under-display
)
1013 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1014 char char char under-display display-prop
))
1016 (format "(%d, #o%o, #x%x, file %s)"
1018 (if (> (length encoded
) 1)
1020 (encoded-string-description encoded coding
)))
1021 (format "(%d, #o%o, #x%x)" char char char
)))))
1023 ;; We show the detailed information about CHAR.
1024 (describe-char (point)))
1025 (if (or (/= beg
1) (/= end
(1+ total
)))
1026 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1028 (single-key-description char
)
1029 (buffer-substring-no-properties (point) (1+ (point))))
1030 encoding-msg pos total percent beg end col hscroll
)
1031 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
1032 (if enable-multibyte-characters
1034 (single-key-description char
)
1035 (buffer-substring-no-properties (point) (1+ (point))))
1036 (single-key-description char
))
1037 encoding-msg pos total percent col hscroll
))))))
1039 ;; Initialize read-expression-map. It is defined at C level.
1040 (let ((m (make-sparse-keymap)))
1041 (define-key m
"\M-\t" 'lisp-complete-symbol
)
1042 (set-keymap-parent m minibuffer-local-map
)
1043 (setq read-expression-map m
))
1045 (defvar read-expression-history nil
)
1047 (defvar minibuffer-completing-symbol nil
1048 "Non-nil means completing a Lisp symbol in the minibuffer.")
1050 (defvar minibuffer-default nil
1051 "The current default value or list of default values in the minibuffer.
1052 The functions `read-from-minibuffer' and `completing-read' bind
1053 this variable locally.")
1055 (defcustom eval-expression-print-level
4
1056 "Value for `print-level' while printing value in `eval-expression'.
1057 A value of nil means no limit."
1059 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1062 (defcustom eval-expression-print-length
12
1063 "Value for `print-length' while printing value in `eval-expression'.
1064 A value of nil means no limit."
1066 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1069 (defcustom eval-expression-debug-on-error t
1070 "If non-nil set `debug-on-error' to t in `eval-expression'.
1071 If nil, don't change the value of `debug-on-error'."
1076 (defun eval-expression-print-format (value)
1077 "Format VALUE as a result of evaluated expression.
1078 Return a formatted string which is displayed in the echo area
1079 in addition to the value printed by prin1 in functions which
1080 display the result of expression evaluation."
1081 (if (and (integerp value
)
1082 (or (not (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1083 (eq this-command last-command
)
1084 (if (boundp 'edebug-active
) edebug-active
)))
1086 (if (or (if (boundp 'edebug-active
) edebug-active
)
1087 (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1088 (prin1-char value
))))
1090 (format " (#o%o, #x%x, %s)" value value char-string
)
1091 (format " (#o%o, #x%x)" value value
)))))
1093 ;; We define this, rather than making `eval' interactive,
1094 ;; for the sake of completion of names like eval-region, eval-buffer.
1095 (defun eval-expression (eval-expression-arg
1096 &optional eval-expression-insert-value
)
1097 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1098 Value is also consed on to front of the variable `values'.
1099 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
1100 insert the result into the current buffer instead of printing it in
1103 If `eval-expression-debug-on-error' is non-nil, which is the default,
1104 this command arranges for all errors to enter the debugger."
1106 (list (let ((minibuffer-completing-symbol t
))
1107 (read-from-minibuffer "Eval: "
1108 nil read-expression-map t
1109 'read-expression-history
))
1110 current-prefix-arg
))
1112 (if (null eval-expression-debug-on-error
)
1113 (setq values
(cons (eval eval-expression-arg
) values
))
1114 (let ((old-value (make-symbol "t")) new-value
)
1115 ;; Bind debug-on-error to something unique so that we can
1116 ;; detect when evaled code changes it.
1117 (let ((debug-on-error old-value
))
1118 (setq values
(cons (eval eval-expression-arg
) values
))
1119 (setq new-value debug-on-error
))
1120 ;; If evaled code has changed the value of debug-on-error,
1121 ;; propagate that change to the global binding.
1122 (unless (eq old-value new-value
)
1123 (setq debug-on-error new-value
))))
1125 (let ((print-length eval-expression-print-length
)
1126 (print-level eval-expression-print-level
))
1127 (if eval-expression-insert-value
1129 (let ((standard-output (current-buffer)))
1130 (prin1 (car values
))))
1132 (prin1 (car values
) t
)
1133 (let ((str (eval-expression-print-format (car values
))))
1134 (if str
(princ str t
)))))))
1136 (defun edit-and-eval-command (prompt command
)
1137 "Prompting with PROMPT, let user edit COMMAND and eval result.
1138 COMMAND is a Lisp expression. Let user edit that expression in
1139 the minibuffer, then read and evaluate the result."
1141 (let ((print-level nil
)
1142 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1144 (read-from-minibuffer prompt
1145 (prin1-to-string command
)
1146 read-expression-map t
1148 ;; If command was added to command-history as a string,
1149 ;; get rid of that. We want only evaluable expressions there.
1150 (if (stringp (car command-history
))
1151 (setq command-history
(cdr command-history
)))))))
1153 ;; If command to be redone does not match front of history,
1154 ;; add it to the history.
1155 (or (equal command
(car command-history
))
1156 (setq command-history
(cons command command-history
)))
1159 (defun repeat-complex-command (arg)
1160 "Edit and re-evaluate last complex command, or ARGth from last.
1161 A complex command is one which used the minibuffer.
1162 The command is placed in the minibuffer as a Lisp form for editing.
1163 The result is executed, repeating the command as changed.
1164 If the command has been changed or is not the most recent previous
1165 command it is added to the front of the command history.
1166 You can use the minibuffer history commands \
1167 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1168 to get different commands to edit and resubmit."
1170 (let ((elt (nth (1- arg
) command-history
))
1175 (let ((print-level nil
)
1176 (minibuffer-history-position arg
)
1177 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1179 (read-from-minibuffer
1180 "Redo: " (prin1-to-string elt
) read-expression-map t
1181 (cons 'command-history arg
))
1183 ;; If command was added to command-history as a
1184 ;; string, get rid of that. We want only
1185 ;; evaluable expressions there.
1186 (if (stringp (car command-history
))
1187 (setq command-history
(cdr command-history
))))))
1189 ;; If command to be redone does not match front of history,
1190 ;; add it to the history.
1191 (or (equal newcmd
(car command-history
))
1192 (setq command-history
(cons newcmd command-history
)))
1195 (error "Argument %d is beyond length of command history" arg
)
1196 (error "There are no previous complex commands to repeat")))))
1198 (defvar minibuffer-history nil
1199 "Default minibuffer history list.
1200 This is used for all minibuffer input
1201 except when an alternate history list is specified.
1203 Maximum length of the history list is determined by the value
1204 of `history-length', which see.")
1205 (defvar minibuffer-history-sexp-flag nil
1206 "Control whether history list elements are expressions or strings.
1207 If the value of this variable equals current minibuffer depth,
1208 they are expressions; otherwise they are strings.
1209 \(That convention is designed to do the right thing for
1210 recursive uses of the minibuffer.)")
1211 (setq minibuffer-history-variable
'minibuffer-history
)
1212 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1213 (defvar minibuffer-history-search-history nil
)
1215 (defvar minibuffer-text-before-history nil
1216 "Text that was in this minibuffer before any history commands.
1217 This is nil if there have not yet been any history commands
1218 in this use of the minibuffer.")
1220 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1222 (defun minibuffer-history-initialize ()
1223 (setq minibuffer-text-before-history nil
))
1225 (defun minibuffer-avoid-prompt (new old
)
1226 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1227 (constrain-to-field nil
(point-max)))
1229 (defcustom minibuffer-history-case-insensitive-variables nil
1230 "Minibuffer history variables for which matching should ignore case.
1231 If a history variable is a member of this list, then the
1232 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1233 commands ignore case when searching it, regardless of `case-fold-search'."
1234 :type
'(repeat variable
)
1237 (defun previous-matching-history-element (regexp n
)
1238 "Find the previous history element that matches REGEXP.
1239 \(Previous history elements refer to earlier actions.)
1240 With prefix argument N, search for Nth previous match.
1241 If N is negative, find the next or Nth next match.
1242 Normally, history elements are matched case-insensitively if
1243 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1244 makes the search case-sensitive.
1245 See also `minibuffer-history-case-insensitive-variables'."
1247 (let* ((enable-recursive-minibuffers t
)
1248 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1250 minibuffer-local-map
1252 'minibuffer-history-search-history
1253 (car minibuffer-history-search-history
))))
1254 ;; Use the last regexp specified, by default, if input is empty.
1255 (list (if (string= regexp
"")
1256 (if minibuffer-history-search-history
1257 (car minibuffer-history-search-history
)
1258 (error "No previous history search regexp"))
1260 (prefix-numeric-value current-prefix-arg
))))
1262 (if (and (zerop minibuffer-history-position
)
1263 (null minibuffer-text-before-history
))
1264 (setq minibuffer-text-before-history
1265 (minibuffer-contents-no-properties)))
1266 (let ((history (symbol-value minibuffer-history-variable
))
1268 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1269 ;; On some systems, ignore case for file names.
1270 (if (memq minibuffer-history-variable
1271 minibuffer-history-case-insensitive-variables
)
1273 ;; Respect the user's setting for case-fold-search:
1279 (pos minibuffer-history-position
))
1282 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1283 (when (= pos prevpos
)
1284 (error (if (= pos
1)
1285 "No later matching history item"
1286 "No earlier matching history item")))
1288 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1289 (let ((print-level nil
))
1290 (prin1-to-string (nth (1- pos
) history
)))
1291 (nth (1- pos
) history
)))
1294 (and (string-match regexp match-string
)
1296 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1297 (match-beginning 1))))
1299 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1300 (setq minibuffer-history-position pos
)
1301 (goto-char (point-max))
1302 (delete-minibuffer-contents)
1303 (insert match-string
)
1304 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1305 (if (memq (car (car command-history
)) '(previous-matching-history-element
1306 next-matching-history-element
))
1307 (setq command-history
(cdr command-history
))))
1309 (defun next-matching-history-element (regexp n
)
1310 "Find the next history element that matches REGEXP.
1311 \(The next history element refers to a more recent action.)
1312 With prefix argument N, search for Nth next match.
1313 If N is negative, find the previous or Nth previous match.
1314 Normally, history elements are matched case-insensitively if
1315 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1316 makes the search case-sensitive."
1318 (let* ((enable-recursive-minibuffers t
)
1319 (regexp (read-from-minibuffer "Next element matching (regexp): "
1321 minibuffer-local-map
1323 'minibuffer-history-search-history
1324 (car minibuffer-history-search-history
))))
1325 ;; Use the last regexp specified, by default, if input is empty.
1326 (list (if (string= regexp
"")
1327 (if minibuffer-history-search-history
1328 (car minibuffer-history-search-history
)
1329 (error "No previous history search regexp"))
1331 (prefix-numeric-value current-prefix-arg
))))
1332 (previous-matching-history-element regexp
(- n
)))
1334 (defvar minibuffer-temporary-goal-position nil
)
1336 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
1337 "Function run by `goto-history-element' before consuming default values.
1338 This is useful to dynamically add more elements to the list of default values
1339 when `goto-history-element' reaches the end of this list.
1340 Before calling this function `goto-history-element' sets the variable
1341 `minibuffer-default-add-done' to t, so it will call this function only
1342 once. In special cases, when this function needs to be called more
1343 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1344 overriding the setting of this variable to t in `goto-history-element'.")
1346 (defvar minibuffer-default-add-done nil
1347 "When nil, add more elements to the end of the list of default values.
1348 The value nil causes `goto-history-element' to add more elements to
1349 the list of defaults when it reaches the end of this list. It does
1350 this by calling a function defined by `minibuffer-default-add-function'.")
1352 (make-variable-buffer-local 'minibuffer-default-add-done
)
1354 (defun minibuffer-default-add-completions ()
1355 "Return a list of all completions without the default value.
1356 This function is used to add all elements of the completion table to
1357 the end of the list of defaults just after the default value."
1359 (let ((def minibuffer-default
)
1360 (all (all-completions ""
1361 minibuffer-completion-table
1362 minibuffer-completion-predicate
1366 (cons def
(delete def all
)))))
1368 (defun goto-history-element (nabs)
1369 "Puts element of the minibuffer history in the minibuffer.
1370 The argument NABS specifies the absolute history position."
1372 (when (and (not minibuffer-default-add-done
)
1373 (functionp minibuffer-default-add-function
)
1374 (< nabs
(- (if (listp minibuffer-default
)
1375 (length minibuffer-default
)
1377 (setq minibuffer-default-add-done t
1378 minibuffer-default
(funcall minibuffer-default-add-function
)))
1379 (let ((minimum (if minibuffer-default
1380 (- (if (listp minibuffer-default
)
1381 (length minibuffer-default
)
1384 elt minibuffer-returned-to-present
)
1385 (if (and (zerop minibuffer-history-position
)
1386 (null minibuffer-text-before-history
))
1387 (setq minibuffer-text-before-history
1388 (minibuffer-contents-no-properties)))
1389 (if (< nabs minimum
)
1390 (if minibuffer-default
1391 (error "End of defaults; no next item")
1392 (error "End of history; no default available")))
1393 (if (> nabs
(length (symbol-value minibuffer-history-variable
)))
1394 (error "Beginning of history; no preceding item"))
1395 (unless (memq last-command
'(next-history-element
1396 previous-history-element
))
1397 (let ((prompt-end (minibuffer-prompt-end)))
1398 (set (make-local-variable 'minibuffer-temporary-goal-position
)
1399 (cond ((<= (point) prompt-end
) prompt-end
)
1402 (goto-char (point-max))
1403 (delete-minibuffer-contents)
1404 (setq minibuffer-history-position nabs
)
1406 (setq elt
(if (listp minibuffer-default
)
1407 (nth (1- (abs nabs
)) minibuffer-default
)
1408 minibuffer-default
)))
1410 (setq elt
(or minibuffer-text-before-history
""))
1411 (setq minibuffer-returned-to-present t
)
1412 (setq minibuffer-text-before-history nil
))
1413 (t (setq elt
(nth (1- minibuffer-history-position
)
1414 (symbol-value minibuffer-history-variable
)))))
1416 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1417 (not minibuffer-returned-to-present
))
1418 (let ((print-level nil
))
1419 (prin1-to-string elt
))
1421 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
1423 (defun next-history-element (n)
1424 "Puts next element of the minibuffer history in the minibuffer.
1425 With argument N, it uses the Nth following element."
1428 (goto-history-element (- minibuffer-history-position n
))))
1430 (defun previous-history-element (n)
1431 "Puts previous element of the minibuffer history in the minibuffer.
1432 With argument N, it uses the Nth previous element."
1435 (goto-history-element (+ minibuffer-history-position n
))))
1437 (defun next-complete-history-element (n)
1438 "Get next history element which completes the minibuffer before the point.
1439 The contents of the minibuffer after the point are deleted, and replaced
1440 by the new completion."
1442 (let ((point-at-start (point)))
1443 (next-matching-history-element
1445 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1447 ;; next-matching-history-element always puts us at (point-min).
1448 ;; Move to the position we were at before changing the buffer contents.
1449 ;; This is still sensical, because the text before point has not changed.
1450 (goto-char point-at-start
)))
1452 (defun previous-complete-history-element (n)
1454 Get previous history element which completes the minibuffer before the point.
1455 The contents of the minibuffer after the point are deleted, and replaced
1456 by the new completion."
1458 (next-complete-history-element (- n
)))
1460 ;; For compatibility with the old subr of the same name.
1461 (defun minibuffer-prompt-width ()
1462 "Return the display width of the minibuffer prompt.
1463 Return 0 if current buffer is not a minibuffer."
1464 ;; Return the width of everything before the field at the end of
1465 ;; the buffer; this should be 0 for normal buffers.
1466 (1- (minibuffer-prompt-end)))
1468 ;; isearch minibuffer history
1469 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
1471 (defvar minibuffer-history-isearch-message-overlay
)
1472 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
1474 (defun minibuffer-history-isearch-setup ()
1475 "Set up a minibuffer for using isearch to search the minibuffer history.
1476 Intended to be added to `minibuffer-setup-hook'."
1477 (set (make-local-variable 'isearch-search-fun-function
)
1478 'minibuffer-history-isearch-search
)
1479 (set (make-local-variable 'isearch-message-function
)
1480 'minibuffer-history-isearch-message
)
1481 (set (make-local-variable 'isearch-wrap-function
)
1482 'minibuffer-history-isearch-wrap
)
1483 (set (make-local-variable 'isearch-push-state-function
)
1484 'minibuffer-history-isearch-push-state
)
1485 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
1487 (defun minibuffer-history-isearch-end ()
1488 "Clean up the minibuffer after terminating isearch in the minibuffer."
1489 (if minibuffer-history-isearch-message-overlay
1490 (delete-overlay minibuffer-history-isearch-message-overlay
)))
1492 (defun minibuffer-history-isearch-search ()
1493 "Return the proper search function, for isearch in minibuffer history."
1496 (if isearch-forward
'word-search-forward
'word-search-backward
))
1498 (lambda (string bound noerror
)
1500 ;; Use standard functions to search within minibuffer text
1503 (if isearch-forward
're-search-forward
're-search-backward
))
1505 (if isearch-forward
'search-forward
'search-backward
))))
1507 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1508 ;; searching forward. Lazy-highlight calls this lambda with the
1509 ;; bound arg, so skip the minibuffer prompt.
1510 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
1511 (goto-char (minibuffer-prompt-end)))
1513 ;; 1. First try searching in the initial minibuffer text
1514 (funcall search-fun string
1515 (if isearch-forward bound
(minibuffer-prompt-end))
1517 ;; 2. If the above search fails, start putting next/prev history
1518 ;; elements in the minibuffer successively, and search the string
1519 ;; in them. Do this only when bound is nil (i.e. not while
1520 ;; lazy-highlighting search strings in the current minibuffer text).
1525 (cond (isearch-forward
1526 (next-history-element 1)
1527 (goto-char (minibuffer-prompt-end)))
1529 (previous-history-element 1)
1530 (goto-char (point-max))))
1531 (setq isearch-barrier
(point) isearch-opoint
(point))
1532 ;; After putting the next/prev history element, search
1533 ;; the string in them again, until next-history-element
1534 ;; or previous-history-element raises an error at the
1535 ;; beginning/end of history.
1536 (setq found
(funcall search-fun string
1537 (unless isearch-forward
1538 ;; For backward search, don't search
1539 ;; in the minibuffer prompt
1540 (minibuffer-prompt-end))
1542 ;; Return point of the new search result
1544 ;; Return nil when next(prev)-history-element fails
1547 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
1548 "Display the minibuffer history search prompt.
1549 If there are no search errors, this function displays an overlay with
1550 the isearch prompt which replaces the original minibuffer prompt.
1551 Otherwise, it displays the standard isearch message returned from
1553 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
1554 ;; Use standard function `isearch-message' when not in the minibuffer,
1555 ;; or search fails, or has an error (like incomplete regexp).
1556 ;; This function overwrites minibuffer text with isearch message,
1557 ;; so it's possible to see what is wrong in the search string.
1558 (isearch-message c-q-hack ellipsis
)
1559 ;; Otherwise, put the overlay with the standard isearch prompt over
1560 ;; the initial minibuffer prompt.
1561 (if (overlayp minibuffer-history-isearch-message-overlay
)
1562 (move-overlay minibuffer-history-isearch-message-overlay
1563 (point-min) (minibuffer-prompt-end))
1564 (setq minibuffer-history-isearch-message-overlay
1565 (make-overlay (point-min) (minibuffer-prompt-end)))
1566 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
1567 (overlay-put minibuffer-history-isearch-message-overlay
1568 'display
(isearch-message-prefix c-q-hack ellipsis
))
1569 ;; And clear any previous isearch message.
1572 (defun minibuffer-history-isearch-wrap ()
1573 "Wrap the minibuffer history search when search fails.
1574 Move point to the first history element for a forward search,
1575 or to the last history element for a backward search."
1576 (unless isearch-word
1577 ;; When `minibuffer-history-isearch-search' fails on reaching the
1578 ;; beginning/end of the history, wrap the search to the first/last
1579 ;; minibuffer history element.
1581 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
1582 (goto-history-element 0))
1583 (setq isearch-success t
))
1584 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
1586 (defun minibuffer-history-isearch-push-state ()
1587 "Save a function restoring the state of minibuffer history search.
1588 Save `minibuffer-history-position' to the additional state parameter
1589 in the search status stack."
1591 (minibuffer-history-isearch-pop-state cmd
,minibuffer-history-position
)))
1593 (defun minibuffer-history-isearch-pop-state (cmd hist-pos
)
1594 "Restore the minibuffer history search state.
1595 Go to the history element by the absolute history position HIST-POS."
1596 (goto-history-element hist-pos
))
1599 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1600 (defalias 'advertised-undo
'undo
)
1602 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
1603 "Table mapping redo records to the corresponding undo one.
1604 A redo record for undo-in-region maps to t.
1605 A redo record for ordinary undo maps to the following (earlier) undo.")
1607 (defvar undo-in-region nil
1608 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1610 (defvar undo-no-redo nil
1611 "If t, `undo' doesn't go through redo entries.")
1613 (defvar pending-undo-list nil
1614 "Within a run of consecutive undo commands, list remaining to be undone.
1615 If t, we undid all the way to the end of it.")
1617 (defun undo (&optional arg
)
1618 "Undo some previous changes.
1619 Repeat this command to undo more changes.
1620 A numeric ARG serves as a repeat count.
1622 In Transient Mark mode when the mark is active, only undo changes within
1623 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1624 as an argument limits undo to changes within the current region."
1626 ;; Make last-command indicate for the next command that this was an undo.
1627 ;; That way, another undo will undo more.
1628 ;; If we get to the end of the undo history and get an error,
1629 ;; another undo command will find the undo history empty
1630 ;; and will get another error. To begin undoing the undos,
1631 ;; you must type some other command.
1632 (let ((modified (buffer-modified-p))
1633 (recent-save (recent-auto-save-p))
1635 ;; If we get an error in undo-start,
1636 ;; the next command should not be a "consecutive undo".
1637 ;; So set `this-command' to something other than `undo'.
1638 (setq this-command
'undo-start
)
1640 (unless (and (eq last-command
'undo
)
1641 (or (eq pending-undo-list t
)
1642 ;; If something (a timer or filter?) changed the buffer
1643 ;; since the previous command, don't continue the undo seq.
1644 (let ((list buffer-undo-list
))
1645 (while (eq (car list
) nil
)
1646 (setq list
(cdr list
)))
1647 ;; If the last undo record made was made by undo
1648 ;; it shows nothing else happened in between.
1649 (gethash list undo-equiv-table
))))
1650 (setq undo-in-region
1651 (or (region-active-p) (and arg
(not (numberp arg
)))))
1653 (undo-start (region-beginning) (region-end))
1655 ;; get rid of initial undo boundary
1657 ;; If we got this far, the next command should be a consecutive undo.
1658 (setq this-command
'undo
)
1659 ;; Check to see whether we're hitting a redo record, and if
1660 ;; so, ask the user whether she wants to skip the redo/undo pair.
1661 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
1662 (or (eq (selected-window) (minibuffer-window))
1663 (setq message
(if undo-in-region
1664 (if equiv
"Redo in region!" "Undo in region!")
1665 (if equiv
"Redo!" "Undo!"))))
1666 (when (and (consp equiv
) undo-no-redo
)
1667 ;; The equiv entry might point to another redo record if we have done
1668 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1669 (while (let ((next (gethash equiv undo-equiv-table
)))
1670 (if next
(setq equiv next
))))
1671 (setq pending-undo-list equiv
)))
1674 (prefix-numeric-value arg
)
1676 ;; Record the fact that the just-generated undo records come from an
1677 ;; undo operation--that is, they are redo records.
1678 ;; In the ordinary case (not within a region), map the redo
1679 ;; record to the following undos.
1680 ;; I don't know how to do that in the undo-in-region case.
1681 (puthash buffer-undo-list
1682 (if undo-in-region t pending-undo-list
)
1684 ;; Don't specify a position in the undo record for the undo command.
1685 ;; Instead, undoing this should move point to where the change is.
1686 (let ((tail buffer-undo-list
)
1689 (when (integerp (car tail
))
1690 (let ((pos (car tail
)))
1692 (setcdr prev
(cdr tail
))
1693 (setq buffer-undo-list
(cdr tail
)))
1694 (setq tail
(cdr tail
))
1696 (if (eq pos
(car tail
))
1698 (setcdr prev
(cdr tail
))
1699 (setq buffer-undo-list
(cdr tail
)))
1701 (setq tail
(cdr tail
)))
1703 (setq prev tail tail
(cdr tail
))))
1704 ;; Record what the current undo list says,
1705 ;; so the next command can tell if the buffer was modified in between.
1706 (and modified
(not (buffer-modified-p))
1707 (delete-auto-save-file-if-necessary recent-save
))
1708 ;; Display a message announcing success.
1710 (message "%s" message
))))
1712 (defun buffer-disable-undo (&optional buffer
)
1713 "Make BUFFER stop keeping undo information.
1714 No argument or nil as argument means do this for the current buffer."
1716 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
1717 (setq buffer-undo-list t
)))
1719 (defun undo-only (&optional arg
)
1720 "Undo some previous changes.
1721 Repeat this command to undo more changes.
1722 A numeric ARG serves as a repeat count.
1723 Contrary to `undo', this will not redo a previous undo."
1725 (let ((undo-no-redo t
)) (undo arg
)))
1727 (defvar undo-in-progress nil
1728 "Non-nil while performing an undo.
1729 Some change-hooks test this variable to do something different.")
1731 (defun undo-more (n)
1732 "Undo back N undo-boundaries beyond what was already undone recently.
1733 Call `undo-start' to get ready to undo recent changes,
1734 then call `undo-more' one or more times to undo them."
1735 (or (listp pending-undo-list
)
1736 (error (concat "No further undo information"
1737 (and undo-in-region
" for region"))))
1738 (let ((undo-in-progress t
))
1739 ;; Note: The following, while pulling elements off
1740 ;; `pending-undo-list' will call primitive change functions which
1741 ;; will push more elements onto `buffer-undo-list'.
1742 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
1743 (if (null pending-undo-list
)
1744 (setq pending-undo-list t
))))
1746 ;; Deep copy of a list
1747 (defun undo-copy-list (list)
1748 "Make a copy of undo list LIST."
1749 (mapcar 'undo-copy-list-1 list
))
1751 (defun undo-copy-list-1 (elt)
1753 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
1756 (defun undo-start (&optional beg end
)
1757 "Set `pending-undo-list' to the front of the undo list.
1758 The next call to `undo-more' will undo the most recently made change.
1759 If BEG and END are specified, then only undo elements
1760 that apply to text between BEG and END are used; other undo elements
1761 are ignored. If BEG and END are nil, all undo elements are used."
1762 (if (eq buffer-undo-list t
)
1763 (error "No undo information in this buffer"))
1764 (setq pending-undo-list
1765 (if (and beg end
(not (= beg end
)))
1766 (undo-make-selective-list (min beg end
) (max beg end
))
1769 (defvar undo-adjusted-markers
)
1771 (defun undo-make-selective-list (start end
)
1772 "Return a list of undo elements for the region START to END.
1773 The elements come from `buffer-undo-list', but we keep only
1774 the elements inside this region, and discard those outside this region.
1775 If we find an element that crosses an edge of this region,
1776 we stop and ignore all further elements."
1777 (let ((undo-list-copy (undo-copy-list buffer-undo-list
))
1778 (undo-list (list nil
))
1779 undo-adjusted-markers
1781 undo-elt undo-elt temp-undo-list delta
)
1782 (while undo-list-copy
1783 (setq undo-elt
(car undo-list-copy
))
1785 (cond ((and (consp undo-elt
) (eq (car undo-elt
) t
))
1786 ;; This is a "was unmodified" element.
1787 ;; Keep it if we have kept everything thus far.
1788 (not some-rejected
))
1790 (undo-elt-in-region undo-elt start end
)))))
1793 (setq end
(+ end
(cdr (undo-delta undo-elt
))))
1794 ;; Don't put two nils together in the list
1795 (if (not (and (eq (car undo-list
) nil
)
1797 (setq undo-list
(cons undo-elt undo-list
))))
1798 (if (undo-elt-crosses-region undo-elt start end
)
1799 (setq undo-list-copy nil
)
1800 (setq some-rejected t
)
1801 (setq temp-undo-list
(cdr undo-list-copy
))
1802 (setq delta
(undo-delta undo-elt
))
1804 (when (/= (cdr delta
) 0)
1805 (let ((position (car delta
))
1806 (offset (cdr delta
)))
1808 ;; Loop down the earlier events adjusting their buffer
1809 ;; positions to reflect the fact that a change to the buffer
1810 ;; isn't being undone. We only need to process those element
1811 ;; types which undo-elt-in-region will return as being in
1812 ;; the region since only those types can ever get into the
1815 (while temp-undo-list
1816 (setq undo-elt
(car temp-undo-list
))
1817 (cond ((integerp undo-elt
)
1818 (if (>= undo-elt position
)
1819 (setcar temp-undo-list
(- undo-elt offset
))))
1820 ((atom undo-elt
) nil
)
1821 ((stringp (car undo-elt
))
1822 ;; (TEXT . POSITION)
1823 (let ((text-pos (abs (cdr undo-elt
)))
1824 (point-at-end (< (cdr undo-elt
) 0 )))
1825 (if (>= text-pos position
)
1826 (setcdr undo-elt
(* (if point-at-end -
1 1)
1827 (- text-pos offset
))))))
1828 ((integerp (car undo-elt
))
1830 (when (>= (car undo-elt
) position
)
1831 (setcar undo-elt
(- (car undo-elt
) offset
))
1832 (setcdr undo-elt
(- (cdr undo-elt
) offset
))))
1833 ((null (car undo-elt
))
1834 ;; (nil PROPERTY VALUE BEG . END)
1835 (let ((tail (nthcdr 3 undo-elt
)))
1836 (when (>= (car tail
) position
)
1837 (setcar tail
(- (car tail
) offset
))
1838 (setcdr tail
(- (cdr tail
) offset
))))))
1839 (setq temp-undo-list
(cdr temp-undo-list
))))))))
1840 (setq undo-list-copy
(cdr undo-list-copy
)))
1841 (nreverse undo-list
)))
1843 (defun undo-elt-in-region (undo-elt start end
)
1844 "Determine whether UNDO-ELT falls inside the region START ... END.
1845 If it crosses the edge, we return nil."
1846 (cond ((integerp undo-elt
)
1847 (and (>= undo-elt start
)
1853 ((stringp (car undo-elt
))
1854 ;; (TEXT . POSITION)
1855 (and (>= (abs (cdr undo-elt
)) start
)
1856 (< (abs (cdr undo-elt
)) end
)))
1857 ((and (consp undo-elt
) (markerp (car undo-elt
)))
1858 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1859 ;; See if MARKER is inside the region.
1860 (let ((alist-elt (assq (car undo-elt
) undo-adjusted-markers
)))
1862 (setq alist-elt
(cons (car undo-elt
)
1863 (marker-position (car undo-elt
))))
1864 (setq undo-adjusted-markers
1865 (cons alist-elt undo-adjusted-markers
)))
1866 (and (cdr alist-elt
)
1867 (>= (cdr alist-elt
) start
)
1868 (<= (cdr alist-elt
) end
))))
1869 ((null (car undo-elt
))
1870 ;; (nil PROPERTY VALUE BEG . END)
1871 (let ((tail (nthcdr 3 undo-elt
)))
1872 (and (>= (car tail
) start
)
1873 (<= (cdr tail
) end
))))
1874 ((integerp (car undo-elt
))
1876 (and (>= (car undo-elt
) start
)
1877 (<= (cdr undo-elt
) end
)))))
1879 (defun undo-elt-crosses-region (undo-elt start end
)
1880 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1881 This assumes we have already decided that UNDO-ELT
1882 is not *inside* the region START...END."
1883 (cond ((atom undo-elt
) nil
)
1884 ((null (car undo-elt
))
1885 ;; (nil PROPERTY VALUE BEG . END)
1886 (let ((tail (nthcdr 3 undo-elt
)))
1887 (and (< (car tail
) end
)
1888 (> (cdr tail
) start
))))
1889 ((integerp (car undo-elt
))
1891 (and (< (car undo-elt
) end
)
1892 (> (cdr undo-elt
) start
)))))
1894 ;; Return the first affected buffer position and the delta for an undo element
1895 ;; delta is defined as the change in subsequent buffer positions if we *did*
1897 (defun undo-delta (undo-elt)
1898 (if (consp undo-elt
)
1899 (cond ((stringp (car undo-elt
))
1900 ;; (TEXT . POSITION)
1901 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
1902 ((integerp (car undo-elt
))
1904 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
1909 (defcustom undo-ask-before-discard nil
1910 "If non-nil ask about discarding undo info for the current command.
1911 Normally, Emacs discards the undo info for the current command if
1912 it exceeds `undo-outer-limit'. But if you set this option
1913 non-nil, it asks in the echo area whether to discard the info.
1914 If you answer no, there is a slight risk that Emacs might crash, so
1915 only do it if you really want to undo the command.
1917 This option is mainly intended for debugging. You have to be
1918 careful if you use it for other purposes. Garbage collection is
1919 inhibited while the question is asked, meaning that Emacs might
1920 leak memory. So you should make sure that you do not wait
1921 excessively long before answering the question."
1926 (defvar undo-extra-outer-limit nil
1927 "If non-nil, an extra level of size that's ok in an undo item.
1928 We don't ask the user about truncating the undo list until the
1929 current item gets bigger than this amount.
1931 This variable only matters if `undo-ask-before-discard' is non-nil.")
1932 (make-variable-buffer-local 'undo-extra-outer-limit
)
1934 ;; When the first undo batch in an undo list is longer than
1935 ;; undo-outer-limit, this function gets called to warn the user that
1936 ;; the undo info for the current command was discarded. Garbage
1937 ;; collection is inhibited around the call, so it had better not do a
1939 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
1940 (defun undo-outer-limit-truncate (size)
1941 (if undo-ask-before-discard
1942 (when (or (null undo-extra-outer-limit
)
1943 (> size undo-extra-outer-limit
))
1944 ;; Don't ask the question again unless it gets even bigger.
1945 ;; This applies, in particular, if the user quits from the question.
1946 ;; Such a quit quits out of GC, but something else will call GC
1947 ;; again momentarily. It will call this function again,
1948 ;; but we don't want to ask the question again.
1949 (setq undo-extra-outer-limit
(+ size
50000))
1950 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
1951 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
1952 (buffer-name) size
)))
1953 (progn (setq buffer-undo-list nil
)
1954 (setq undo-extra-outer-limit nil
)
1957 (display-warning '(undo discard-info
)
1959 (format "Buffer `%s' undo info was %d bytes long.\n"
1961 "The undo info was discarded because it exceeded \
1964 This is normal if you executed a command that made a huge change
1965 to the buffer. In that case, to prevent similar problems in the
1966 future, set `undo-outer-limit' to a value that is large enough to
1967 cover the maximum size of normal changes you expect a single
1968 command to make, but not so large that it might exceed the
1969 maximum memory allotted to Emacs.
1971 If you did not execute any such command, the situation is
1972 probably due to a bug and you should report it.
1974 You can disable the popping up of this buffer by adding the entry
1975 \(undo discard-info) to the user option `warning-suppress-types'.\n")
1977 (setq buffer-undo-list nil
)
1980 (defvar shell-command-history nil
1981 "History list for some commands that read shell commands.
1983 Maximum length of the history list is determined by the value
1984 of `history-length', which see.")
1986 (defvar shell-command-switch
"-c"
1987 "Switch used to have the shell execute its command line argument.")
1989 (defvar shell-command-default-error-buffer nil
1990 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1991 This buffer is used when `shell-command' or `shell-command-on-region'
1992 is run interactively. A value of nil means that output to stderr and
1993 stdout will be intermixed in the output stream.")
1995 (declare-function mailcap-file-default-commands
"mailcap" (files))
1997 (defun minibuffer-default-add-shell-commands ()
1998 "Return a list of all commands associated with the current file.
1999 This function is used to add all related commands retrieved by `mailcap'
2000 to the end of the list of defaults just after the default value."
2002 (let* ((filename (if (listp minibuffer-default
)
2003 (car minibuffer-default
)
2004 minibuffer-default
))
2005 (commands (and filename
(require 'mailcap nil t
)
2006 (mailcap-file-default-commands (list filename
)))))
2007 (setq commands
(mapcar (lambda (command)
2008 (concat command
" " filename
))
2010 (if (listp minibuffer-default
)
2011 (append minibuffer-default commands
)
2012 (cons minibuffer-default commands
))))
2014 (defvar shell-delimiter-argument-list
)
2015 (defvar shell-file-name-chars
)
2016 (defvar shell-file-name-quote-list
)
2018 (defun minibuffer-complete-shell-command ()
2019 "Dynamically complete shell command at point."
2022 (let ((comint-delimiter-argument-list shell-delimiter-argument-list
)
2023 (comint-file-name-chars shell-file-name-chars
)
2024 (comint-file-name-quote-list shell-file-name-quote-list
))
2025 (run-hook-with-args-until-success 'shell-dynamic-complete-functions
)))
2027 (defvar minibuffer-local-shell-command-map
2028 (let ((map (make-sparse-keymap)))
2029 (set-keymap-parent map minibuffer-local-map
)
2030 (define-key map
"\t" 'minibuffer-complete-shell-command
)
2032 "Keymap used for completing shell commands in minibuffer.")
2034 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
2035 "Read a shell command from the minibuffer.
2036 The arguments are the same as the ones of `read-from-minibuffer',
2037 except READ and KEYMAP are missing and HIST defaults
2038 to `shell-command-history'."
2039 (minibuffer-with-setup-hook
2041 (set (make-local-variable 'minibuffer-default-add-function
)
2042 'minibuffer-default-add-shell-commands
))
2043 (apply 'read-from-minibuffer prompt initial-contents
2044 minibuffer-local-shell-command-map
2046 (or hist
'shell-command-history
)
2049 (defun shell-command (command &optional output-buffer error-buffer
)
2050 "Execute string COMMAND in inferior shell; display output, if any.
2051 With prefix argument, insert the COMMAND's output at point.
2053 If COMMAND ends in ampersand, execute it asynchronously.
2054 The output appears in the buffer `*Async Shell Command*'.
2055 That buffer is in shell mode.
2057 Otherwise, COMMAND is executed synchronously. The output appears in
2058 the buffer `*Shell Command Output*'. If the output is short enough to
2059 display in the echo area (which is determined by the variables
2060 `resize-mini-windows' and `max-mini-window-height'), it is shown
2061 there, but it is nonetheless available in buffer `*Shell Command
2062 Output*' even though that buffer is not automatically displayed.
2064 To specify a coding system for converting non-ASCII characters
2065 in the shell command output, use \\[universal-coding-system-argument] \
2066 before this command.
2068 Noninteractive callers can specify coding systems by binding
2069 `coding-system-for-read' and `coding-system-for-write'.
2071 The optional second argument OUTPUT-BUFFER, if non-nil,
2072 says to put the output in some other buffer.
2073 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2074 If OUTPUT-BUFFER is not a buffer and not nil,
2075 insert output in current buffer. (This cannot be done asynchronously.)
2076 In either case, the output is inserted after point (leaving mark after it).
2078 If the command terminates without error, but generates output,
2079 and you did not specify \"insert it in the current buffer\",
2080 the output can be displayed in the echo area or in its buffer.
2081 If the output is short enough to display in the echo area
2082 \(determined by the variable `max-mini-window-height' if
2083 `resize-mini-windows' is non-nil), it is shown there.
2084 Otherwise,the buffer containing the output is displayed.
2086 If there is output and an error, and you did not specify \"insert it
2087 in the current buffer\", a message about the error goes at the end
2090 If there is no output, or if output is inserted in the current buffer,
2091 then `*Shell Command Output*' is deleted.
2093 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2094 or buffer name to which to direct the command's standard error output.
2095 If it is nil, error output is mingled with regular output.
2096 In an interactive call, the variable `shell-command-default-error-buffer'
2097 specifies the value of ERROR-BUFFER."
2101 (read-shell-command "Shell command: " nil nil
2102 (and buffer-file-name
2103 (file-relative-name buffer-file-name
)))
2105 shell-command-default-error-buffer
))
2106 ;; Look for a handler in case default-directory is a remote file name.
2108 (find-file-name-handler (directory-file-name default-directory
)
2111 (funcall handler
'shell-command command output-buffer error-buffer
)
2112 (if (and output-buffer
2113 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
2114 ;; Output goes in current buffer.
2118 (expand-file-name "scor"
2119 (or small-temporary-file-directory
2120 temporary-file-directory
)))
2122 (barf-if-buffer-read-only)
2124 ;; We do not use -f for csh; we will not support broken use of
2125 ;; .cshrcs. Even the BSD csh manual says to use
2126 ;; "if ($?prompt) exit" before things which are not useful
2127 ;; non-interactively. Besides, if someone wants their other
2128 ;; aliases for shell commands then they can still have them.
2129 (call-process shell-file-name nil
2133 nil shell-command-switch command
)
2134 (when (and error-file
(file-exists-p error-file
))
2135 (if (< 0 (nth 7 (file-attributes error-file
)))
2136 (with-current-buffer (get-buffer-create error-buffer
)
2137 (let ((pos-from-end (- (point-max) (point))))
2140 ;; Do no formatting while reading error file,
2141 ;; because that can run a shell command, and we
2142 ;; don't want that to cause an infinite recursion.
2143 (format-insert-file error-file nil
)
2144 ;; Put point after the inserted errors.
2145 (goto-char (- (point-max) pos-from-end
)))
2146 (display-buffer (current-buffer))))
2147 (delete-file error-file
))
2148 ;; This is like exchange-point-and-mark, but doesn't
2149 ;; activate the mark. It is cleaner to avoid activation,
2150 ;; even though the command loop would deactivate the mark
2151 ;; because we inserted text.
2152 (goto-char (prog1 (mark t
)
2153 (set-marker (mark-marker) (point)
2154 (current-buffer)))))
2155 ;; Output goes in a separate buffer.
2156 ;; Preserve the match data in case called from a program.
2158 (if (string-match "[ \t]*&[ \t]*\\'" command
)
2159 ;; Command ending with ampersand means asynchronous.
2160 (let ((buffer (get-buffer-create
2161 (or output-buffer
"*Async Shell Command*")))
2162 (directory default-directory
)
2164 ;; Remove the ampersand.
2165 (setq command
(substring command
0 (match-beginning 0)))
2166 ;; If will kill a process, query first.
2167 (setq proc
(get-buffer-process buffer
))
2169 (if (yes-or-no-p "A command is running. Kill it? ")
2171 (error "Shell command in progress")))
2172 (with-current-buffer buffer
2173 (setq buffer-read-only nil
)
2175 (display-buffer buffer
)
2176 (setq default-directory directory
)
2177 (setq proc
(start-process "Shell" buffer shell-file-name
2178 shell-command-switch command
))
2179 (setq mode-line-process
'(":%s"))
2180 (require 'shell
) (shell-mode)
2181 (set-process-sentinel proc
'shell-command-sentinel
)
2183 (shell-command-on-region (point) (point) command
2184 output-buffer nil error-buffer
)))))))
2186 (defun display-message-or-buffer (message
2187 &optional buffer-name not-this-window frame
)
2188 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2189 MESSAGE may be either a string or a buffer.
2191 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2192 the maximum height of the echo area, as defined by `max-mini-window-height'
2193 if `resize-mini-windows' is non-nil.
2195 Returns either the string shown in the echo area, or when a pop-up
2196 buffer is used, the window used to display it.
2198 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2199 name of the buffer used to display it in the case where a pop-up buffer
2200 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2201 string and it is displayed in the echo area, it is not specified whether
2202 the contents are inserted into the buffer anyway.
2204 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2205 and only used if a buffer is displayed."
2206 (cond ((and (stringp message
) (not (string-match "\n" message
)))
2207 ;; Trivial case where we can use the echo area
2208 (message "%s" message
))
2209 ((and (stringp message
)
2210 (= (string-match "\n" message
) (1- (length message
))))
2211 ;; Trivial case where we can just remove single trailing newline
2212 (message "%s" (substring message
0 (1- (length message
)))))
2215 (with-current-buffer
2216 (if (bufferp message
)
2218 (get-buffer-create (or buffer-name
"*Message*")))
2220 (unless (bufferp message
)
2225 (if (= (buffer-size) 0)
2227 (count-screen-lines nil nil nil
(minibuffer-window)))))
2229 ((and (or (<= lines
1)
2231 (if resize-mini-windows
2232 (cond ((floatp max-mini-window-height
)
2234 max-mini-window-height
))
2235 ((integerp max-mini-window-height
)
2236 max-mini-window-height
)
2240 ;; Don't use the echo area if the output buffer is
2241 ;; already dispayed in the selected frame.
2242 (not (get-buffer-window (current-buffer))))
2244 (goto-char (point-max))
2247 (message "%s" (buffer-substring (point-min) (point))))
2250 (goto-char (point-min))
2251 (display-buffer (current-buffer)
2252 not-this-window frame
))))))))
2255 ;; We have a sentinel to prevent insertion of a termination message
2256 ;; in the buffer itself.
2257 (defun shell-command-sentinel (process signal
)
2258 (if (memq (process-status process
) '(exit signal
))
2260 (car (cdr (cdr (process-command process
))))
2261 (substring signal
0 -
1))))
2263 (defun shell-command-on-region (start end command
2264 &optional output-buffer replace
2265 error-buffer display-error-buffer
)
2266 "Execute string COMMAND in inferior shell with region as input.
2267 Normally display output (if any) in temp buffer `*Shell Command Output*';
2268 Prefix arg means replace the region with it. Return the exit code of
2271 To specify a coding system for converting non-ASCII characters
2272 in the input and output to the shell command, use \\[universal-coding-system-argument]
2273 before this command. By default, the input (from the current buffer)
2274 is encoded in the same coding system that will be used to save the file,
2275 `buffer-file-coding-system'. If the output is going to replace the region,
2276 then it is decoded from that same coding system.
2278 The noninteractive arguments are START, END, COMMAND,
2279 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2280 Noninteractive callers can specify coding systems by binding
2281 `coding-system-for-read' and `coding-system-for-write'.
2283 If the command generates output, the output may be displayed
2284 in the echo area or in a buffer.
2285 If the output is short enough to display in the echo area
2286 \(determined by the variable `max-mini-window-height' if
2287 `resize-mini-windows' is non-nil), it is shown there. Otherwise
2288 it is displayed in the buffer `*Shell Command Output*'. The output
2289 is available in that buffer in both cases.
2291 If there is output and an error, a message about the error
2292 appears at the end of the output.
2294 If there is no output, or if output is inserted in the current buffer,
2295 then `*Shell Command Output*' is deleted.
2297 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2298 that says to put the output in some other buffer.
2299 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2300 If OUTPUT-BUFFER is not a buffer and not nil,
2301 insert output in the current buffer.
2302 In either case, the output is inserted after point (leaving mark after it).
2304 If REPLACE, the optional fifth argument, is non-nil, that means insert
2305 the output in place of text from START to END, putting point and mark
2308 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2309 or buffer name to which to direct the command's standard error output.
2310 If it is nil, error output is mingled with regular output.
2311 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2312 were any errors. (This is always t, interactively.)
2313 In an interactive call, the variable `shell-command-default-error-buffer'
2314 specifies the value of ERROR-BUFFER."
2315 (interactive (let (string)
2317 (error "The mark is not set now, so there is no region"))
2318 ;; Do this before calling region-beginning
2319 ;; and region-end, in case subprocess output
2320 ;; relocates them while we are in the minibuffer.
2321 (setq string
(read-shell-command "Shell command on region: "))
2322 ;; call-interactively recognizes region-beginning and
2323 ;; region-end specially, leaving them in the history.
2324 (list (region-beginning) (region-end)
2328 shell-command-default-error-buffer
2333 (expand-file-name "scor"
2334 (or small-temporary-file-directory
2335 temporary-file-directory
)))
2340 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
2341 ;; Replace specified region with output from command.
2342 (let ((swap (and replace
(< start end
))))
2343 ;; Don't muck with mark unless REPLACE says we should.
2345 (and replace
(push-mark (point) 'nomsg
))
2347 (call-process-region start end shell-file-name t
2351 nil shell-command-switch command
))
2352 ;; It is rude to delete a buffer which the command is not using.
2353 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2354 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2355 ;; (kill-buffer shell-buffer)))
2356 ;; Don't muck with mark unless REPLACE says we should.
2357 (and replace swap
(exchange-point-and-mark)))
2358 ;; No prefix argument: put the output in a temp buffer,
2359 ;; replacing its entire contents.
2360 (let ((buffer (get-buffer-create
2361 (or output-buffer
"*Shell Command Output*"))))
2363 (if (eq buffer
(current-buffer))
2364 ;; If the input is the same buffer as the output,
2365 ;; delete everything but the specified region,
2366 ;; then replace that region with the output.
2367 (progn (setq buffer-read-only nil
)
2368 (delete-region (max start end
) (point-max))
2369 (delete-region (point-min) (min start end
))
2371 (call-process-region (point-min) (point-max)
2376 nil shell-command-switch
2378 ;; Clear the output buffer, then run the command with
2380 (let ((directory default-directory
))
2383 (setq buffer-read-only nil
)
2384 (if (not output-buffer
)
2385 (setq default-directory directory
))
2388 (call-process-region start end shell-file-name nil
2390 (list buffer error-file
)
2392 nil shell-command-switch command
)))
2393 ;; Report the output.
2394 (with-current-buffer buffer
2395 (setq mode-line-process
2396 (cond ((null exit-status
)
2398 ((stringp exit-status
)
2399 (format " - Signal [%s]" exit-status
))
2400 ((not (equal 0 exit-status
))
2401 (format " - Exit [%d]" exit-status
)))))
2402 (if (with-current-buffer buffer
(> (point-max) (point-min)))
2403 ;; There's some output, display it
2404 (display-message-or-buffer buffer
)
2405 ;; No output; error?
2408 (< 0 (nth 7 (file-attributes error-file
))))
2411 (cond ((null exit-status
)
2412 (message "(Shell command failed with error)"))
2413 ((equal 0 exit-status
)
2414 (message "(Shell command succeeded with %s)"
2416 ((stringp exit-status
)
2417 (message "(Shell command killed by signal %s)"
2420 (message "(Shell command failed with code %d and %s)"
2421 exit-status output
))))
2422 ;; Don't kill: there might be useful info in the undo-log.
2423 ;; (kill-buffer buffer)
2426 (when (and error-file
(file-exists-p error-file
))
2427 (if (< 0 (nth 7 (file-attributes error-file
)))
2428 (with-current-buffer (get-buffer-create error-buffer
)
2429 (let ((pos-from-end (- (point-max) (point))))
2432 ;; Do no formatting while reading error file,
2433 ;; because that can run a shell command, and we
2434 ;; don't want that to cause an infinite recursion.
2435 (format-insert-file error-file nil
)
2436 ;; Put point after the inserted errors.
2437 (goto-char (- (point-max) pos-from-end
)))
2438 (and display-error-buffer
2439 (display-buffer (current-buffer)))))
2440 (delete-file error-file
))
2443 (defun shell-command-to-string (command)
2444 "Execute shell command COMMAND and return its output as a string."
2445 (with-output-to-string
2446 (with-current-buffer
2448 (call-process shell-file-name nil t nil shell-command-switch command
))))
2450 (defun process-file (program &optional infile buffer display
&rest args
)
2451 "Process files synchronously in a separate process.
2452 Similar to `call-process', but may invoke a file handler based on
2453 `default-directory'. The current working directory of the
2454 subprocess is `default-directory'.
2456 File names in INFILE and BUFFER are handled normally, but file
2457 names in ARGS should be relative to `default-directory', as they
2458 are passed to the process verbatim. \(This is a difference to
2459 `call-process' which does not support file handlers for INFILE
2462 Some file handlers might not support all variants, for example
2463 they might behave as if DISPLAY was nil, regardless of the actual
2465 (let ((fh (find-file-name-handler default-directory
'process-file
))
2468 (if fh
(apply fh
'process-file program infile buffer display args
)
2469 (when infile
(setq lc
(file-local-copy infile
)))
2470 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
2471 (make-temp-file "emacs")))
2473 (apply 'call-process program
2475 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
2477 (when stderr-file
(copy-file stderr-file
(cadr buffer
)))))
2478 (when stderr-file
(delete-file stderr-file
))
2479 (when lc
(delete-file lc
)))))
2481 (defun start-file-process (name buffer program
&rest program-args
)
2482 "Start a program in a subprocess. Return the process object for it.
2484 Similar to `start-process', but may invoke a file handler based on
2485 `default-directory'. See Info node `(elisp)Magic File Names'.
2487 This handler ought to run PROGRAM, perhaps on the local host,
2488 perhaps on a remote host that corresponds to `default-directory'.
2489 In the latter case, the local part of `default-directory' becomes
2490 the working directory of the process.
2492 PROGRAM and PROGRAM-ARGS might be file names. They are not
2493 objects of file handler invocation."
2494 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
2495 (if fh
(apply fh
'start-file-process name buffer program program-args
)
2496 (apply 'start-process name buffer program program-args
))))
2499 (defvar universal-argument-map
2500 (let ((map (make-sparse-keymap)))
2501 (define-key map
[t] 'universal-argument-other-key)
2502 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2503 (define-key map [switch-frame] nil)
2504 (define-key map [?\C-u] 'universal-argument-more)
2505 (define-key map [?-] 'universal-argument-minus)
2506 (define-key map [?0] 'digit-argument)
2507 (define-key map [?1] 'digit-argument)
2508 (define-key map [?2] 'digit-argument)
2509 (define-key map [?3] 'digit-argument)
2510 (define-key map [?4] 'digit-argument)
2511 (define-key map [?5] 'digit-argument)
2512 (define-key map [?6] 'digit-argument)
2513 (define-key map [?7] 'digit-argument)
2514 (define-key map [?8] 'digit-argument)
2515 (define-key map [?9] 'digit-argument)
2516 (define-key map [kp-0] 'digit-argument)
2517 (define-key map [kp-1] 'digit-argument)
2518 (define-key map [kp-2] 'digit-argument)
2519 (define-key map [kp-3] 'digit-argument)
2520 (define-key map [kp-4] 'digit-argument)
2521 (define-key map [kp-5] 'digit-argument)
2522 (define-key map [kp-6] 'digit-argument)
2523 (define-key map [kp-7] 'digit-argument)
2524 (define-key map [kp-8] 'digit-argument)
2525 (define-key map [kp-9] 'digit-argument)
2526 (define-key map [kp-subtract] 'universal-argument-minus)
2528 "Keymap used while processing \\[universal-argument].")
2530 (defvar universal-argument-num-events nil
2531 "Number of argument-specifying events read by `universal-argument'.
2532 `universal-argument-other-key' uses this to discard those events
2533 from (this-command-keys), and reread only the final command.")
2535 (defvar overriding-map-is-bound nil
2536 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2538 (defvar saved-overriding-map nil
2539 "The saved value of `overriding-terminal-local-map'.
2540 That variable gets restored to this value on exiting \"universal
2543 (defun ensure-overriding-map-is-bound ()
2544 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2545 (unless overriding-map-is-bound
2546 (setq saved-overriding-map overriding-terminal-local-map)
2547 (setq overriding-terminal-local-map universal-argument-map)
2548 (setq overriding-map-is-bound t)))
2550 (defun restore-overriding-map ()
2551 "Restore `overriding-terminal-local-map' to its saved value."
2552 (setq overriding-terminal-local-map saved-overriding-map)
2553 (setq overriding-map-is-bound nil))
2555 (defun universal-argument ()
2556 "Begin a numeric argument for the following command.
2557 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2558 \\[universal-argument] following the digits or minus sign ends the argument.
2559 \\[universal-argument] without digits or minus sign provides 4 as argument.
2560 Repeating \\[universal-argument] without digits or minus sign
2561 multiplies the argument by 4 each time.
2562 For some commands, just \\[universal-argument] by itself serves as a flag
2563 which is different in effect from any particular numeric argument.
2564 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2566 (setq prefix-arg (list 4))
2567 (setq universal-argument-num-events (length (this-command-keys)))
2568 (ensure-overriding-map-is-bound))
2570 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2571 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2572 (defun universal-argument-more (arg)
2575 (setq prefix-arg (list (* 4 (car arg))))
2577 (setq prefix-arg (list -4))
2578 (setq prefix-arg arg)
2579 (restore-overriding-map)))
2580 (setq universal-argument-num-events (length (this-command-keys))))
2582 (defun negative-argument (arg)
2583 "Begin a negative numeric argument for the next command.
2584 \\[universal-argument] following digits or minus sign ends the argument."
2586 (cond ((integerp arg)
2587 (setq prefix-arg (- arg)))
2589 (setq prefix-arg nil))
2591 (setq prefix-arg '-)))
2592 (setq universal-argument-num-events (length (this-command-keys)))
2593 (ensure-overriding-map-is-bound))
2595 (defun digit-argument (arg)
2596 "Part of the numeric argument for the next command.
2597 \\[universal-argument] following digits or minus sign ends the argument."
2599 (let* ((char (if (integerp last-command-event)
2601 (get last-command-event 'ascii-character)))
2602 (digit (- (logand char ?\177) ?0)))
2603 (cond ((integerp arg)
2604 (setq prefix-arg (+ (* arg 10)
2605 (if (< arg 0) (- digit) digit))))
2607 ;; Treat -0 as just -, so that -01 will work.
2608 (setq prefix-arg (if (zerop digit) '- (- digit))))
2610 (setq prefix-arg digit))))
2611 (setq universal-argument-num-events (length (this-command-keys)))
2612 (ensure-overriding-map-is-bound))
2614 ;; For backward compatibility, minus with no modifiers is an ordinary
2615 ;; command if digits have already been entered.
2616 (defun universal-argument-minus (arg)
2619 (universal-argument-other-key arg)
2620 (negative-argument arg)))
2622 ;; Anything else terminates the argument and is left in the queue to be
2623 ;; executed as a command.
2624 (defun universal-argument-other-key (arg)
2626 (setq prefix-arg arg)
2627 (let* ((key (this-command-keys))
2628 (keylist (listify-key-sequence key)))
2629 (setq unread-command-events
2630 (append (nthcdr universal-argument-num-events keylist)
2631 unread-command-events)))
2632 (reset-this-command-lengths)
2633 (restore-overriding-map))
2635 (defvar buffer-substring-filters nil
2636 "List of filter functions for `filter-buffer-substring'.
2637 Each function must accept a single argument, a string, and return
2638 a string. The buffer substring is passed to the first function
2639 in the list, and the return value of each function is passed to
2640 the next. The return value of the last function is used as the
2641 return value of `filter-buffer-substring'.
2643 If this variable is nil, no filtering is performed.")
2645 (defun filter-buffer-substring (beg end &optional delete noprops)
2646 "Return the buffer substring between BEG and END, after filtering.
2647 The buffer substring is passed through each of the filter
2648 functions in `buffer-substring-filters', and the value from the
2649 last filter function is returned. If `buffer-substring-filters'
2650 is nil, the buffer substring is returned unaltered.
2652 If DELETE is non-nil, the text between BEG and END is deleted
2655 If NOPROPS is non-nil, final string returned does not include
2656 text properties, while the string passed to the filters still
2657 includes text properties from the buffer text.
2659 Point is temporarily set to BEG before calling
2660 `buffer-substring-filters', in case the functions need to know
2661 where the text came from.
2663 This function should be used instead of `buffer-substring',
2664 `buffer-substring-no-properties', or `delete-and-extract-region'
2665 when you want to allow filtering to take place. For example,
2666 major or minor modes can use `buffer-substring-filters' to
2667 extract characters that are special to a buffer, and should not
2668 be copied into other buffers."
2670 ((or delete buffer-substring-filters)
2673 (let ((string (if delete (delete-and-extract-region beg end)
2674 (buffer-substring beg end))))
2675 (dolist (filter buffer-substring-filters)
2676 (setq string (funcall filter string)))
2678 (set-text-properties 0 (length string) nil string))
2681 (buffer-substring-no-properties beg end))
2683 (buffer-substring beg end))))
2686 ;;;; Window system cut and paste hooks.
2688 (defvar interprogram-cut-function nil
2689 "Function to call to make a killed region available to other programs.
2691 Most window systems provide some sort of facility for cutting and
2692 pasting text between the windows of different programs.
2693 This variable holds a function that Emacs calls whenever text
2694 is put in the kill ring, to make the new kill available to other
2697 The function takes one or two arguments.
2698 The first argument, TEXT, is a string containing
2699 the text which should be made available.
2700 The second, optional, argument PUSH, has the same meaning as the
2701 similar argument to `x-set-cut-buffer', which see.")
2703 (defvar interprogram-paste-function nil
2704 "Function to call to get text cut from other programs.
2706 Most window systems provide some sort of facility for cutting and
2707 pasting text between the windows of different programs.
2708 This variable holds a function that Emacs calls to obtain
2709 text that other programs have provided for pasting.
2711 The function should be called with no arguments. If the function
2712 returns nil, then no other program has provided such text, and the top
2713 of the Emacs kill ring should be used. If the function returns a
2714 string, then the caller of the function \(usually `current-kill')
2715 should put this string in the kill ring as the latest kill.
2717 This function may also return a list of strings if the window
2718 system supports multiple selections. The first string will be
2719 used as the pasted text, but the other will be placed in the
2720 kill ring for easy access via `yank-pop'.
2722 Note that the function should return a string only if a program other
2723 than Emacs has provided a string for pasting; if Emacs provided the
2724 most recent string, the function should return nil. If it is
2725 difficult to tell whether Emacs or some other program provided the
2726 current string, it is probably good enough to return nil if the string
2727 is equal (according to `string=') to the last text Emacs provided.")
2731 ;;;; The kill ring data structure.
2733 (defvar kill-ring nil
2734 "List of killed text sequences.
2735 Since the kill ring is supposed to interact nicely with cut-and-paste
2736 facilities offered by window systems, use of this variable should
2737 interact nicely with `interprogram-cut-function' and
2738 `interprogram-paste-function'. The functions `kill-new',
2739 `kill-append', and `current-kill' are supposed to implement this
2740 interaction; you may want to use them instead of manipulating the kill
2743 (defcustom kill-ring-max 60
2744 "Maximum length of kill ring before oldest elements are thrown away."
2748 (defvar kill-ring-yank-pointer nil
2749 "The tail of the kill ring whose car is the last thing yanked.")
2751 (defun kill-new (string &optional replace yank-handler)
2752 "Make STRING the latest kill in the kill ring.
2753 Set `kill-ring-yank-pointer' to point to it.
2754 If `interprogram-cut-function' is non-nil, apply it to STRING.
2755 Optional second argument REPLACE non-nil means that STRING will replace
2756 the front of the kill ring, rather than being added to the list.
2758 Optional third arguments YANK-HANDLER controls how the STRING is later
2759 inserted into a buffer; see `insert-for-yank' for details.
2760 When a yank handler is specified, STRING must be non-empty (the yank
2761 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2763 When the yank handler has a non-nil PARAM element, the original STRING
2764 argument is not used by `insert-for-yank'. However, since Lisp code
2765 may access and use elements from the kill ring directly, the STRING
2766 argument should still be a \"useful\" string for such uses."
2767 (if (> (length string) 0)
2769 (put-text-property 0 (length string)
2770 'yank-handler yank-handler string))
2772 (signal 'args-out-of-range
2773 (list string "yank-handler specified for empty string"))))
2774 (if (fboundp 'menu-bar-update-yank-menu)
2775 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2776 (if (and replace kill-ring)
2777 (setcar kill-ring string)
2778 (push string kill-ring)
2779 (if (> (length kill-ring) kill-ring-max)
2780 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2781 (setq kill-ring-yank-pointer kill-ring)
2782 (if interprogram-cut-function
2783 (funcall interprogram-cut-function string (not replace))))
2785 (defun kill-append (string before-p &optional yank-handler)
2786 "Append STRING to the end of the latest kill in the kill ring.
2787 If BEFORE-P is non-nil, prepend STRING to the kill.
2788 Optional third argument YANK-HANDLER, if non-nil, specifies the
2789 yank-handler text property to be set on the combined kill ring
2790 string. If the specified yank-handler arg differs from the
2791 yank-handler property of the latest kill string, this function
2792 adds the combined string to the kill ring as a new element,
2793 instead of replacing the last kill with it.
2794 If `interprogram-cut-function' is set, pass the resulting kill to it."
2795 (let* ((cur (car kill-ring)))
2796 (kill-new (if before-p (concat string cur) (concat cur string))
2797 (or (= (length cur) 0)
2798 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2801 (defcustom yank-pop-change-selection nil
2802 "If non-nil, rotating the kill ring changes the window system selection."
2807 (defun current-kill (n &optional do-not-move)
2808 "Rotate the yanking point by N places, and then return that kill.
2809 If N is zero, `interprogram-paste-function' is set, and calling
2810 it returns a string or list of strings, then that string (or
2811 list) is added to the front of the kill ring and the string (or
2812 first string in the list) is returned as the latest kill.
2814 If N is not zero, and if `yank-pop-change-selection' is
2815 non-nil, use `interprogram-cut-function' to transfer the
2816 kill at the new yank point into the window system selection.
2818 If optional arg DO-NOT-MOVE is non-nil, then don't actually
2819 move the yanking point; just return the Nth kill forward."
2821 (let ((interprogram-paste (and (= n 0)
2822 interprogram-paste-function
2823 (funcall interprogram-paste-function))))
2824 (if interprogram-paste
2826 ;; Disable the interprogram cut function when we add the new
2827 ;; text to the kill ring, so Emacs doesn't try to own the
2828 ;; selection, with identical text.
2829 (let ((interprogram-cut-function nil))
2830 (if (listp interprogram-paste)
2831 (mapc 'kill-new (nreverse interprogram-paste))
2832 (kill-new interprogram-paste)))
2834 (or kill-ring (error "Kill ring is empty"))
2835 (let ((ARGth-kill-element
2836 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2840 (setq kill-ring-yank-pointer ARGth-kill-element)
2841 (when (and yank-pop-change-selection
2843 interprogram-cut-function)
2844 (funcall interprogram-cut-function (car ARGth-kill-element))))
2845 (car ARGth-kill-element)))))
2849 ;;;; Commands for manipulating the kill ring.
2851 (defcustom kill-read-only-ok nil
2852 "Non-nil means don't signal an error for killing read-only text."
2856 (put 'text-read-only 'error-conditions
2857 '(text-read-only buffer-read-only error))
2858 (put 'text-read-only 'error-message "Text is read-only")
2860 (defun kill-region (beg end &optional yank-handler)
2861 "Kill (\"cut\") text between point and mark.
2862 This deletes the text from the buffer and saves it in the kill ring.
2863 The command \\[yank] can retrieve it from there.
2864 \(If you want to save the region without killing it, use \\[kill-ring-save].)
2866 If you want to append the killed region to the last killed text,
2867 use \\[append-next-kill] before \\[kill-region].
2869 If the buffer is read-only, Emacs will beep and refrain from deleting
2870 the text, but put the text in the kill ring anyway. This means that
2871 you can use the killing commands to copy text from a read-only buffer.
2873 This is the primitive for programs to kill text (as opposed to deleting it).
2874 Supply two arguments, character positions indicating the stretch of text
2876 Any command that calls this function is a \"kill command\".
2877 If the previous command was also a kill command,
2878 the text killed this time appends to the text killed last time
2879 to make one entry in the kill ring.
2881 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2882 specifies the yank-handler text property to be set on the killed
2883 text. See `insert-for-yank'."
2884 ;; Pass point first, then mark, because the order matters
2885 ;; when calling kill-append.
2886 (interactive (list (point) (mark)))
2887 (unless (and beg end)
2888 (error "The mark is not set now, so there is no region"))
2890 (let ((string (filter-buffer-substring beg end t)))
2891 (when string ;STRING is nil if BEG = END
2892 ;; Add that string to the kill ring, one way or another.
2893 (if (eq last-command 'kill-region)
2894 (kill-append string (< end beg) yank-handler)
2895 (kill-new string nil yank-handler)))
2896 (when (or string (eq last-command 'kill-region))
2897 (setq this-command 'kill-region))
2899 ((buffer-read-only text-read-only)
2900 ;; The code above failed because the buffer, or some of the characters
2901 ;; in the region, are read-only.
2902 ;; We should beep, in case the user just isn't aware of this.
2903 ;; However, there's no harm in putting
2904 ;; the region's text in the kill ring, anyway.
2905 (copy-region-as-kill beg end)
2906 ;; Set this-command now, so it will be set even if we get an error.
2907 (setq this-command 'kill-region)
2908 ;; This should barf, if appropriate, and give us the correct error.
2909 (if kill-read-only-ok
2910 (progn (message "Read only text copied to kill ring") nil)
2911 ;; Signal an error if the buffer is read-only.
2912 (barf-if-buffer-read-only)
2913 ;; If the buffer isn't read-only, the text is.
2914 (signal 'text-read-only (list (current-buffer)))))))
2916 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2917 ;; to get two copies of the text when the user accidentally types M-w and
2918 ;; then corrects it with the intended C-w.
2919 (defun copy-region-as-kill (beg end)
2920 "Save the region as if killed, but don't kill it.
2921 In Transient Mark mode, deactivate the mark.
2922 If `interprogram-cut-function' is non-nil, also save the text for a window
2923 system cut and paste.
2925 This command's old key binding has been given to `kill-ring-save'."
2927 (if (eq last-command 'kill-region)
2928 (kill-append (filter-buffer-substring beg end) (< end beg))
2929 (kill-new (filter-buffer-substring beg end)))
2930 (setq deactivate-mark t)
2933 (defun kill-ring-save (beg end)
2934 "Save the region as if killed, but don't kill it.
2935 In Transient Mark mode, deactivate the mark.
2936 If `interprogram-cut-function' is non-nil, also save the text for a window
2937 system cut and paste.
2939 If you want to append the killed line to the last killed text,
2940 use \\[append-next-kill] before \\[kill-ring-save].
2942 This command is similar to `copy-region-as-kill', except that it gives
2943 visual feedback indicating the extent of the region being copied."
2945 (copy-region-as-kill beg end)
2946 ;; This use of interactive-p is correct
2947 ;; because the code it controls just gives the user visual feedback.
2949 (let ((other-end (if (= (point) beg) end beg))
2951 ;; Inhibit quitting so we can make a quit here
2952 ;; look like a C-g typed as a command.
2954 (if (pos-visible-in-window-p other-end (selected-window))
2955 ;; Swap point-and-mark quickly so as to show the region that
2956 ;; was selected. Don't do it if the region is highlighted.
2957 (unless (and (region-active-p)
2958 (face-background 'region))
2959 ;; Swap point and mark.
2960 (set-marker (mark-marker) (point) (current-buffer))
2961 (goto-char other-end)
2962 (sit-for blink-matching-delay)
2964 (set-marker (mark-marker) other-end (current-buffer))
2966 ;; If user quit, deactivate the mark
2967 ;; as C-g would as a command.
2968 (and quit-flag mark-active
2970 (let* ((killed-text (current-kill 0))
2971 (message-len (min (length killed-text) 40)))
2973 ;; Don't say "killed"; that is misleading.
2974 (message "Saved text until \"%s\""
2975 (substring killed-text (- message-len)))
2976 (message "Saved text from \"%s\""
2977 (substring killed-text 0 message-len))))))))
2979 (defun append-next-kill (&optional interactive)
2980 "Cause following command, if it kills, to append to previous kill.
2981 The argument is used for internal purposes; do not supply one."
2983 ;; We don't use (interactive-p), since that breaks kbd macros.
2986 (setq this-command 'kill-region)
2987 (message "If the next command is a kill, it will append"))
2988 (setq last-command 'kill-region)))
2992 ;; This is actually used in subr.el but defcustom does not work there.
2993 (defcustom yank-excluded-properties
2994 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2995 yank-handler follow-link fontified)
2996 "Text properties to discard when yanking.
2997 The value should be a list of text properties to discard or t,
2998 which means to discard all text properties."
2999 :type '(choice (const :tag "All" t) (repeat symbol))
3003 (defvar yank-window-start nil)
3004 (defvar yank-undo-function nil
3005 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3006 Function is called with two parameters, START and END corresponding to
3007 the value of the mark and point; it is guaranteed that START <= END.
3008 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3010 (defun yank-pop (&optional arg)
3011 "Replace just-yanked stretch of killed text with a different stretch.
3012 This command is allowed only immediately after a `yank' or a `yank-pop'.
3013 At such a time, the region contains a stretch of reinserted
3014 previously-killed text. `yank-pop' deletes that text and inserts in its
3015 place a different stretch of killed text.
3017 With no argument, the previous kill is inserted.
3018 With argument N, insert the Nth previous kill.
3019 If N is negative, this is a more recent kill.
3021 The sequence of kills wraps around, so that after the oldest one
3022 comes the newest one.
3024 When this command inserts killed text into the buffer, it honors
3025 `yank-excluded-properties' and `yank-handler' as described in the
3026 doc string for `insert-for-yank-1', which see."
3028 (if (not (eq last-command 'yank))
3029 (error "Previous command was not a yank"))
3030 (setq this-command 'yank)
3031 (unless arg (setq arg 1))
3032 (let ((inhibit-read-only t)
3033 (before (< (point) (mark t))))
3035 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3036 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
3037 (setq yank-undo-function nil)
3038 (set-marker (mark-marker) (point) (current-buffer))
3039 (insert-for-yank (current-kill arg))
3040 ;; Set the window start back where it was in the yank command,
3042 (set-window-start (selected-window) yank-window-start t)
3044 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3045 ;; It is cleaner to avoid activation, even though the command
3046 ;; loop would deactivate the mark because we inserted text.
3047 (goto-char (prog1 (mark t)
3048 (set-marker (mark-marker) (point) (current-buffer))))))
3051 (defun yank (&optional arg)
3052 "Reinsert (\"paste\") the last stretch of killed text.
3053 More precisely, reinsert the stretch of killed text most recently
3054 killed OR yanked. Put point at end, and set mark at beginning.
3055 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
3056 With argument N, reinsert the Nth most recently killed stretch of killed
3059 When this command inserts killed text into the buffer, it honors
3060 `yank-excluded-properties' and `yank-handler' as described in the
3061 doc string for `insert-for-yank-1', which see.
3063 See also the command `yank-pop' (\\[yank-pop])."
3065 (setq yank-window-start (window-start))
3066 ;; If we don't get all the way thru, make last-command indicate that
3067 ;; for the following command.
3068 (setq this-command t)
3070 (insert-for-yank (current-kill (cond
3075 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3076 ;; It is cleaner to avoid activation, even though the command
3077 ;; loop would deactivate the mark because we inserted text.
3078 (goto-char (prog1 (mark t)
3079 (set-marker (mark-marker) (point) (current-buffer)))))
3080 ;; If we do get all the way thru, make this-command indicate that.
3081 (if (eq this-command t)
3082 (setq this-command 'yank))
3085 (defun rotate-yank-pointer (arg)
3086 "Rotate the yanking point in the kill ring.
3087 With ARG, rotate that many kills forward (or backward, if negative)."
3091 ;; Some kill commands.
3093 ;; Internal subroutine of delete-char
3094 (defun kill-forward-chars (arg)
3095 (if (listp arg) (setq arg (car arg)))
3096 (if (eq arg '-) (setq arg -1))
3097 (kill-region (point) (forward-point arg)))
3099 ;; Internal subroutine of backward-delete-char
3100 (defun kill-backward-chars (arg)
3101 (if (listp arg) (setq arg (car arg)))
3102 (if (eq arg '-) (setq arg -1))
3103 (kill-region (point) (forward-point (- arg))))
3105 (defcustom backward-delete-char-untabify-method 'untabify
3106 "The method for untabifying when deleting backward.
3107 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3108 `hungry' -- delete all whitespace, both tabs and spaces;
3109 `all' -- delete all whitespace, including tabs, spaces and newlines;
3110 nil -- just delete one character."
3111 :type '(choice (const untabify) (const hungry) (const all) (const nil))
3115 (defun backward-delete-char-untabify (arg &optional killp)
3116 "Delete characters backward, changing tabs into spaces.
3117 The exact behavior depends on `backward-delete-char-untabify-method'.
3118 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3119 Interactively, ARG is the prefix arg (default 1)
3120 and KILLP is t if a prefix arg was specified."
3121 (interactive "*p\nP")
3122 (when (eq backward-delete-char-untabify-method 'untabify)
3125 (while (and (> count 0) (not (bobp)))
3126 (if (= (preceding-char) ?\t)
3127 (let ((col (current-column)))
3129 (setq col (- col (current-column)))
3130 (insert-char ?\s col)
3133 (setq count (1- count))))))
3134 (delete-backward-char
3135 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3136 ((eq backward-delete-char-untabify-method 'all)
3139 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
3141 (+ arg (if (zerop wh) 0 (1- wh))))
3145 (defun zap-to-char (arg char)
3146 "Kill up to and including ARGth occurrence of CHAR.
3147 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3148 Goes backward if ARG is negative; error if CHAR not found."
3149 (interactive "p\ncZap to char: ")
3150 (if (char-table-p translation-table-for-input)
3151 (setq char (or (aref translation-table-for-input char) char)))
3152 (kill-region (point) (progn
3153 (search-forward (char-to-string char) nil nil arg)
3154 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3157 ;; kill-line and its subroutines.
3159 (defcustom kill-whole-line nil
3160 "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
3164 (defun kill-line (&optional arg)
3165 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3166 With prefix argument ARG, kill that many lines from point.
3167 Negative arguments kill lines backward.
3168 With zero argument, kills the text before point on the current line.
3170 When calling from a program, nil means \"no arg\",
3171 a number counts as a prefix arg.
3173 To kill a whole line, when point is not at the beginning, type \
3174 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3176 If `kill-whole-line' is non-nil, then this command kills the whole line
3177 including its terminating newline, when used at the beginning of a line
3178 with no argument. As a consequence, you can always kill a whole line
3179 by typing \\[move-beginning-of-line] \\[kill-line].
3181 If you want to append the killed line to the last killed text,
3182 use \\[append-next-kill] before \\[kill-line].
3184 If the buffer is read-only, Emacs will beep and refrain from deleting
3185 the line, but put the line in the kill ring anyway. This means that
3186 you can use this command to copy text from a read-only buffer.
3187 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3190 (kill-region (point)
3191 ;; It is better to move point to the other end of the kill
3192 ;; before killing. That way, in a read-only buffer, point
3193 ;; moves across the text that is copied to the kill ring.
3194 ;; The choice has no effect on undo now that undo records
3195 ;; the value of point from before the command was run.
3198 (forward-visible-line (prefix-numeric-value arg))
3200 (signal 'end-of-buffer nil))
3203 (end-of-visible-line) (point))))
3204 (if (or (save-excursion
3205 ;; If trailing whitespace is visible,
3206 ;; don't treat it as nothing.
3207 (unless show-trailing-whitespace
3208 (skip-chars-forward " \t" end))
3210 (and kill-whole-line (bolp)))
3211 (forward-visible-line 1)
3215 (defun kill-whole-line (&optional arg)
3217 With prefix ARG, kill that many lines starting from the current line.
3218 If ARG is negative, kill backward. Also kill the preceding newline.
3219 \(This is meant to make \\[repeat] work well with negative arguments.\)
3220 If ARG is zero, kill current line but exclude the trailing newline."
3222 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3223 (signal 'end-of-buffer nil))
3224 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3225 (signal 'beginning-of-buffer nil))
3226 (unless (eq last-command 'kill-region)
3228 (setq last-command 'kill-region))
3230 ;; We need to kill in two steps, because the previous command
3231 ;; could have been a kill command, in which case the text
3232 ;; before point needs to be prepended to the current kill
3233 ;; ring entry and the text after point appended. Also, we
3234 ;; need to use save-excursion to avoid copying the same text
3235 ;; twice to the kill ring in read-only buffers.
3237 (kill-region (point) (progn (forward-visible-line 0) (point))))
3238 (kill-region (point) (progn (end-of-visible-line) (point))))
3241 (kill-region (point) (progn (end-of-visible-line) (point))))
3242 (kill-region (point)
3243 (progn (forward-visible-line (1+ arg))
3244 (unless (bobp) (backward-char))
3248 (kill-region (point) (progn (forward-visible-line 0) (point))))
3249 (kill-region (point)
3250 (progn (forward-visible-line arg) (point))))))
3252 (defun forward-visible-line (arg)
3253 "Move forward by ARG lines, ignoring currently invisible newlines only.
3254 If ARG is negative, move backward -ARG lines.
3255 If ARG is zero, move to the beginning of the current line."
3260 (or (zerop (forward-line 1))
3261 (signal 'end-of-buffer nil))
3262 ;; If the newline we just skipped is invisible,
3265 (get-char-property (1- (point)) 'invisible)))
3266 (if (if (eq buffer-invisibility-spec t)
3268 (or (memq prop buffer-invisibility-spec)
3269 (assq prop buffer-invisibility-spec)))
3270 (setq arg (1+ arg))))
3271 (setq arg (1- arg)))
3272 ;; If invisible text follows, and it is a number of complete lines,
3274 (let ((opoint (point)))
3275 (while (and (not (eobp))
3277 (get-char-property (point) 'invisible)))
3278 (if (eq buffer-invisibility-spec t)
3280 (or (memq prop buffer-invisibility-spec)
3281 (assq prop buffer-invisibility-spec)))))
3283 (if (get-text-property (point) 'invisible)
3284 (or (next-single-property-change (point) 'invisible)
3286 (next-overlay-change (point)))))
3288 (goto-char opoint))))
3290 (while (or first (<= arg 0))
3293 (or (zerop (forward-line -1))
3294 (signal 'beginning-of-buffer nil)))
3295 ;; If the newline we just moved to is invisible,
3299 (get-char-property (1- (point)) 'invisible)))
3300 (unless (if (eq buffer-invisibility-spec t)
3302 (or (memq prop buffer-invisibility-spec)
3303 (assq prop buffer-invisibility-spec)))
3304 (setq arg (1+ arg)))))
3306 ;; If invisible text follows, and it is a number of complete lines,
3308 (let ((opoint (point)))
3309 (while (and (not (bobp))
3311 (get-char-property (1- (point)) 'invisible)))
3312 (if (eq buffer-invisibility-spec t)
3314 (or (memq prop buffer-invisibility-spec)
3315 (assq prop buffer-invisibility-spec)))))
3317 (if (get-text-property (1- (point)) 'invisible)
3318 (or (previous-single-property-change (point) 'invisible)
3320 (previous-overlay-change (point)))))
3322 (goto-char opoint)))))
3323 ((beginning-of-buffer end-of-buffer)
3326 (defun end-of-visible-line ()
3327 "Move to end of current visible line."
3329 ;; If the following character is currently invisible,
3330 ;; skip all characters with that same `invisible' property value,
3331 ;; then find the next newline.
3332 (while (and (not (eobp))
3334 (skip-chars-forward "^\n")
3336 (get-char-property (point) 'invisible)))
3337 (if (eq buffer-invisibility-spec t)
3339 (or (memq prop buffer-invisibility-spec)
3340 (assq prop buffer-invisibility-spec))))))
3341 (skip-chars-forward "^\n")
3342 (if (get-text-property (point) 'invisible)
3343 (goto-char (next-single-property-change (point) 'invisible))
3344 (goto-char (next-overlay-change (point))))
3347 (defun insert-buffer (buffer)
3348 "Insert after point the contents of BUFFER.
3349 Puts mark after the inserted text.
3350 BUFFER may be a buffer or a buffer name.
3352 This function is meant for the user to run interactively.
3353 Don't call it from programs: use `insert-buffer-substring' instead!"
3357 (barf-if-buffer-read-only)
3358 (read-buffer "Insert buffer: "
3359 (if (eq (selected-window) (next-window (selected-window)))
3360 (other-buffer (current-buffer))
3361 (window-buffer (next-window (selected-window))))
3365 (insert-buffer-substring (get-buffer buffer))
3369 (defun append-to-buffer (buffer start end)
3370 "Append to specified buffer the text of the region.
3371 It is inserted into that buffer before its point.
3373 When calling from a program, give three arguments:
3374 BUFFER (or buffer name), START and END.
3375 START and END specify the portion of the current buffer to be copied."
3377 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3378 (region-beginning) (region-end)))
3379 (let ((oldbuf (current-buffer)))
3381 (let* ((append-to (get-buffer-create buffer))
3382 (windows (get-buffer-window-list append-to t t))
3384 (set-buffer append-to)
3385 (setq point (point))
3386 (barf-if-buffer-read-only)
3387 (insert-buffer-substring oldbuf start end)
3388 (dolist (window windows)
3389 (when (= (window-point window) point)
3390 (set-window-point window (point))))))))
3392 (defun prepend-to-buffer (buffer start end)
3393 "Prepend to specified buffer the text of the region.
3394 It is inserted into that buffer after its point.
3396 When calling from a program, give three arguments:
3397 BUFFER (or buffer name), START and END.
3398 START and END specify the portion of the current buffer to be copied."
3399 (interactive "BPrepend to buffer: \nr")
3400 (let ((oldbuf (current-buffer)))
3402 (set-buffer (get-buffer-create buffer))
3403 (barf-if-buffer-read-only)
3405 (insert-buffer-substring oldbuf start end)))))
3407 (defun copy-to-buffer (buffer start end)
3408 "Copy to specified buffer the text of the region.
3409 It is inserted into that buffer, replacing existing text there.
3411 When calling from a program, give three arguments:
3412 BUFFER (or buffer name), START and END.
3413 START and END specify the portion of the current buffer to be copied."
3414 (interactive "BCopy to buffer: \nr")
3415 (let ((oldbuf (current-buffer)))
3416 (with-current-buffer (get-buffer-create buffer)
3417 (barf-if-buffer-read-only)
3420 (insert-buffer-substring oldbuf start end)))))
3422 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3423 (put 'mark-inactive 'error-message "The mark is not active now")
3425 (defvar activate-mark-hook nil
3426 "Hook run when the mark becomes active.
3427 It is also run at the end of a command, if the mark is active and
3428 it is possible that the region may have changed.")
3430 (defvar deactivate-mark-hook nil
3431 "Hook run when the mark becomes inactive.")
3433 (defun mark (&optional force)
3434 "Return this buffer's mark value as integer, or nil if never set.
3436 In Transient Mark mode, this function signals an error if
3437 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3438 or the argument FORCE is non-nil, it disregards whether the mark
3439 is active, and returns an integer or nil in the usual way.
3441 If you are using this in an editing command, you are most likely making
3442 a mistake; see the documentation of `set-mark'."
3443 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3444 (marker-position (mark-marker))
3445 (signal 'mark-inactive nil)))
3447 ;; Many places set mark-active directly, and several of them failed to also
3448 ;; run deactivate-mark-hook. This shorthand should simplify.
3449 (defsubst deactivate-mark ()
3450 "Deactivate the mark by setting `mark-active' to nil.
3451 \(That makes a difference only in Transient Mark mode.)
3452 Also runs the hook `deactivate-mark-hook'."
3453 (when transient-mark-mode
3454 (if (or (eq transient-mark-mode 'lambda)
3455 (and (eq (car-safe transient-mark-mode) 'only)
3456 (null (cdr transient-mark-mode))))
3457 (setq transient-mark-mode nil)
3458 (if (eq (car-safe transient-mark-mode) 'only)
3459 (setq transient-mark-mode (cdr transient-mark-mode)))
3460 (setq mark-active nil)
3461 (run-hooks 'deactivate-mark-hook))))
3463 (defun activate-mark ()
3464 "Activate the mark."
3466 (setq mark-active t)
3467 (unless transient-mark-mode
3468 (setq transient-mark-mode 'lambda))))
3470 (defcustom select-active-regions nil
3471 "If non-nil, an active region automatically becomes the window selection."
3476 (defun set-mark (pos)
3477 "Set this buffer's mark to POS. Don't use this function!
3478 That is to say, don't use this function unless you want
3479 the user to see that the mark has moved, and you want the previous
3480 mark position to be lost.
3482 Normally, when a new mark is set, the old one should go on the stack.
3483 This is why most applications should use `push-mark', not `set-mark'.
3485 Novice Emacs Lisp programmers often try to use the mark for the wrong
3486 purposes. The mark saves a location for the user's convenience.
3487 Most editing commands should not alter the mark.
3488 To remember a location for internal use in the Lisp program,
3489 store it in a Lisp variable. Example:
3491 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3495 (setq mark-active t)
3496 (run-hooks 'activate-mark-hook)
3497 (and select-active-regions
3499 nil (buffer-substring (region-beginning) (region-end))))
3500 (set-marker (mark-marker) pos (current-buffer)))
3501 ;; Normally we never clear mark-active except in Transient Mark mode.
3502 ;; But when we actually clear out the mark value too,
3503 ;; we must clear mark-active in any mode.
3504 (setq mark-active nil)
3505 (run-hooks 'deactivate-mark-hook)
3506 (set-marker (mark-marker) nil)))
3508 (defcustom use-empty-active-region nil
3509 "Whether \"region-aware\" commands should act on empty regions.
3510 If nil, region-aware commands treat empty regions as inactive.
3511 If non-nil, region-aware commands treat the region as active as
3512 long as the mark is active, even if the region is empty.
3514 Region-aware commands are those that act on the region if it is
3515 active and Transient Mark mode is enabled, and on the text near
3519 :group 'editing-basics)
3521 (defun use-region-p ()
3522 "Return t if the region is active and it is appropriate to act on it.
3523 This is used by commands that act specially on the region under
3524 Transient Mark mode. It returns t if and only if Transient Mark
3525 mode is enabled, the mark is active, and the region is non-empty.
3526 If `use-empty-active-region' is non-nil, it returns t even if the
3529 For some commands, it may be appropriate to disregard the value
3530 of `use-empty-active-region'; in that case, use `region-active-p'."
3531 (and (region-active-p)
3532 (or use-empty-active-region (> (region-end) (region-beginning)))))
3534 (defun region-active-p ()
3535 "Return t if Transient Mark mode is enabled and the mark is active.
3537 Most commands that act on the region if it is active and
3538 Transient Mark mode is enabled, and on the text near point
3539 otherwise, should use `use-region-p' instead. That function
3540 checks the value of `use-empty-active-region' as well."
3541 (and transient-mark-mode mark-active))
3543 (defvar mark-ring nil
3544 "The list of former marks of the current buffer, most recent first.")
3545 (make-variable-buffer-local 'mark-ring)
3546 (put 'mark-ring 'permanent-local t)
3548 (defcustom mark-ring-max 16
3549 "Maximum size of mark ring. Start discarding off end if gets this big."
3551 :group 'editing-basics)
3553 (defvar global-mark-ring nil
3554 "The list of saved global marks, most recent first.")
3556 (defcustom global-mark-ring-max 16
3557 "Maximum size of global mark ring. \
3558 Start discarding off end if gets this big."
3560 :group 'editing-basics)
3562 (defun pop-to-mark-command ()
3563 "Jump to mark, and pop a new position for mark off the ring.
3564 \(Does not affect global mark ring\)."
3567 (error "No mark set in this buffer")
3568 (if (= (point) (mark t))
3569 (message "Mark popped"))
3570 (goto-char (mark t))
3573 (defun push-mark-command (arg &optional nomsg)
3574 "Set mark at where point is.
3575 If no prefix ARG and mark is already set there, just activate it.
3576 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3578 (let ((mark (marker-position (mark-marker))))
3579 (if (or arg (null mark) (/= mark (point)))
3580 (push-mark nil nomsg t)
3581 (setq mark-active t)
3582 (run-hooks 'activate-mark-hook)
3584 (message "Mark activated")))))
3586 (defcustom set-mark-command-repeat-pop nil
3587 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3588 That means that C-u \\[set-mark-command] \\[set-mark-command]
3589 will pop the mark twice, and
3590 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3591 will pop the mark three times.
3593 A value of nil means \\[set-mark-command]'s behavior does not change
3594 after C-u \\[set-mark-command]."
3596 :group 'editing-basics)
3598 (defcustom set-mark-default-inactive nil
3599 "If non-nil, setting the mark does not activate it.
3600 This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
3601 behave the same whether or not `transient-mark-mode' is enabled.")
3603 (defun set-mark-command (arg)
3604 "Set the mark where point is, or jump to the mark.
3605 Setting the mark also alters the region, which is the text
3606 between point and mark; this is the closest equivalent in
3607 Emacs to what some editors call the \"selection\".
3609 With no prefix argument, set the mark at point, and push the
3610 old mark position on local mark ring. Also push the old mark on
3611 global mark ring, if the previous mark was set in another buffer.
3613 When Transient Mark Mode is off, immediately repeating this
3614 command activates `transient-mark-mode' temporarily.
3616 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3617 jump to the mark, and set the mark from
3618 position popped off the local mark ring \(this does not affect the global
3619 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3620 mark ring \(see `pop-global-mark'\).
3622 If `set-mark-command-repeat-pop' is non-nil, repeating
3623 the \\[set-mark-command] command with no prefix argument pops the next position
3624 off the local (or global) mark ring and jumps there.
3626 With \\[universal-argument] \\[universal-argument] as prefix
3627 argument, unconditionally set mark where point is, even if
3628 `set-mark-command-repeat-pop' is non-nil.
3630 Novice Emacs Lisp programmers often try to use the mark for the wrong
3631 purposes. See the documentation of `set-mark' for more information."
3633 (cond ((eq transient-mark-mode 'lambda)
3634 (setq transient-mark-mode nil))
3635 ((eq (car-safe transient-mark-mode) 'only)
3638 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3639 (push-mark-command nil))
3640 ((not (eq this-command 'set-mark-command))
3642 (pop-to-mark-command)
3643 (push-mark-command t)))
3644 ((and set-mark-command-repeat-pop
3645 (eq last-command 'pop-to-mark-command))
3646 (setq this-command 'pop-to-mark-command)
3647 (pop-to-mark-command))
3648 ((and set-mark-command-repeat-pop
3649 (eq last-command 'pop-global-mark)
3651 (setq this-command 'pop-global-mark)
3654 (setq this-command 'pop-to-mark-command)
3655 (pop-to-mark-command))
3656 ((eq last-command 'set-mark-command)
3657 (if (region-active-p)
3660 (message "Mark deactivated"))
3662 (message "Mark activated")))
3664 (push-mark-command nil)
3665 (if set-mark-default-inactive (deactivate-mark)))))
3667 (defun push-mark (&optional location nomsg activate)
3668 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3669 If the last global mark pushed was not in the current buffer,
3670 also push LOCATION on the global mark ring.
3671 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3673 Novice Emacs Lisp programmers often try to use the mark for the wrong
3674 purposes. See the documentation of `set-mark' for more information.
3676 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
3677 (unless (null (mark t))
3678 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3679 (when (> (length mark-ring) mark-ring-max)
3680 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3681 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3682 (set-marker (mark-marker) (or location (point)) (current-buffer))
3683 ;; Now push the mark on the global mark ring.
3684 (if (and global-mark-ring
3685 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3686 ;; The last global mark pushed was in this same buffer.
3687 ;; Don't push another one.
3689 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3690 (when (> (length global-mark-ring) global-mark-ring-max)
3691 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3692 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3693 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3694 (message "Mark set"))
3695 (if (or activate (not transient-mark-mode))
3696 (set-mark (mark t)))
3700 "Pop off mark ring into the buffer's actual mark.
3701 Does not set point. Does nothing if mark ring is empty."
3703 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3704 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3705 (move-marker (car mark-ring) nil)
3706 (if (null (mark t)) (ding))
3707 (setq mark-ring (cdr mark-ring)))
3710 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3711 (defun exchange-point-and-mark (&optional arg)
3712 "Put the mark where point is now, and point where the mark is now.
3713 This command works even when the mark is not active,
3714 and it reactivates the mark.
3716 If Transient Mark mode is on, a prefix ARG deactivates the mark
3717 if it is active, and otherwise avoids reactivating it. If
3718 Transient Mark mode is off, a prefix ARG enables Transient Mark
3721 (let ((omark (mark t))
3722 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
3724 (error "No mark set in this buffer"))
3728 (if set-mark-default-inactive (deactivate-mark))
3729 (cond (temp-highlight
3730 (setq transient-mark-mode (cons 'only transient-mark-mode)))
3731 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
3732 (not (or arg (region-active-p))))
3734 (t (activate-mark)))
3737 (defun handle-shift-selection (&optional deactivate)
3738 "Check for shift translation, and operate on the mark accordingly.
3739 This is called whenever a command with a `^' character in its
3740 `interactive' spec is invoked while `shift-select-mode' is
3743 If the command was invoked through shift-translation, set the
3744 mark and activate the region temporarily, unless it was already
3745 set in this way. If the command was invoked without
3746 shift-translation and a region is temporarily active, deactivate
3749 With optional arg DEACTIVATE, only perform region deactivation."
3750 (cond ((and this-command-keys-shift-translated
3752 (unless (and mark-active
3753 (eq (car-safe transient-mark-mode) 'only))
3754 (setq transient-mark-mode
3756 (unless (eq transient-mark-mode 'lambda)
3757 transient-mark-mode)))
3758 (push-mark nil nil t)))
3759 ((eq (car-safe transient-mark-mode) 'only)
3760 (setq transient-mark-mode (cdr transient-mark-mode))
3761 (deactivate-mark))))
3763 (define-minor-mode transient-mark-mode
3764 "Toggle Transient Mark mode.
3765 With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
3767 In Transient Mark mode, when the mark is active, the region is highlighted.
3768 Changing the buffer \"deactivates\" the mark.
3769 So do certain other operations that set the mark
3770 but whose main purpose is something else--for example,
3771 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3773 You can also deactivate the mark by typing \\[keyboard-quit] or
3774 \\[keyboard-escape-quit].
3776 Many commands change their behavior when Transient Mark mode is in effect
3777 and the mark is active, by acting on the region instead of their usual
3778 default part of the buffer's text. Examples of such commands include
3779 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3780 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3781 Invoke \\[apropos-documentation] and type \"transient\" or
3782 \"mark.*active\" at the prompt, to see the documentation of
3783 commands which are sensitive to the Transient Mark mode."
3785 :init-value (not noninteractive)
3786 :group 'editing-basics)
3788 ;; The variable transient-mark-mode is ugly: it can take on special
3789 ;; values. Document these here.
3790 (defvar transient-mark-mode t
3791 "*Non-nil if Transient Mark mode is enabled.
3792 See the command `transient-mark-mode' for a description of this minor mode.
3794 Non-nil also enables highlighting of the region whenever the mark is active.
3795 The variable `highlight-nonselected-windows' controls whether to highlight
3796 all windows or just the selected window.
3798 If the value is `lambda', that enables Transient Mark mode temporarily.
3799 After any subsequent action that would normally deactivate the mark
3800 \(such as buffer modification), Transient Mark mode is turned off.
3802 If the value is (only . OLDVAL), that enables Transient Mark mode
3803 temporarily. After any subsequent point motion command that is not
3804 shift-translated, or any other action that would normally deactivate
3805 the mark (such as buffer modification), the value of
3806 `transient-mark-mode' is set to OLDVAL.")
3808 (defvar widen-automatically t
3809 "Non-nil means it is ok for commands to call `widen' when they want to.
3810 Some commands will do this in order to go to positions outside
3811 the current accessible part of the buffer.
3813 If `widen-automatically' is nil, these commands will do something else
3814 as a fallback, and won't change the buffer bounds.")
3816 (defun pop-global-mark ()
3817 "Pop off global mark ring and jump to the top location."
3819 ;; Pop entries which refer to non-existent buffers.
3820 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3821 (setq global-mark-ring (cdr global-mark-ring)))
3822 (or global-mark-ring
3823 (error "No global mark set"))
3824 (let* ((marker (car global-mark-ring))
3825 (buffer (marker-buffer marker))
3826 (position (marker-position marker)))
3827 (setq global-mark-ring (nconc (cdr global-mark-ring)
3828 (list (car global-mark-ring))))
3830 (or (and (>= position (point-min))
3831 (<= position (point-max)))
3832 (if widen-automatically
3834 (error "Global mark position is outside accessible part of buffer")))
3835 (goto-char position)
3836 (switch-to-buffer buffer)))
3838 (defcustom next-line-add-newlines nil
3839 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3842 :group 'editing-basics)
3844 (defun next-line (&optional arg try-vscroll)
3845 "Move cursor vertically down ARG lines.
3846 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3847 If there is no character in the target line exactly under the current column,
3848 the cursor is positioned after the character in that line which spans this
3849 column, or at the end of the line if it is not long enough.
3850 If there is no line in the buffer after this one, behavior depends on the
3851 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3852 to create a line, and moves the cursor to that line. Otherwise it moves the
3853 cursor to the end of the buffer.
3855 If the variable `line-move-visual' is non-nil, this command moves
3856 by display lines. Otherwise, it moves by buffer lines, without
3857 taking variable-width characters or continued lines into account.
3859 The command \\[set-goal-column] can be used to create
3860 a semipermanent goal column for this command.
3861 Then instead of trying to move exactly vertically (or as close as possible),
3862 this command moves to the specified goal column (or as close as possible).
3863 The goal column is stored in the variable `goal-column', which is nil
3864 when there is no goal column.
3866 If you are thinking of using this in a Lisp program, consider
3867 using `forward-line' instead. It is usually easier to use
3868 and more reliable (no dependence on goal column, etc.)."
3869 (interactive "^p\np")
3870 (or arg (setq arg 1))
3871 (if (and next-line-add-newlines (= arg 1))
3872 (if (save-excursion (end-of-line) (eobp))
3873 ;; When adding a newline, don't expand an abbrev.
3874 (let ((abbrev-mode nil))
3876 (insert (if use-hard-newlines hard-newline "\n")))
3877 (line-move arg nil nil try-vscroll))
3880 (line-move arg nil nil try-vscroll)
3881 ((beginning-of-buffer end-of-buffer) (ding)))
3882 (line-move arg nil nil try-vscroll)))
3885 (defun previous-line (&optional arg try-vscroll)
3886 "Move cursor vertically up ARG lines.
3887 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3888 If there is no character in the target line exactly over the current column,
3889 the cursor is positioned after the character in that line which spans this
3890 column, or at the end of the line if it is not long enough.
3892 If the variable `line-move-visual' is non-nil, this command moves
3893 by display lines. Otherwise, it moves by buffer lines, without
3894 taking variable-width characters or continued lines into account.
3896 The command \\[set-goal-column] can be used to create
3897 a semipermanent goal column for this command.
3898 Then instead of trying to move exactly vertically (or as close as possible),
3899 this command moves to the specified goal column (or as close as possible).
3900 The goal column is stored in the variable `goal-column', which is nil
3901 when there is no goal column.
3903 If you are thinking of using this in a Lisp program, consider using
3904 `forward-line' with a negative argument instead. It is usually easier
3905 to use and more reliable (no dependence on goal column, etc.)."
3906 (interactive "^p\np")
3907 (or arg (setq arg 1))
3910 (line-move (- arg) nil nil try-vscroll)
3911 ((beginning-of-buffer end-of-buffer) (ding)))
3912 (line-move (- arg) nil nil try-vscroll))
3915 (defcustom track-eol nil
3916 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
3917 This means moving to the end of each line moved onto.
3918 The beginning of a blank line does not count as the end of a line.
3919 This has no effect when `line-move-visual' is non-nil."
3921 :group 'editing-basics)
3923 (defcustom goal-column nil
3924 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3925 :type '(choice integer
3926 (const :tag "None" nil))
3927 :group 'editing-basics)
3928 (make-variable-buffer-local 'goal-column)
3930 (defvar temporary-goal-column 0
3931 "Current goal column for vertical motion.
3932 It is the column where point was at the start of the current run
3933 of vertical motion commands. It is a floating point number when
3934 moving by visual lines via `line-move-visual'; this is the
3935 x-position, in pixels, divided by the default column width. When
3936 the `track-eol' feature is doing its job, the value is
3937 `most-positive-fixnum'.")
3939 (defcustom line-move-ignore-invisible t
3940 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3941 Outline mode sets this."
3943 :group 'editing-basics)
3945 (defcustom line-move-visual t
3946 "When non-nil, `line-move' moves point by visual lines.
3947 This movement is based on where the cursor is displayed on the
3948 screen, instead of relying on buffer contents alone. It takes
3949 into account variable-width characters and line continuation."
3951 :group 'editing-basics)
3953 ;; Returns non-nil if partial move was done.
3954 (defun line-move-partial (arg noerror to-end)
3956 ;; Move backward (up).
3957 ;; If already vscrolled, reduce vscroll
3958 (let ((vs (window-vscroll nil t)))
3959 (when (> vs (frame-char-height))
3960 (set-window-vscroll nil (- vs (frame-char-height)) t)))
3962 ;; Move forward (down).
3963 (let* ((lh (window-line-height -1))
3969 (>= rbot (frame-char-height))
3970 (<= ypos (- (frame-char-height))))
3972 (let ((wend (pos-visible-in-window-p t nil t)))
3973 (setq rbot (nth 3 wend)
3974 vpos (nth 5 wend))))
3976 ;; If last line of window is fully visible, move forward.
3977 ((or (null rbot) (= rbot 0))
3979 ;; If cursor is not in the bottom scroll margin, move forward.
3982 (or (nth 1 (window-line-height))
3983 (let ((ppos (posn-at-point)))
3984 (cdr (or (posn-actual-col-row ppos)
3985 (posn-col-row ppos))))))
3986 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
3988 ;; When already vscrolled, we vscroll some more if we can,
3989 ;; or clear vscroll and move forward at end of tall image.
3990 ((> (setq vs (window-vscroll nil t)) 0)
3992 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
3993 ;; If cursor just entered the bottom scroll margin, move forward,
3994 ;; but also vscroll one line so redisplay wont recenter.
3996 (= py (min (- (window-text-height) scroll-margin 1)
3998 (set-window-vscroll nil (frame-char-height) t)
3999 (line-move-1 arg noerror to-end)
4001 ;; If there are lines above the last line, scroll-up one line.
4005 ;; Finally, start vscroll.
4007 (set-window-vscroll nil (frame-char-height) t)))))))
4010 ;; This is like line-move-1 except that it also performs
4011 ;; vertical scrolling of tall images if appropriate.
4012 ;; That is not really a clean thing to do, since it mixes
4013 ;; scrolling with cursor motion. But so far we don't have
4014 ;; a cleaner solution to the problem of making C-n do something
4015 ;; useful given a tall image.
4016 (defun line-move (arg &optional noerror to-end try-vscroll)
4017 (unless (and auto-window-vscroll try-vscroll
4018 ;; Only vscroll for single line moves
4020 ;; But don't vscroll in a keyboard macro.
4021 (not defining-kbd-macro)
4022 (not executing-kbd-macro)
4023 (line-move-partial arg noerror to-end))
4024 (set-window-vscroll nil 0 t)
4025 (if line-move-visual
4026 (line-move-visual arg noerror)
4027 (line-move-1 arg noerror to-end))))
4029 ;; Display-based alternative to line-move-1.
4030 ;; Arg says how many lines to move. The value is t if we can move the
4031 ;; specified number of lines.
4032 (defun line-move-visual (arg &optional noerror)
4033 (unless (and (floatp temporary-goal-column)
4034 (or (memq last-command '(next-line previous-line))
4035 ;; In case we're called from some other command.
4036 (eq last-command this-command)))
4037 (let ((x (car (nth 2 (posn-at-point)))))
4039 (setq temporary-goal-column (/ (float x) (frame-char-width))))))
4040 (or (= (vertical-motion
4041 (cons (or goal-column (truncate temporary-goal-column)) arg))
4044 (signal (if (< arg 0)
4045 'beginning-of-buffer
4049 ;; This is the guts of next-line and previous-line.
4050 ;; Arg says how many lines to move.
4051 ;; The value is t if we can move the specified number of lines.
4052 (defun line-move-1 (arg &optional noerror to-end)
4053 ;; Don't run any point-motion hooks, and disregard intangibility,
4054 ;; for intermediate positions.
4055 (let ((inhibit-point-motion-hooks t)
4058 (if (floatp temporary-goal-column)
4059 (setq temporary-goal-column (truncate temporary-goal-column)))
4062 (if (not (memq last-command '(next-line previous-line)))
4063 (setq temporary-goal-column
4064 (if (and track-eol (eolp)
4065 ;; Don't count beg of empty line as end of line
4066 ;; unless we just did explicit end-of-line.
4067 (or (not (bolp)) (eq last-command 'move-end-of-line)))
4068 most-positive-fixnum
4071 (if (not (or (integerp selective-display)
4072 line-move-ignore-invisible))
4073 ;; Use just newline characters.
4074 ;; Set ARG to 0 if we move as many lines as requested.
4076 (progn (if (> arg 1) (forward-line (1- arg)))
4077 ;; This way of moving forward ARG lines
4078 ;; verifies that we have a newline after the last one.
4079 ;; It doesn't get confused by intangible text.
4081 (if (zerop (forward-line 1))
4083 (and (zerop (forward-line arg))
4087 (signal (if (< arg 0)
4088 'beginning-of-buffer
4091 ;; Move by arg lines, but ignore invisible ones.
4093 (while (and (> arg 0) (not done))
4094 ;; If the following character is currently invisible,
4095 ;; skip all characters with that same `invisible' property value.
4096 (while (and (not (eobp)) (invisible-p (point)))
4097 (goto-char (next-char-property-change (point))))
4099 ;; We don't use `end-of-line', since we want to escape
4100 ;; from field boundaries ocurring exactly at point.
4101 (goto-char (constrain-to-field
4102 (let ((inhibit-field-text-motion t))
4103 (line-end-position))
4105 'inhibit-line-move-field-capture))
4106 ;; If there's no invisibility here, move over the newline.
4110 (signal 'end-of-buffer nil)
4112 ((and (> arg 1) ;; Use vertical-motion for last move
4113 (not (integerp selective-display))
4114 (not (invisible-p (point))))
4115 ;; We avoid vertical-motion when possible
4116 ;; because that has to fontify.
4118 ;; Otherwise move a more sophisticated way.
4119 ((zerop (vertical-motion 1))
4121 (signal 'end-of-buffer nil)
4124 (setq arg (1- arg))))
4125 ;; The logic of this is the same as the loop above,
4126 ;; it just goes in the other direction.
4127 (while (and (< arg 0) (not done))
4128 ;; For completely consistency with the forward-motion
4129 ;; case, we should call beginning-of-line here.
4130 ;; However, if point is inside a field and on a
4131 ;; continued line, the call to (vertical-motion -1)
4132 ;; below won't move us back far enough; then we return
4133 ;; to the same column in line-move-finish, and point
4134 ;; gets stuck -- cyd
4139 (signal 'beginning-of-buffer nil)
4141 ((and (< arg -1) ;; Use vertical-motion for last move
4142 (not (integerp selective-display))
4143 (not (invisible-p (1- (point)))))
4145 ((zerop (vertical-motion -1))
4147 (signal 'beginning-of-buffer nil)
4151 (while (and ;; Don't move over previous invis lines
4152 ;; if our target is the middle of this line.
4153 (or (zerop (or goal-column temporary-goal-column))
4155 (not (bobp)) (invisible-p (1- (point))))
4156 (goto-char (previous-char-property-change (point))))))))
4157 ;; This is the value the function returns.
4161 ;; If we did not move down as far as desired, at least go
4162 ;; to end of line. Be sure to call point-entered and
4163 ;; point-left-hooks.
4164 (let* ((npoint (prog1 (line-end-position)
4165 (goto-char opoint)))
4166 (inhibit-point-motion-hooks nil))
4167 (goto-char npoint)))
4169 ;; If we did not move up as far as desired,
4170 ;; at least go to beginning of line.
4171 (let* ((npoint (prog1 (line-beginning-position)
4172 (goto-char opoint)))
4173 (inhibit-point-motion-hooks nil))
4174 (goto-char npoint)))
4176 (line-move-finish (or goal-column temporary-goal-column)
4177 opoint (> orig-arg 0)))))))
4179 (defun line-move-finish (column opoint forward)
4182 ;; Set REPEAT to t to repeat the whole thing.
4187 (line-beg (save-excursion (beginning-of-line) (point)))
4189 ;; Compute the end of the line
4190 ;; ignoring effectively invisible newlines.
4192 ;; Like end-of-line but ignores fields.
4193 (skip-chars-forward "^\n")
4194 (while (and (not (eobp)) (invisible-p (point)))
4195 (goto-char (next-char-property-change (point)))
4196 (skip-chars-forward "^\n"))
4199 ;; Move to the desired column.
4200 (line-move-to-column column)
4202 ;; Corner case: suppose we start out in a field boundary in
4203 ;; the middle of a continued line. When we get to
4204 ;; line-move-finish, point is at the start of a new *screen*
4205 ;; line but the same text line; then line-move-to-column would
4206 ;; move us backwards. Test using C-n with point on the "x" in
4207 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4214 ;; Process intangibility within a line.
4215 ;; With inhibit-point-motion-hooks bound to nil, a call to
4216 ;; goto-char moves point past intangible text.
4218 ;; However, inhibit-point-motion-hooks controls both the
4219 ;; intangibility and the point-entered/point-left hooks. The
4220 ;; following hack avoids calling the point-* hooks
4221 ;; unnecessarily. Note that we move *forward* past intangible
4222 ;; text when the initial and final points are the same.
4224 (let ((inhibit-point-motion-hooks nil))
4227 ;; If intangibility moves us to a different (later) place
4228 ;; in the same line, use that as the destination.
4229 (if (<= (point) line-end)
4231 ;; If that position is "too late",
4232 ;; try the previous allowable position.
4236 ;; If going forward, don't accept the previous
4237 ;; allowable position if it is before the target line.
4238 (< line-beg (point))
4239 ;; If going backward, don't accept the previous
4240 ;; allowable position if it is still after the target line.
4241 (<= (point) line-end))
4243 ;; As a last resort, use the end of the line.
4244 (setq new line-end))))
4246 ;; Now move to the updated destination, processing fields
4247 ;; as well as intangibility.
4249 (let ((inhibit-point-motion-hooks nil))
4251 ;; Ignore field boundaries if the initial and final
4252 ;; positions have the same `field' property, even if the
4253 ;; fields are non-contiguous. This seems to be "nicer"
4254 ;; behavior in many situations.
4255 (if (eq (get-char-property new 'field)
4256 (get-char-property opoint 'field))
4258 (constrain-to-field new opoint t t
4259 'inhibit-line-move-field-capture))))
4261 ;; If all this moved us to a different line,
4262 ;; retry everything within that new line.
4263 (when (or (< (point) line-beg) (> (point) line-end))
4264 ;; Repeat the intangibility and field processing.
4265 (setq repeat t))))))
4267 (defun line-move-to-column (col)
4268 "Try to find column COL, considering invisibility.
4269 This function works only in certain cases,
4270 because what we really need is for `move-to-column'
4271 and `current-column' to be able to ignore invisible text."
4274 (move-to-column col))
4276 (when (and line-move-ignore-invisible
4277 (not (bolp)) (invisible-p (1- (point))))
4278 (let ((normal-location (point))
4279 (normal-column (current-column)))
4280 ;; If the following character is currently invisible,
4281 ;; skip all characters with that same `invisible' property value.
4282 (while (and (not (eobp))
4283 (invisible-p (point)))
4284 (goto-char (next-char-property-change (point))))
4285 ;; Have we advanced to a larger column position?
4286 (if (> (current-column) normal-column)
4287 ;; We have made some progress towards the desired column.
4288 ;; See if we can make any further progress.
4289 (line-move-to-column (+ (current-column) (- col normal-column)))
4290 ;; Otherwise, go to the place we originally found
4291 ;; and move back over invisible text.
4292 ;; that will get us to the same place on the screen
4293 ;; but with a more reasonable buffer position.
4294 (goto-char normal-location)
4295 (let ((line-beg (save-excursion (beginning-of-line) (point))))
4296 (while (and (not (bolp)) (invisible-p (1- (point))))
4297 (goto-char (previous-char-property-change (point) line-beg))))))))
4299 (defun move-end-of-line (arg)
4300 "Move point to end of current line as displayed.
4301 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4302 If point reaches the beginning or end of buffer, it stops there.
4304 To ignore the effects of the `intangible' text or overlay
4305 property, bind `inhibit-point-motion-hooks' to t.
4306 If there is an image in the current line, this function
4307 disregards newlines that are part of the text on which the image
4310 (or arg (setq arg 1))
4315 (let ((goal-column 0)
4316 (line-move-visual nil))
4317 (and (line-move arg t)
4320 (while (and (not (bobp)) (invisible-p (1- (point))))
4321 (goto-char (previous-single-char-property-change
4322 (point) 'invisible)))
4326 (if (and (> (point) newpos)
4327 (eq (preceding-char) ?\n))
4329 (if (and (> (point) newpos) (not (eobp))
4330 (not (eq (following-char) ?\n)))
4331 ;; If we skipped something intangible and now we're not
4332 ;; really at eol, keep going.
4336 (defun move-beginning-of-line (arg)
4337 "Move point to beginning of current line as displayed.
4338 \(If there's an image in the line, this disregards newlines
4339 which are part of the text that the image rests on.)
4341 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4342 If point reaches the beginning or end of buffer, it stops there.
4343 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4345 (or arg (setq arg 1))
4347 (let ((orig (point))
4348 first-vis first-vis-field-value)
4350 ;; Move by lines, if ARG is not 1 (the default).
4352 (let ((line-move-visual nil))
4353 (line-move (1- arg) t)))
4355 ;; Move to beginning-of-line, ignoring fields and invisibles.
4356 (skip-chars-backward "^\n")
4357 (while (and (not (bobp)) (invisible-p (1- (point))))
4358 (goto-char (previous-char-property-change (point)))
4359 (skip-chars-backward "^\n"))
4361 ;; Now find first visible char in the line
4362 (while (and (not (eobp)) (invisible-p (point)))
4363 (goto-char (next-char-property-change (point))))
4364 (setq first-vis (point))
4366 ;; See if fields would stop us from reaching FIRST-VIS.
4367 (setq first-vis-field-value
4368 (constrain-to-field first-vis orig (/= arg 1) t nil))
4370 (goto-char (if (/= first-vis-field-value first-vis)
4371 ;; If yes, obey them.
4372 first-vis-field-value
4373 ;; Otherwise, move to START with attention to fields.
4374 ;; (It is possible that fields never matter in this case.)
4375 (constrain-to-field (point) orig
4376 (/= arg 1) t nil)))))
4379 ;;; Many people have said they rarely use this feature, and often type
4380 ;;; it by accident. Maybe it shouldn't even be on a key.
4381 (put 'set-goal-column 'disabled t)
4383 (defun set-goal-column (arg)
4384 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4385 Those commands will move to this position in the line moved to
4386 rather than trying to keep the same horizontal position.
4387 With a non-nil argument ARG, clears out the goal column
4388 so that \\[next-line] and \\[previous-line] resume vertical motion.
4389 The goal column is stored in the variable `goal-column'."
4393 (setq goal-column nil)
4394 (message "No goal column"))
4395 (setq goal-column (current-column))
4396 ;; The older method below can be erroneous if `set-goal-column' is bound
4397 ;; to a sequence containing %
4398 ;;(message (substitute-command-keys
4399 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4403 (format "Goal column %d " goal-column)
4404 (substitute-command-keys
4405 "(use \\[set-goal-column] with an arg to unset it)")))
4410 ;;; Editing based on visual lines, as opposed to logical lines.
4412 (defun end-of-visual-line (&optional n)
4413 "Move point to end of current visual line.
4414 With argument N not nil or 1, move forward N - 1 visual lines first.
4415 If point reaches the beginning or end of buffer, it stops there.
4416 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4420 (let ((line-move-visual t))
4421 (line-move (1- n) t)))
4422 (vertical-motion (cons (window-width) 0)))
4424 (defun beginning-of-visual-line (&optional n)
4425 "Move point to beginning of current visual line.
4426 With argument N not nil or 1, move forward N - 1 visual lines first.
4427 If point reaches the beginning or end of buffer, it stops there.
4428 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4432 (let ((line-move-visual t))
4433 (line-move (1- n) t)))
4434 (vertical-motion 0))
4436 (defun kill-visual-line (&optional arg)
4437 "Kill the rest of the visual line.
4438 If there are only whitespace characters there, kill through the
4441 With prefix argument ARG, kill that many lines from point.
4442 Negative arguments kill lines backward.
4443 With zero argument, kill the text before point on the current line.
4445 When calling from a program, nil means \"no arg\",
4446 a number counts as a prefix arg.
4448 If `kill-whole-line' is non-nil, then this command kills the whole line
4449 including its terminating newline, when used at the beginning of a line
4450 with no argument. As a consequence, you can always kill a whole line
4451 by typing \\[beginning-of-line] \\[kill-line].
4453 If you want to append the killed line to the last killed text,
4454 use \\[append-next-kill] before \\[kill-line].
4456 If the buffer is read-only, Emacs will beep and refrain from deleting
4457 the line, but put the line in the kill ring anyway. This means that
4458 you can use this command to copy text from a read-only buffer.
4459 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4462 (let ((opoint (point))
4463 (line-move-visual t)
4465 ;; It is better to move point to the other end of the kill before
4466 ;; killing. That way, in a read-only buffer, point moves across
4467 ;; the text that is copied to the kill ring. The choice has no
4468 ;; effect on undo now that undo records the value of point from
4469 ;; before the command was run.
4471 (vertical-motion (prefix-numeric-value arg))
4473 (signal 'end-of-buffer nil))
4474 (setq end (save-excursion
4475 (end-of-visual-line) (point)))
4476 (if (or (save-excursion
4477 ;; If trailing whitespace is visible,
4478 ;; don't treat it as nothing.
4479 (unless show-trailing-whitespace
4480 (skip-chars-forward " \t" end))
4482 (and kill-whole-line (bolp)))
4485 (kill-region opoint (point))))
4487 (defun next-logical-line (&optional arg try-vscroll)
4488 "Move cursor vertically down ARG lines.
4489 This is identical to `next-line', except that it always moves
4490 by logical lines instead of visual lines, ignoring the value of
4491 the variable `line-move-visual'."
4492 (interactive "^p\np")
4493 (let ((line-move-visual nil))
4495 (next-line arg try-vscroll))))
4497 (defun previous-logical-line (&optional arg try-vscroll)
4498 "Move cursor vertically up ARG lines.
4499 This is identical to `previous-line', except that it always moves
4500 by logical lines instead of visual lines, ignoring the value of
4501 the variable `line-move-visual'."
4502 (interactive "^p\np")
4503 (let ((line-move-visual nil))
4505 (previous-line arg try-vscroll))))
4507 (defgroup visual-line nil
4508 "Editing based on visual lines."
4512 (defvar visual-line-mode-map
4513 (let ((map (make-sparse-keymap)))
4514 (define-key map [remap kill-line] 'kill-visual-line)
4515 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4516 (define-key map [remap move-end-of-line] 'end-of-visual-line)
4517 ;; These keybindings interfere with xterm function keys. Are
4518 ;; there any other suitable bindings?
4519 ;; (define-key map "\M-[" 'previous-logical-line)
4520 ;; (define-key map "\M-]" 'next-logical-line)
4523 (defcustom visual-line-fringe-indicators '(nil nil)
4524 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4525 The value should be a list of the form (LEFT RIGHT), where LEFT
4526 and RIGHT are symbols representing the bitmaps to display, to
4527 indicate wrapped lines, in the left and right fringes respectively.
4528 See also `fringe-indicator-alist'.
4529 The default is not to display fringe indicators for wrapped lines.
4530 This variable does not affect fringe indicators displayed for
4532 :type '(list (choice (const :tag "Hide left indicator" nil)
4533 (const :tag "Left curly arrow" left-curly-arrow)
4534 (symbol :tag "Other bitmap"))
4535 (choice (const :tag "Hide right indicator" nil)
4536 (const :tag "Right curly arrow" right-curly-arrow)
4537 (symbol :tag "Other bitmap")))
4538 :set (lambda (symbol value)
4539 (dolist (buf (buffer-list))
4540 (with-current-buffer buf
4541 (when (and (boundp 'visual-line-mode)
4542 (symbol-value 'visual-line-mode))
4543 (setq fringe-indicator-alist
4544 (cons (cons 'continuation value)
4547 (copy-tree fringe-indicator-alist)))))))
4548 (set-default symbol value)))
4550 (defvar visual-line--saved-state nil)
4552 (define-minor-mode visual-line-mode
4553 "Redefine simple editing commands to act on visual lines, not logical lines.
4554 This also turns on `word-wrap' in the buffer."
4555 :keymap visual-line-mode-map
4558 (if visual-line-mode
4560 (set (make-local-variable 'visual-line--saved-state) nil)
4561 ;; Save the local values of some variables, to be restored if
4562 ;; visual-line-mode is turned off.
4563 (dolist (var '(line-move-visual truncate-lines
4564 truncate-partial-width-windows
4565 word-wrap fringe-indicator-alist))
4566 (if (local-variable-p var)
4567 (push (cons var (symbol-value var))
4568 visual-line--saved-state)))
4569 (set (make-local-variable 'line-move-visual) t)
4570 (set (make-local-variable 'truncate-partial-width-windows) nil)
4571 (setq truncate-lines nil
4573 fringe-indicator-alist
4574 (cons (cons 'continuation visual-line-fringe-indicators)
4575 fringe-indicator-alist)))
4576 (kill-local-variable 'line-move-visual)
4577 (kill-local-variable 'word-wrap)
4578 (kill-local-variable 'truncate-lines)
4579 (kill-local-variable 'truncate-partial-width-windows)
4580 (kill-local-variable 'fringe-indicator-alist)
4581 (dolist (saved visual-line--saved-state)
4582 (set (make-local-variable (car saved)) (cdr saved)))
4583 (kill-local-variable 'visual-line--saved-state)))
4585 (defun turn-on-visual-line-mode ()
4586 (visual-line-mode 1))
4588 (define-globalized-minor-mode global-visual-line-mode
4589 visual-line-mode turn-on-visual-line-mode
4592 (defun scroll-other-window-down (lines)
4593 "Scroll the \"other window\" down.
4594 For more details, see the documentation for `scroll-other-window'."
4596 (scroll-other-window
4597 ;; Just invert the argument's meaning.
4598 ;; We can do that without knowing which window it will be.
4599 (if (eq lines '-) nil
4601 (- (prefix-numeric-value lines))))))
4603 (defun beginning-of-buffer-other-window (arg)
4604 "Move point to the beginning of the buffer in the other window.
4605 Leave mark at previous position.
4606 With arg N, put point N/10 of the way from the true beginning."
4608 (let ((orig-window (selected-window))
4609 (window (other-window-for-scrolling)))
4610 ;; We use unwind-protect rather than save-window-excursion
4611 ;; because the latter would preserve the things we want to change.
4614 (select-window window)
4615 ;; Set point and mark in that window's buffer.
4617 (beginning-of-buffer arg))
4618 ;; Set point accordingly.
4620 (select-window orig-window))))
4622 (defun end-of-buffer-other-window (arg)
4623 "Move point to the end of the buffer in the other window.
4624 Leave mark at previous position.
4625 With arg N, put point N/10 of the way from the true end."
4627 ;; See beginning-of-buffer-other-window for comments.
4628 (let ((orig-window (selected-window))
4629 (window (other-window-for-scrolling)))
4632 (select-window window)
4634 (end-of-buffer arg))
4636 (select-window orig-window))))
4638 (defun transpose-chars (arg)
4639 "Interchange characters around point, moving forward one character.
4640 With prefix arg ARG, effect is to take character before point
4641 and drag it forward past ARG other characters (backward if ARG negative).
4642 If no argument and at end of line, the previous two chars are exchanged."
4644 (and (null arg) (eolp) (forward-char -1))
4645 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4647 (defun transpose-words (arg)
4648 "Interchange words around point, leaving point at end of them.
4649 With prefix arg ARG, effect is to take word before or around point
4650 and drag it forward past ARG other words (backward if ARG negative).
4651 If ARG is zero, the words around or after point and around or after mark
4653 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
4655 (transpose-subr 'forward-word arg))
4657 (defun transpose-sexps (arg)
4658 "Like \\[transpose-words] but applies to sexps.
4659 Does not work on a sexp that point is in the middle of
4660 if it is a list or string."
4664 ;; Here we should try to simulate the behavior of
4665 ;; (cons (progn (forward-sexp x) (point))
4666 ;; (progn (forward-sexp (- x)) (point)))
4667 ;; Except that we don't want to rely on the second forward-sexp
4668 ;; putting us back to where we want to be, since forward-sexp-function
4669 ;; might do funny things like infix-precedence.
4671 (looking-at "\\sw\\|\\s_")
4673 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4674 ;; Jumping over a symbol. We might be inside it, mind you.
4675 (progn (funcall (if (> arg 0)
4676 'skip-syntax-backward 'skip-syntax-forward)
4678 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4679 ;; Otherwise, we're between sexps. Take a step back before jumping
4680 ;; to make sure we'll obey the same precedence no matter which direction
4682 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4683 (cons (save-excursion (forward-sexp arg) (point))
4684 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4685 (not (zerop (funcall (if (> arg 0)
4686 'skip-syntax-forward
4687 'skip-syntax-backward)
4692 (defun transpose-lines (arg)
4693 "Exchange current line and previous line, leaving point after both.
4694 With argument ARG, takes previous line and moves it past ARG lines.
4695 With argument 0, interchanges line point is in with line mark is in."
4697 (transpose-subr (function
4701 ;; Move forward over ARG lines,
4702 ;; but create newlines if necessary.
4703 (setq arg (forward-line arg))
4704 (if (/= (preceding-char) ?\n)
4705 (setq arg (1+ arg)))
4708 (forward-line arg))))
4711 (defun transpose-subr (mover arg &optional special)
4712 (let ((aux (if special mover
4714 (cons (progn (funcall mover x) (point))
4715 (progn (funcall mover (- x)) (point))))))
4720 (setq pos1 (funcall aux 1))
4722 (setq pos2 (funcall aux 1))
4723 (transpose-subr-1 pos1 pos2))
4724 (exchange-point-and-mark))
4726 (setq pos1 (funcall aux -1))
4727 (setq pos2 (funcall aux arg))
4728 (transpose-subr-1 pos1 pos2)
4729 (goto-char (car pos2)))
4731 (setq pos1 (funcall aux -1))
4732 (goto-char (car pos1))
4733 (setq pos2 (funcall aux arg))
4734 (transpose-subr-1 pos1 pos2)))))
4736 (defun transpose-subr-1 (pos1 pos2)
4737 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
4738 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
4739 (when (> (car pos1) (car pos2))
4741 (setq pos1 pos2 pos2 swap)))
4742 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
4743 (atomic-change-group
4745 ;; FIXME: We first delete the two pieces of text, so markers that
4746 ;; used to point to after the text end up pointing to before it :-(
4747 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
4748 (goto-char (car pos2))
4749 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
4750 (goto-char (car pos1))
4753 (defun backward-word (&optional arg)
4754 "Move backward until encountering the beginning of a word.
4755 With argument ARG, do this that many times."
4757 (forward-word (- (or arg 1))))
4759 (defun mark-word (&optional arg allow-extend)
4760 "Set mark ARG words away from point.
4761 The place mark goes is the same place \\[forward-word] would
4762 move to with the same argument.
4763 Interactively, if this command is repeated
4764 or (in Transient Mark mode) if the mark is active,
4765 it marks the next ARG words after the ones already marked."
4766 (interactive "P\np")
4767 (cond ((and allow-extend
4768 (or (and (eq last-command this-command) (mark t))
4770 (setq arg (if arg (prefix-numeric-value arg)
4771 (if (< (mark) (point)) -1 1)))
4780 (forward-word (prefix-numeric-value arg))
4784 (defun kill-word (arg)
4785 "Kill characters forward until encountering the end of a word.
4786 With argument ARG, do this that many times."
4788 (kill-region (point) (progn (forward-word arg) (point))))
4790 (defun backward-kill-word (arg)
4791 "Kill characters backward until encountering the beginning of a word.
4792 With argument ARG, do this that many times."
4794 (kill-word (- arg)))
4796 (defun current-word (&optional strict really-word)
4797 "Return the symbol or word that point is on (or a nearby one) as a string.
4798 The return value includes no text properties.
4799 If optional arg STRICT is non-nil, return nil unless point is within
4800 or adjacent to a symbol or word. In all cases the value can be nil
4801 if there is no word nearby.
4802 The function, belying its name, normally finds a symbol.
4803 If optional arg REALLY-WORD is non-nil, it finds just a word."
4805 (let* ((oldpoint (point)) (start (point)) (end (point))
4806 (syntaxes (if really-word "w" "w_"))
4807 (not-syntaxes (concat "^" syntaxes)))
4808 (skip-syntax-backward syntaxes) (setq start (point))
4809 (goto-char oldpoint)
4810 (skip-syntax-forward syntaxes) (setq end (point))
4811 (when (and (eq start oldpoint) (eq end oldpoint)
4812 ;; Point is neither within nor adjacent to a word.
4814 ;; Look for preceding word in same line.
4815 (skip-syntax-backward not-syntaxes
4816 (save-excursion (beginning-of-line)
4819 ;; No preceding word in same line.
4820 ;; Look for following word in same line.
4822 (skip-syntax-forward not-syntaxes
4823 (save-excursion (end-of-line)
4825 (setq start (point))
4826 (skip-syntax-forward syntaxes)
4829 (skip-syntax-backward syntaxes)
4830 (setq start (point))))
4831 ;; If we found something nonempty, return it as a string.
4832 (unless (= start end)
4833 (buffer-substring-no-properties start end)))))
4835 (defcustom fill-prefix nil
4836 "String for filling to insert at front of new line, or nil for none."
4837 :type '(choice (const :tag "None" nil)
4840 (make-variable-buffer-local 'fill-prefix)
4841 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
4843 (defcustom auto-fill-inhibit-regexp nil
4844 "Regexp to match lines which should not be auto-filled."
4845 :type '(choice (const :tag "None" nil)
4849 ;; This function is used as the auto-fill-function of a buffer
4850 ;; when Auto-Fill mode is enabled.
4851 ;; It returns t if it really did any work.
4852 ;; (Actually some major modes use a different auto-fill function,
4853 ;; but this one is the default one.)
4854 (defun do-auto-fill ()
4855 (let (fc justify give-up
4856 (fill-prefix fill-prefix))
4857 (if (or (not (setq justify (current-justification)))
4858 (null (setq fc (current-fill-column)))
4859 (and (eq justify 'left)
4860 (<= (current-column) fc))
4861 (and auto-fill-inhibit-regexp
4862 (save-excursion (beginning-of-line)
4863 (looking-at auto-fill-inhibit-regexp))))
4864 nil ;; Auto-filling not required
4865 (if (memq justify '(full center right))
4866 (save-excursion (unjustify-current-line)))
4868 ;; Choose a fill-prefix automatically.
4869 (when (and adaptive-fill-mode
4870 (or (null fill-prefix) (string= fill-prefix "")))
4872 (fill-context-prefix
4873 (save-excursion (backward-paragraph 1) (point))
4874 (save-excursion (forward-paragraph 1) (point)))))
4875 (and prefix (not (equal prefix ""))
4876 ;; Use auto-indentation rather than a guessed empty prefix.
4877 (not (and fill-indent-according-to-mode
4878 (string-match "\\`[ \t]*\\'" prefix)))
4879 (setq fill-prefix prefix))))
4881 (while (and (not give-up) (> (current-column) fc))
4882 ;; Determine where to split the line.
4887 (setq after-prefix (point))
4889 (looking-at (regexp-quote fill-prefix))
4890 (setq after-prefix (match-end 0)))
4891 (move-to-column (1+ fc))
4892 (fill-move-to-break-point after-prefix)
4895 ;; See whether the place we found is any good.
4897 (goto-char fill-point)
4899 ;; There is no use breaking at end of line.
4900 (save-excursion (skip-chars-forward " ") (eolp))
4901 ;; It is futile to split at the end of the prefix
4902 ;; since we would just insert the prefix again.
4903 (and after-prefix (<= (point) after-prefix))
4904 ;; Don't split right after a comment starter
4905 ;; since we would just make another comment starter.
4906 (and comment-start-skip
4907 (let ((limit (point)))
4909 (and (re-search-forward comment-start-skip
4911 (eq (point) limit))))))
4912 ;; No good place to break => stop trying.
4914 ;; Ok, we have a useful place to break the line. Do it.
4915 (let ((prev-column (current-column)))
4916 ;; If point is at the fill-point, do not `save-excursion'.
4917 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4918 ;; point will end up before it rather than after it.
4920 (skip-chars-backward " \t")
4921 (= (point) fill-point))
4922 (default-indent-new-line t)
4924 (goto-char fill-point)
4925 (default-indent-new-line t)))
4926 ;; Now do justification, if required
4927 (if (not (eq justify 'left))
4930 (justify-current-line justify nil t)))
4931 ;; If making the new line didn't reduce the hpos of
4932 ;; the end of the line, then give up now;
4933 ;; trying again will not help.
4934 (if (>= (current-column) prev-column)
4935 (setq give-up t))))))
4936 ;; Justify last line.
4937 (justify-current-line justify t t)
4940 (defvar comment-line-break-function 'comment-indent-new-line
4941 "*Mode-specific function which line breaks and continues a comment.
4942 This function is called during auto-filling when a comment syntax
4944 The function should take a single optional argument, which is a flag
4945 indicating whether it should use soft newlines.")
4947 (defun default-indent-new-line (&optional soft)
4948 "Break line at point and indent.
4949 If a comment syntax is defined, call `comment-indent-new-line'.
4951 The inserted newline is marked hard if variable `use-hard-newlines' is true,
4952 unless optional argument SOFT is non-nil."
4955 (funcall comment-line-break-function soft)
4956 ;; Insert the newline before removing empty space so that markers
4957 ;; get preserved better.
4958 (if soft (insert-and-inherit ?\n) (newline 1))
4959 (save-excursion (forward-char -1) (delete-horizontal-space))
4960 (delete-horizontal-space)
4962 (if (and fill-prefix (not adaptive-fill-mode))
4963 ;; Blindly trust a non-adaptive fill-prefix.
4965 (indent-to-left-margin)
4966 (insert-before-markers-and-inherit fill-prefix))
4969 ;; If there's an adaptive prefix, use it unless we're inside
4970 ;; a comment and the prefix is not a comment starter.
4972 (indent-to-left-margin)
4973 (insert-and-inherit fill-prefix))
4974 ;; If we're not inside a comment, just try to indent.
4975 (t (indent-according-to-mode))))))
4977 (defvar normal-auto-fill-function 'do-auto-fill
4978 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4979 Some major modes set this.")
4981 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
4982 ;; FIXME: turn into a proper minor mode.
4983 ;; Add a global minor mode version of it.
4984 (defun auto-fill-mode (&optional arg)
4985 "Toggle Auto Fill mode.
4986 With ARG, turn Auto Fill mode on if and only if ARG is positive.
4987 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4988 automatically breaks the line at a previous space.
4990 The value of `normal-auto-fill-function' specifies the function to use
4991 for `auto-fill-function' when turning Auto Fill mode on."
4993 (prog1 (setq auto-fill-function
4995 (not auto-fill-function)
4996 (> (prefix-numeric-value arg) 0))
4997 normal-auto-fill-function
4999 (force-mode-line-update)))
5001 ;; This holds a document string used to document auto-fill-mode.
5002 (defun auto-fill-function ()
5003 "Automatically break line at a previous space, in insertion of text."
5006 (defun turn-on-auto-fill ()
5007 "Unconditionally turn on Auto Fill mode."
5010 (defun turn-off-auto-fill ()
5011 "Unconditionally turn off Auto Fill mode."
5012 (auto-fill-mode -1))
5014 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
5016 (defun set-fill-column (arg)
5017 "Set `fill-column' to specified argument.
5018 Use \\[universal-argument] followed by a number to specify a column.
5019 Just \\[universal-argument] as argument means to use the current column."
5021 (list (or current-prefix-arg
5022 ;; We used to use current-column silently, but C-x f is too easily
5023 ;; typed as a typo for C-x C-f, so we turned it into an error and
5024 ;; now an interactive prompt.
5025 (read-number "Set fill-column to: " (current-column)))))
5027 (setq arg (current-column)))
5028 (if (not (integerp arg))
5029 ;; Disallow missing argument; it's probably a typo for C-x C-f.
5030 (error "set-fill-column requires an explicit argument")
5031 (message "Fill column set to %d (was %d)" arg fill-column)
5032 (setq fill-column arg)))
5034 (defun set-selective-display (arg)
5035 "Set `selective-display' to ARG; clear it if no arg.
5036 When the value of `selective-display' is a number > 0,
5037 lines whose indentation is >= that value are not displayed.
5038 The variable `selective-display' has a separate value for each buffer."
5040 (if (eq selective-display t)
5041 (error "selective-display already in use for marked lines"))
5044 (narrow-to-region (point-min) (point))
5045 (goto-char (window-start))
5046 (vertical-motion (window-height)))))
5047 (setq selective-display
5048 (and arg (prefix-numeric-value arg)))
5049 (recenter current-vpos))
5050 (set-window-start (selected-window) (window-start (selected-window)))
5051 (princ "selective-display set to " t)
5052 (prin1 selective-display t)
5055 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
5057 (defun toggle-truncate-lines (&optional arg)
5058 "Toggle whether to fold or truncate long lines for the current buffer.
5059 With prefix argument ARG, truncate long lines if ARG is positive,
5060 otherwise don't truncate them. Note that in side-by-side windows,
5061 this command has no effect if `truncate-partial-width-windows'
5064 (setq truncate-lines
5066 (not truncate-lines)
5067 (> (prefix-numeric-value arg) 0)))
5068 (force-mode-line-update)
5069 (unless truncate-lines
5070 (let ((buffer (current-buffer)))
5071 (walk-windows (lambda (window)
5072 (if (eq buffer (window-buffer window))
5073 (set-window-hscroll window 0)))
5075 (message "Truncate long lines %s"
5076 (if truncate-lines "enabled" "disabled")))
5078 (defvar overwrite-mode-textual " Ovwrt"
5079 "The string displayed in the mode line when in overwrite mode.")
5080 (defvar overwrite-mode-binary " Bin Ovwrt"
5081 "The string displayed in the mode line when in binary overwrite mode.")
5083 (defun overwrite-mode (arg)
5084 "Toggle overwrite mode.
5085 With prefix argument ARG, turn overwrite mode on if ARG is positive,
5086 otherwise turn it off. In overwrite mode, printing characters typed
5087 in replace existing text on a one-for-one basis, rather than pushing
5088 it to the right. At the end of a line, such characters extend the line.
5089 Before a tab, such characters insert until the tab is filled in.
5090 \\[quoted-insert] still inserts characters in overwrite mode; this
5091 is supposed to make it easier to insert characters when necessary."
5093 (setq overwrite-mode
5094 (if (if (null arg) (not overwrite-mode)
5095 (> (prefix-numeric-value arg) 0))
5096 'overwrite-mode-textual))
5097 (force-mode-line-update))
5099 (defun binary-overwrite-mode (arg)
5100 "Toggle binary overwrite mode.
5101 With prefix argument ARG, turn binary overwrite mode on if ARG is
5102 positive, otherwise turn it off. In binary overwrite mode, printing
5103 characters typed in replace existing text. Newlines are not treated
5104 specially, so typing at the end of a line joins the line to the next,
5105 with the typed character between them. Typing before a tab character
5106 simply replaces the tab with the character typed. \\[quoted-insert]
5107 replaces the text at the cursor, just as ordinary typing characters do.
5109 Note that binary overwrite mode is not its own minor mode; it is a
5110 specialization of overwrite mode, entered by setting the
5111 `overwrite-mode' variable to `overwrite-mode-binary'."
5113 (setq overwrite-mode
5115 (not (eq overwrite-mode 'overwrite-mode-binary))
5116 (> (prefix-numeric-value arg) 0))
5117 'overwrite-mode-binary))
5118 (force-mode-line-update))
5120 (define-minor-mode line-number-mode
5121 "Toggle Line Number mode.
5122 With ARG, turn Line Number mode on if ARG is positive, otherwise
5123 turn it off. When Line Number mode is enabled, the line number
5124 appears in the mode line.
5126 Line numbers do not appear for very large buffers and buffers
5127 with very long lines; see variables `line-number-display-limit'
5128 and `line-number-display-limit-width'."
5129 :init-value t :global t :group 'mode-line)
5131 (define-minor-mode column-number-mode
5132 "Toggle Column Number mode.
5133 With ARG, turn Column Number mode on if ARG is positive,
5134 otherwise turn it off. When Column Number mode is enabled, the
5135 column number appears in the mode line."
5136 :global t :group 'mode-line)
5138 (define-minor-mode size-indication-mode
5139 "Toggle Size Indication mode.
5140 With ARG, turn Size Indication mode on if ARG is positive,
5141 otherwise turn it off. When Size Indication mode is enabled, the
5142 size of the accessible part of the buffer appears in the mode line."
5143 :global t :group 'mode-line)
5145 (defgroup paren-blinking nil
5146 "Blinking matching of parens and expressions."
5147 :prefix "blink-matching-"
5148 :group 'paren-matching)
5150 (defcustom blink-matching-paren t
5151 "Non-nil means show matching open-paren when close-paren is inserted."
5153 :group 'paren-blinking)
5155 (defcustom blink-matching-paren-on-screen t
5156 "Non-nil means show matching open-paren when it is on screen.
5157 If nil, don't show it (but the open-paren can still be shown
5158 when it is off screen).
5160 This variable has no effect if `blink-matching-paren' is nil.
5161 \(In that case, the open-paren is never shown.)
5162 It is also ignored if `show-paren-mode' is enabled."
5164 :group 'paren-blinking)
5166 (defcustom blink-matching-paren-distance (* 25 1024)
5167 "If non-nil, maximum distance to search backwards for matching open-paren.
5168 If nil, search stops at the beginning of the accessible portion of the buffer."
5169 :type '(choice (const nil) integer)
5170 :group 'paren-blinking)
5172 (defcustom blink-matching-delay 1
5173 "Time in seconds to delay after showing a matching paren."
5175 :group 'paren-blinking)
5177 (defcustom blink-matching-paren-dont-ignore-comments nil
5178 "If nil, `blink-matching-paren' ignores comments.
5179 More precisely, when looking for the matching parenthesis,
5180 it skips the contents of comments that end before point."
5182 :group 'paren-blinking)
5184 (defun blink-matching-open ()
5185 "Move cursor momentarily to the beginning of the sexp before point."
5187 (when (and (> (point) (point-min))
5188 blink-matching-paren
5189 ;; Verify an even number of quoting characters precede the close.
5190 (= 1 (logand 1 (- (point)
5193 (skip-syntax-backward "/\\")
5195 (let* ((oldpos (point))
5196 (message-log-max nil) ; Don't log messages about paren matching.
5197 (atdollar (eq (syntax-class (syntax-after (1- oldpos))) 8))
5202 (if blink-matching-paren-distance
5204 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5205 (- (point) blink-matching-paren-distance))
5207 (let ((parse-sexp-ignore-comments
5208 (and parse-sexp-ignore-comments
5209 (not blink-matching-paren-dont-ignore-comments))))
5211 (scan-sexps oldpos -1)
5217 (eq (syntax-class (syntax-after blinkpos)) 8)))
5218 (let ((syntax (syntax-after blinkpos)))
5220 (eq (syntax-class syntax) 4)
5224 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-10/msg00871.html
5225 ((not (or (and isdollar blinkpos)
5226 (and atdollar (not blinkpos)) ; see below
5227 (eq matching-paren (char-before oldpos))
5228 ;; The cdr might hold a new paren-class info rather than
5229 ;; a matching-char info, in which case the two CDRs
5231 (eq matching-paren (cdr (syntax-after (1- oldpos))))))
5233 (minibuffer-message " [Mismatched parentheses]")
5234 (message "Mismatched parentheses")))
5236 (or blink-matching-paren-distance
5237 ;; Don't complain when `$' with no blinkpos, because it
5238 ;; could just be the first one typed in the buffer.
5241 (minibuffer-message " [Unmatched parenthesis]")
5242 (message "Unmatched parenthesis"))))
5243 ((pos-visible-in-window-p blinkpos)
5244 ;; Matching open within window, temporarily move to blinkpos but only
5245 ;; if `blink-matching-paren-on-screen' is non-nil.
5246 (and blink-matching-paren-on-screen
5247 (not show-paren-mode)
5249 (goto-char blinkpos)
5250 (sit-for blink-matching-delay))))
5253 (goto-char blinkpos)
5254 (let ((open-paren-line-string
5255 ;; Show what precedes the open in its line, if anything.
5257 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5258 (buffer-substring (line-beginning-position)
5260 ;; Show what follows the open in its line, if anything.
5263 (skip-chars-forward " \t")
5265 (buffer-substring blinkpos
5266 (line-end-position)))
5267 ;; Otherwise show the previous nonblank line,
5269 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5271 (buffer-substring (progn
5272 (skip-chars-backward "\n \t")
5273 (line-beginning-position))
5274 (progn (end-of-line)
5275 (skip-chars-backward " \t")
5277 ;; Replace the newline and other whitespace with `...'.
5279 (buffer-substring blinkpos (1+ blinkpos))))
5280 ;; There is nothing to show except the char itself.
5281 (t (buffer-substring blinkpos (1+ blinkpos))))))
5282 (message "Matches %s"
5283 (substring-no-properties open-paren-line-string)))))))))
5285 (setq blink-paren-function 'blink-matching-open)
5287 ;; This executes C-g typed while Emacs is waiting for a command.
5288 ;; Quitting out of a program does not go through here;
5289 ;; that happens in the QUIT macro at the C code level.
5290 (defun keyboard-quit ()
5291 "Signal a `quit' condition.
5292 During execution of Lisp code, this character causes a quit directly.
5293 At top-level, as an editor command, this simply beeps."
5296 (if (fboundp 'kmacro-keyboard-quit)
5297 (kmacro-keyboard-quit))
5298 (setq defining-kbd-macro nil)
5301 (defvar buffer-quit-function nil
5302 "Function to call to \"quit\" the current buffer, or nil if none.
5303 \\[keyboard-escape-quit] calls this function when its more local actions
5304 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5306 (defun keyboard-escape-quit ()
5307 "Exit the current \"mode\" (in a generalized sense of the word).
5308 This command can exit an interactive command such as `query-replace',
5309 can clear out a prefix argument or a region,
5310 can get out of the minibuffer or other recursive edit,
5311 cancel the use of the current buffer (for special-purpose buffers),
5312 or go back to just one window (by deleting all but the selected window)."
5314 (cond ((eq last-command 'mode-exited) nil)
5315 ((> (minibuffer-depth) 0)
5316 (abort-recursive-edit))
5321 ((> (recursion-depth) 0)
5322 (exit-recursive-edit))
5323 (buffer-quit-function
5324 (funcall buffer-quit-function))
5325 ((not (one-window-p t))
5326 (delete-other-windows))
5327 ((string-match "^ \\*" (buffer-name (current-buffer)))
5330 (defun play-sound-file (file &optional volume device)
5331 "Play sound stored in FILE.
5332 VOLUME and DEVICE correspond to the keywords of the sound
5333 specification for `play-sound'."
5334 (interactive "fPlay sound file: ")
5335 (let ((sound (list :file file)))
5337 (plist-put sound :volume volume))
5339 (plist-put sound :device device))
5341 (play-sound sound)))
5344 (defcustom read-mail-command 'rmail
5345 "Your preference for a mail reading package.
5346 This is used by some keybindings which support reading mail.
5347 See also `mail-user-agent' concerning sending mail."
5348 :type '(choice (function-item rmail)
5349 (function-item gnus)
5350 (function-item mh-rmail)
5351 (function :tag "Other"))
5355 (defcustom mail-user-agent 'sendmail-user-agent
5356 "Your preference for a mail composition package.
5357 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
5358 outgoing email message. This variable lets you specify which
5359 mail-sending package you prefer.
5361 Valid values include:
5363 `sendmail-user-agent' -- use the default Emacs Mail package.
5364 See Info node `(emacs)Sending Mail'.
5365 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5366 See Info node `(mh-e)'.
5367 `message-user-agent' -- use the Gnus Message package.
5368 See Info node `(message)'.
5369 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5370 paraphernalia, particularly the Gcc: header for
5373 Additional valid symbols may be available; check with the author of
5374 your package for details. The function should return non-nil if it
5377 See also `read-mail-command' concerning reading mail."
5378 :type '(radio (function-item :tag "Default Emacs mail"
5380 sendmail-user-agent)
5381 (function-item :tag "Emacs interface to MH"
5384 (function-item :tag "Gnus Message package"
5387 (function-item :tag "Gnus Message with full Gnus features"
5390 (function :tag "Other"))
5393 (define-mail-user-agent 'sendmail-user-agent
5394 'sendmail-user-agent-compose
5395 'mail-send-and-exit)
5397 (defun rfc822-goto-eoh ()
5398 ;; Go to header delimiter line in a mail message, following RFC822 rules
5399 (goto-char (point-min))
5400 (when (re-search-forward
5401 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5402 (goto-char (match-beginning 0))))
5404 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
5405 switch-function yank-action
5408 (let ((special-display-buffer-names nil)
5409 (special-display-regexps nil)
5410 (same-window-buffer-names nil)
5411 (same-window-regexps nil))
5412 (funcall switch-function "*mail*")))
5413 (let ((cc (cdr (assoc-string "cc" other-headers t)))
5414 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
5415 (body (cdr (assoc-string "body" other-headers t))))
5416 (or (mail continue to subject in-reply-to cc yank-action send-actions)
5418 (error "Message aborted"))
5421 (while other-headers
5422 (unless (member-ignore-case (car (car other-headers))
5423 '("in-reply-to" "cc" "body"))
5424 (insert (car (car other-headers)) ": "
5425 (cdr (car other-headers))
5426 (if use-hard-newlines hard-newline "\n")))
5427 (setq other-headers (cdr other-headers)))
5433 (defun compose-mail (&optional to subject other-headers continue
5434 switch-function yank-action send-actions)
5435 "Start composing a mail message to send.
5436 This uses the user's chosen mail composition package
5437 as selected with the variable `mail-user-agent'.
5438 The optional arguments TO and SUBJECT specify recipients
5439 and the initial Subject field, respectively.
5441 OTHER-HEADERS is an alist specifying additional
5442 header fields. Elements look like (HEADER . VALUE) where both
5443 HEADER and VALUE are strings.
5445 CONTINUE, if non-nil, says to continue editing a message already
5448 SWITCH-FUNCTION, if non-nil, is a function to use to
5449 switch to and display the buffer used for mail composition.
5451 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
5452 to insert the raw text of the message being replied to.
5453 It has the form (FUNCTION . ARGS). The user agent will apply
5454 FUNCTION to ARGS, to insert the raw text of the original message.
5455 \(The user agent will also run `mail-citation-hook', *after* the
5456 original text has been inserted in this way.)
5458 SEND-ACTIONS is a list of actions to call when the message is sent.
5459 Each action has the form (FUNCTION . ARGS)."
5461 (list nil nil nil current-prefix-arg))
5462 (let ((function (get mail-user-agent 'composefunc)))
5463 (funcall function to subject other-headers continue
5464 switch-function yank-action send-actions)))
5466 (defun compose-mail-other-window (&optional to subject other-headers continue
5467 yank-action send-actions)
5468 "Like \\[compose-mail], but edit the outgoing message in another window."
5470 (list nil nil nil current-prefix-arg))
5471 (compose-mail to subject other-headers continue
5472 'switch-to-buffer-other-window yank-action send-actions))
5475 (defun compose-mail-other-frame (&optional to subject other-headers continue
5476 yank-action send-actions)
5477 "Like \\[compose-mail], but edit the outgoing message in another frame."
5479 (list nil nil nil current-prefix-arg))
5480 (compose-mail to subject other-headers continue
5481 'switch-to-buffer-other-frame yank-action send-actions))
5483 (defvar set-variable-value-history nil
5484 "History of values entered with `set-variable'.
5486 Maximum length of the history list is determined by the value
5487 of `history-length', which see.")
5489 (defun set-variable (variable value &optional make-local)
5490 "Set VARIABLE to VALUE. VALUE is a Lisp object.
5491 VARIABLE should be a user option variable name, a Lisp variable
5492 meant to be customized by users. You should enter VALUE in Lisp syntax,
5493 so if you want VALUE to be a string, you must surround it with doublequotes.
5494 VALUE is used literally, not evaluated.
5496 If VARIABLE has a `variable-interactive' property, that is used as if
5497 it were the arg to `interactive' (which see) to interactively read VALUE.
5499 If VARIABLE has been defined with `defcustom', then the type information
5500 in the definition is used to check that VALUE is valid.
5502 With a prefix argument, set VARIABLE to VALUE buffer-locally."
5504 (let* ((default-var (variable-at-point))
5505 (var (if (user-variable-p default-var)
5506 (read-variable (format "Set variable (default %s): " default-var)
5508 (read-variable "Set variable: ")))
5509 (minibuffer-help-form '(describe-variable var))
5510 (prop (get var 'variable-interactive))
5511 (obsolete (car (get var 'byte-obsolete-variable)))
5512 (prompt (format "Set %s %s to value: " var
5513 (cond ((local-variable-p var)
5515 ((or current-prefix-arg
5516 (local-variable-if-set-p var))
5521 (message (concat "`%S' is obsolete; "
5522 (if (symbolp obsolete) "use `%S' instead" "%s"))
5526 ;; Use VAR's `variable-interactive' property
5527 ;; as an interactive spec for prompting.
5528 (call-interactively `(lambda (arg)
5532 (read-string prompt nil
5533 'set-variable-value-history
5534 (format "%S" (symbol-value var))))))))
5535 (list var val current-prefix-arg)))
5537 (and (custom-variable-p variable)
5538 (not (get variable 'custom-type))
5539 (custom-load-symbol variable))
5540 (let ((type (get variable 'custom-type)))
5542 ;; Match with custom type.
5544 (setq type (widget-convert type))
5545 (unless (widget-apply type :match value)
5546 (error "Value `%S' does not match type %S of %S"
5547 value (car type) variable))))
5550 (make-local-variable variable))
5552 (set variable value)
5554 ;; Force a thorough redisplay for the case that the variable
5555 ;; has an effect on the display, like `tab-width' has.
5556 (force-mode-line-update))
5558 ;; Define the major mode for lists of completions.
5560 (defvar completion-list-mode-map
5561 (let ((map (make-sparse-keymap)))
5562 (define-key map [mouse-2] 'mouse-choose-completion)
5563 (define-key map [follow-link] 'mouse-face)
5564 (define-key map [down-mouse-2] nil)
5565 (define-key map "\C-m" 'choose-completion)
5566 (define-key map "\e\e\e" 'delete-completion-window)
5567 (define-key map [left] 'previous-completion)
5568 (define-key map [right] 'next-completion)
5570 "Local map for completion list buffers.")
5572 ;; Completion mode is suitable only for specially formatted data.
5573 (put 'completion-list-mode 'mode-class 'special)
5575 (defvar completion-reference-buffer nil
5576 "Record the buffer that was current when the completion list was requested.
5577 This is a local variable in the completion list buffer.
5578 Initial value is nil to avoid some compiler warnings.")
5580 (defvar completion-no-auto-exit nil
5581 "Non-nil means `choose-completion-string' should never exit the minibuffer.
5582 This also applies to other functions such as `choose-completion'
5583 and `mouse-choose-completion'.")
5585 (defvar completion-base-size nil
5586 "Number of chars before point not involved in completion.
5587 This is a local variable in the completion list buffer.
5588 It refers to the chars in the minibuffer if completing in the
5589 minibuffer, or in `completion-reference-buffer' otherwise.
5590 Only characters in the field at point are included.
5592 If nil, Emacs determines which part of the tail end of the
5593 buffer's text is involved in completion by comparing the text
5596 (defun delete-completion-window ()
5597 "Delete the completion list window.
5598 Go to the window from which completion was requested."
5600 (let ((buf completion-reference-buffer))
5601 (if (one-window-p t)
5602 (if (window-dedicated-p (selected-window))
5603 (delete-frame (selected-frame)))
5604 (delete-window (selected-window))
5605 (if (get-buffer-window buf)
5606 (select-window (get-buffer-window buf))))))
5608 (defun previous-completion (n)
5609 "Move to the previous item in the completion list."
5611 (next-completion (- n)))
5613 (defun next-completion (n)
5614 "Move to the next item in the completion list.
5615 With prefix argument N, move N items (negative N means move backward)."
5617 (let ((beg (point-min)) (end (point-max)))
5618 (while (and (> n 0) (not (eobp)))
5619 ;; If in a completion, move to the end of it.
5620 (when (get-text-property (point) 'mouse-face)
5621 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5622 ;; Move to start of next one.
5623 (unless (get-text-property (point) 'mouse-face)
5624 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5626 (while (and (< n 0) (not (bobp)))
5627 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
5628 ;; If in a completion, move to the start of it.
5629 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
5630 (goto-char (previous-single-property-change
5631 (point) 'mouse-face nil beg)))
5632 ;; Move to end of the previous completion.
5633 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
5634 (goto-char (previous-single-property-change
5635 (point) 'mouse-face nil beg)))
5636 ;; Move to the start of that one.
5637 (goto-char (previous-single-property-change
5638 (point) 'mouse-face nil beg))
5641 (defun choose-completion ()
5642 "Choose the completion that point is in or next to."
5644 (let (beg end completion (buffer completion-reference-buffer)
5645 (base-size completion-base-size))
5646 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
5647 (setq end (point) beg (1+ (point))))
5648 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
5649 (setq end (1- (point)) beg (point)))
5651 (error "No completion here"))
5652 (setq beg (previous-single-property-change beg 'mouse-face))
5653 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
5654 (setq completion (buffer-substring-no-properties beg end))
5655 (let ((owindow (selected-window)))
5656 (if (and (one-window-p t 'selected-frame)
5657 (window-dedicated-p owindow))
5658 ;; This is a special buffer's frame
5659 (iconify-frame (selected-frame))
5660 (or (window-dedicated-p (selected-window))
5663 (or (and (buffer-live-p buffer)
5664 (get-buffer-window buffer))
5666 (choose-completion-string completion buffer base-size)))
5668 ;; Delete the longest partial match for STRING
5669 ;; that can be found before POINT.
5670 (defun choose-completion-delete-max-match (string)
5671 (let ((opoint (point))
5673 ;; Try moving back by the length of the string.
5674 (goto-char (max (- (point) (length string))
5675 (minibuffer-prompt-end)))
5676 ;; See how far back we were actually able to move. That is the
5677 ;; upper bound on how much we can match and delete.
5678 (setq len (- opoint (point)))
5679 (if completion-ignore-case
5680 (setq string (downcase string)))
5681 (while (and (> len 0)
5682 (let ((tail (buffer-substring (point) opoint)))
5683 (if completion-ignore-case
5684 (setq tail (downcase tail)))
5685 (not (string= tail (substring string 0 len)))))
5690 (defvar choose-completion-string-functions nil
5691 "Functions that may override the normal insertion of a completion choice.
5692 These functions are called in order with four arguments:
5693 CHOICE - the string to insert in the buffer,
5694 BUFFER - the buffer in which the choice should be inserted,
5695 MINI-P - non-nil if BUFFER is a minibuffer, and
5696 BASE-SIZE - the number of characters in BUFFER before
5697 the string being completed.
5699 If a function in the list returns non-nil, that function is supposed
5700 to have inserted the CHOICE in the BUFFER, and possibly exited
5701 the minibuffer; no further functions will be called.
5703 If all functions in the list return nil, that means to use
5704 the default method of inserting the completion in BUFFER.")
5706 (defun choose-completion-string (choice &optional buffer base-size)
5707 "Switch to BUFFER and insert the completion choice CHOICE.
5708 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
5709 to keep. If it is nil, we call `choose-completion-delete-max-match'
5710 to decide what to delete."
5712 ;; If BUFFER is the minibuffer, exit the minibuffer
5713 ;; unless it is reading a file name and CHOICE is a directory,
5714 ;; or completion-no-auto-exit is non-nil.
5716 (let* ((buffer (or buffer completion-reference-buffer))
5717 (mini-p (minibufferp buffer)))
5718 ;; If BUFFER is a minibuffer, barf unless it's the currently
5719 ;; active minibuffer.
5721 (or (not (active-minibuffer-window))
5723 (window-buffer (active-minibuffer-window))))))
5724 (error "Minibuffer is not active for completion")
5725 ;; Set buffer so buffer-local choose-completion-string-functions works.
5727 (unless (run-hook-with-args-until-success
5728 'choose-completion-string-functions
5729 choice buffer mini-p base-size)
5730 ;; Insert the completion into the buffer where it was requested.
5732 ;; - There may not be a field at point, or there may be a field but
5733 ;; it's not a "completion field", in which case we have to
5734 ;; call choose-completion-delete-max-match even if base-size is set.
5735 ;; - we may need to delete further than (point) to (field-end),
5736 ;; depending on the completion-style, and for that we need to
5737 ;; extra data `completion-extra-size'.
5739 (delete-region (+ base-size (field-beginning)) (point))
5740 (choose-completion-delete-max-match choice))
5742 (remove-text-properties (- (point) (length choice)) (point)
5744 ;; Update point in the window that BUFFER is showing in.
5745 (let ((window (get-buffer-window buffer t)))
5746 (set-window-point window (point)))
5747 ;; If completing for the minibuffer, exit it with this choice.
5748 (and (not completion-no-auto-exit)
5749 (minibufferp buffer)
5750 minibuffer-completion-table
5751 ;; If this is reading a file name, and the file name chosen
5752 ;; is a directory, don't exit the minibuffer.
5753 (if (and minibuffer-completing-file-name
5754 (file-directory-p (field-string (point-max))))
5755 (let ((mini (active-minibuffer-window)))
5756 (select-window mini)
5757 (when minibuffer-auto-raise
5758 (raise-frame (window-frame mini))))
5759 (exit-minibuffer)))))))
5761 (define-derived-mode completion-list-mode nil "Completion List"
5762 "Major mode for buffers showing lists of possible completions.
5763 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
5764 to select the completion near point.
5765 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
5768 \\{completion-list-mode-map}"
5769 (set (make-local-variable 'completion-base-size) nil))
5771 (defun completion-list-mode-finish ()
5772 "Finish setup of the completions buffer.
5773 Called from `temp-buffer-show-hook'."
5774 (when (eq major-mode 'completion-list-mode)
5775 (toggle-read-only 1)))
5777 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
5780 ;; Variables and faces used in `completion-setup-function'.
5782 (defcustom completion-show-help t
5783 "Non-nil means show help message in *Completions* buffer."
5788 ;; This is for packages that need to bind it to a non-default regexp
5789 ;; in order to make the first-differing character highlight work
5791 (defvar completion-root-regexp "^/"
5792 "Regexp to use in `completion-setup-function' to find the root directory.")
5794 ;; This function goes in completion-setup-hook, so that it is called
5795 ;; after the text of the completion list buffer is written.
5796 (defun completion-setup-function ()
5797 (let* ((mainbuf (current-buffer))
5798 (mbuf-contents (minibuffer-completion-contents))
5799 common-string-length)
5800 ;; When reading a file name in the minibuffer,
5801 ;; set default-directory in the minibuffer
5802 ;; so it will get copied into the completion list buffer.
5803 (if minibuffer-completing-file-name
5804 (with-current-buffer mainbuf
5805 (setq default-directory
5806 (file-name-directory (expand-file-name mbuf-contents)))))
5807 (with-current-buffer standard-output
5808 (let ((base-size completion-base-size)) ;Read before killing localvars.
5809 (completion-list-mode)
5810 (set (make-local-variable 'completion-base-size) base-size))
5811 (set (make-local-variable 'completion-reference-buffer) mainbuf)
5812 (unless completion-base-size
5813 ;; This shouldn't be needed any more, but further analysis is needed
5814 ;; to make sure it's the case.
5815 (setq completion-base-size
5817 (minibuffer-completing-file-name
5818 ;; For file name completion, use the number of chars before
5819 ;; the start of the file name component at point.
5820 (with-current-buffer mainbuf
5822 (skip-chars-backward completion-root-regexp)
5823 (- (point) (minibuffer-prompt-end)))))
5824 (minibuffer-completing-symbol nil)
5825 ;; Otherwise, in minibuffer, the base size is 0.
5826 ((minibufferp mainbuf) 0))))
5827 ;; Maybe insert help string.
5828 (when completion-show-help
5829 (goto-char (point-min))
5830 (if (display-mouse-p)
5831 (insert (substitute-command-keys
5832 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
5833 (insert (substitute-command-keys
5834 "In this buffer, type \\[choose-completion] to \
5835 select the completion near point.\n\n"))))))
5837 (add-hook 'completion-setup-hook 'completion-setup-function)
5839 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
5840 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
5842 (defun switch-to-completions ()
5843 "Select the completion list window."
5845 ;; Make sure we have a completions window.
5846 (or (get-buffer-window "*Completions*")
5847 (minibuffer-completion-help))
5848 (let ((window (get-buffer-window "*Completions*")))
5850 (select-window window)
5851 (goto-char (point-min))
5852 (search-forward "\n\n" nil t)
5855 ;;; Support keyboard commands to turn on various modifiers.
5857 ;; These functions -- which are not commands -- each add one modifier
5858 ;; to the following event.
5860 (defun event-apply-alt-modifier (ignore-prompt)
5861 "\\<function-key-map>Add the Alt modifier to the following event.
5862 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
5863 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
5864 (defun event-apply-super-modifier (ignore-prompt)
5865 "\\<function-key-map>Add the Super modifier to the following event.
5866 For example, type \\[event-apply-super-modifier] & to enter Super-&."
5867 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
5868 (defun event-apply-hyper-modifier (ignore-prompt)
5869 "\\<function-key-map>Add the Hyper modifier to the following event.
5870 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
5871 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
5872 (defun event-apply-shift-modifier (ignore-prompt)
5873 "\\<function-key-map>Add the Shift modifier to the following event.
5874 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
5875 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
5876 (defun event-apply-control-modifier (ignore-prompt)
5877 "\\<function-key-map>Add the Ctrl modifier to the following event.
5878 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
5879 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
5880 (defun event-apply-meta-modifier (ignore-prompt)
5881 "\\<function-key-map>Add the Meta modifier to the following event.
5882 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
5883 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
5885 (defun event-apply-modifier (event symbol lshiftby prefix)
5886 "Apply a modifier flag to event EVENT.
5887 SYMBOL is the name of this modifier, as a symbol.
5888 LSHIFTBY is the numeric value of this modifier, in keyboard events.
5889 PREFIX is the string that represents this modifier in an event type symbol."
5891 (cond ((eq symbol 'control)
5892 (if (and (<= (downcase event) ?z)
5893 (>= (downcase event) ?a))
5894 (- (downcase event) ?a -1)
5895 (if (and (<= (downcase event) ?Z)
5896 (>= (downcase event) ?A))
5897 (- (downcase event) ?A -1)
5898 (logior (lsh 1 lshiftby) event))))
5900 (if (and (<= (downcase event) ?z)
5901 (>= (downcase event) ?a))
5903 (logior (lsh 1 lshiftby) event)))
5905 (logior (lsh 1 lshiftby) event)))
5906 (if (memq symbol (event-modifiers event))
5908 (let ((event-type (if (symbolp event) event (car event))))
5909 (setq event-type (intern (concat prefix (symbol-name event-type))))
5912 (cons event-type (cdr event)))))))
5914 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
5915 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
5916 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
5917 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
5918 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
5919 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
5921 ;;;; Keypad support.
5923 ;; Make the keypad keys act like ordinary typing keys. If people add
5924 ;; bindings for the function key symbols, then those bindings will
5925 ;; override these, so this shouldn't interfere with any existing
5928 ;; Also tell read-char how to handle these keys.
5930 (lambda (keypad-normal)
5931 (let ((keypad (nth 0 keypad-normal))
5932 (normal (nth 1 keypad-normal)))
5933 (put keypad 'ascii-character normal)
5934 (define-key function-key-map (vector keypad) (vector normal))))
5935 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
5936 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
5949 ;;;; forking a twin copy of a buffer.
5952 (defvar clone-buffer-hook nil
5953 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5955 (defvar clone-indirect-buffer-hook nil
5956 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
5958 (defun clone-process (process &optional newname)
5959 "Create a twin copy of PROCESS.
5960 If NEWNAME is nil, it defaults to PROCESS' name;
5961 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5962 If PROCESS is associated with a buffer, the new process will be associated
5963 with the current buffer instead.
5964 Returns nil if PROCESS has already terminated."
5965 (setq newname (or newname (process-name process)))
5966 (if (string-match "<[0-9]+>\\'" newname)
5967 (setq newname (substring newname 0 (match-beginning 0))))
5968 (when (memq (process-status process) '(run stop open))
5969 (let* ((process-connection-type (process-tty-name process))
5971 (if (memq (process-status process) '(open))
5972 (let ((args (process-contact process t)))
5973 (setq args (plist-put args :name newname))
5974 (setq args (plist-put args :buffer
5975 (if (process-buffer process)
5977 (apply 'make-network-process args))
5978 (apply 'start-process newname
5979 (if (process-buffer process) (current-buffer))
5980 (process-command process)))))
5981 (set-process-query-on-exit-flag
5982 new-process (process-query-on-exit-flag process))
5983 (set-process-inherit-coding-system-flag
5984 new-process (process-inherit-coding-system-flag process))
5985 (set-process-filter new-process (process-filter process))
5986 (set-process-sentinel new-process (process-sentinel process))
5987 (set-process-plist new-process (copy-sequence (process-plist process)))
5990 ;; things to maybe add (currently partly covered by `funcall mode'):
5993 (defun clone-buffer (&optional newname display-flag)
5994 "Create and return a twin copy of the current buffer.
5995 Unlike an indirect buffer, the new buffer can be edited
5996 independently of the old one (if it is not read-only).
5997 NEWNAME is the name of the new buffer. It may be modified by
5998 adding or incrementing <N> at the end as necessary to create a
5999 unique buffer name. If nil, it defaults to the name of the
6000 current buffer, with the proper suffix. If DISPLAY-FLAG is
6001 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
6002 clone a file-visiting buffer, or a buffer whose major mode symbol
6003 has a non-nil `no-clone' property, results in an error.
6005 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
6006 current buffer with appropriate suffix. However, if a prefix
6007 argument is given, then the command prompts for NEWNAME in the
6010 This runs the normal hook `clone-buffer-hook' in the new buffer
6011 after it has been set up properly in other respects."
6014 (if buffer-file-name
6015 (error "Cannot clone a file-visiting buffer"))
6016 (if (get major-mode 'no-clone)
6017 (error "Cannot clone a buffer in %s mode" mode-name))
6018 (list (if current-prefix-arg
6019 (read-buffer "Name of new cloned buffer: " (current-buffer)))
6021 (if buffer-file-name
6022 (error "Cannot clone a file-visiting buffer"))
6023 (if (get major-mode 'no-clone)
6024 (error "Cannot clone a buffer in %s mode" mode-name))
6025 (setq newname (or newname (buffer-name)))
6026 (if (string-match "<[0-9]+>\\'" newname)
6027 (setq newname (substring newname 0 (match-beginning 0))))
6028 (let ((buf (current-buffer))
6032 (mk (if mark-active (mark t)))
6033 (modified (buffer-modified-p))
6035 (lvars (buffer-local-variables))
6036 (process (get-buffer-process (current-buffer)))
6037 (new (generate-new-buffer (or newname (buffer-name)))))
6040 (with-current-buffer new
6041 (insert-buffer-substring buf)))
6042 (with-current-buffer new
6043 (narrow-to-region ptmin ptmax)
6045 (if mk (set-mark mk))
6046 (set-buffer-modified-p modified)
6048 ;; Clone the old buffer's process, if any.
6049 (when process (clone-process process))
6051 ;; Now set up the major mode.
6054 ;; Set up other local variables.
6056 (condition-case () ;in case var is read-only
6059 (set (make-local-variable (car v)) (cdr v)))
6063 ;; Run any hooks (typically set up by the major mode
6064 ;; for cloning to work properly).
6065 (run-hooks 'clone-buffer-hook))
6067 ;; Presumably the current buffer is shown in the selected frame, so
6068 ;; we want to display the clone elsewhere.
6069 (let ((same-window-regexps nil)
6070 (same-window-buffer-names))
6071 (pop-to-buffer new)))
6075 (defun clone-indirect-buffer (newname display-flag &optional norecord)
6076 "Create an indirect buffer that is a twin copy of the current buffer.
6078 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
6079 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6080 or if not called with a prefix arg, NEWNAME defaults to the current
6081 buffer's name. The name is modified by adding a `<N>' suffix to it
6082 or by incrementing the N in an existing suffix. Trying to clone a
6083 buffer whose major mode symbol has a non-nil `no-clone-indirect'
6084 property results in an error.
6086 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
6087 This is always done when called interactively.
6089 Optional third arg NORECORD non-nil means do not put this buffer at the
6090 front of the list of recently selected ones."
6093 (if (get major-mode 'no-clone-indirect)
6094 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6095 (list (if current-prefix-arg
6096 (read-buffer "Name of indirect buffer: " (current-buffer)))
6098 (if (get major-mode 'no-clone-indirect)
6099 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6100 (setq newname (or newname (buffer-name)))
6101 (if (string-match "<[0-9]+>\\'" newname)
6102 (setq newname (substring newname 0 (match-beginning 0))))
6103 (let* ((name (generate-new-buffer-name newname))
6104 (buffer (make-indirect-buffer (current-buffer) name t)))
6105 (with-current-buffer buffer
6106 (run-hooks 'clone-indirect-buffer-hook))
6108 (pop-to-buffer buffer norecord))
6112 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6113 "Like `clone-indirect-buffer' but display in another window."
6116 (if (get major-mode 'no-clone-indirect)
6117 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6118 (list (if current-prefix-arg
6119 (read-buffer "Name of indirect buffer: " (current-buffer)))
6121 (let ((pop-up-windows t))
6122 (clone-indirect-buffer newname display-flag norecord)))
6125 ;;; Handling of Backspace and Delete keys.
6127 (defcustom normal-erase-is-backspace 'maybe
6128 "Set the default behavior of the Delete and Backspace keys.
6130 If set to t, Delete key deletes forward and Backspace key deletes
6133 If set to nil, both Delete and Backspace keys delete backward.
6135 If set to 'maybe (which is the default), Emacs automatically
6136 selects a behavior. On window systems, the behavior depends on
6137 the keyboard used. If the keyboard has both a Backspace key and
6138 a Delete key, and both are mapped to their usual meanings, the
6139 option's default value is set to t, so that Backspace can be used
6140 to delete backward, and Delete can be used to delete forward.
6142 If not running under a window system, customizing this option
6143 accomplishes a similar effect by mapping C-h, which is usually
6144 generated by the Backspace key, to DEL, and by mapping DEL to C-d
6145 via `keyboard-translate'. The former functionality of C-h is
6146 available on the F1 key. You should probably not use this
6147 setting if you don't have both Backspace, Delete and F1 keys.
6149 Setting this variable with setq doesn't take effect. Programmatically,
6150 call `normal-erase-is-backspace-mode' (which see) instead."
6151 :type '(choice (const :tag "Off" nil)
6152 (const :tag "Maybe" maybe)
6153 (other :tag "On" t))
6154 :group 'editing-basics
6156 :set (lambda (symbol value)
6157 ;; The fboundp is because of a problem with :set when
6158 ;; dumping Emacs. It doesn't really matter.
6159 (if (fboundp 'normal-erase-is-backspace-mode)
6160 (normal-erase-is-backspace-mode (or value 0))
6161 (set-default symbol value))))
6163 (defun normal-erase-is-backspace-setup-frame (&optional frame)
6164 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6165 (unless frame (setq frame (selected-frame)))
6166 (with-selected-frame frame
6167 (unless (terminal-parameter nil 'normal-erase-is-backspace)
6168 (normal-erase-is-backspace-mode
6169 (if (if (eq normal-erase-is-backspace 'maybe)
6170 (and (not noninteractive)
6171 (or (memq system-type '(ms-dos windows-nt))
6172 (and (memq window-system '(x))
6173 (fboundp 'x-backspace-delete-keys-p)
6174 (x-backspace-delete-keys-p))
6175 ;; If the terminal Emacs is running on has erase char
6176 ;; set to ^H, use the Backspace key for deleting
6177 ;; backward, and the Delete key for deleting forward.
6178 (and (null window-system)
6179 (eq tty-erase-char ?\^H))))
6180 normal-erase-is-backspace)
6183 (defun normal-erase-is-backspace-mode (&optional arg)
6184 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6186 With numeric ARG, turn the mode on if and only if ARG is positive.
6188 On window systems, when this mode is on, Delete is mapped to C-d
6189 and Backspace is mapped to DEL; when this mode is off, both
6190 Delete and Backspace are mapped to DEL. (The remapping goes via
6191 `local-function-key-map', so binding Delete or Backspace in the
6192 global or local keymap will override that.)
6194 In addition, on window systems, the bindings of C-Delete, M-Delete,
6195 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6196 the global keymap in accordance with the functionality of Delete and
6197 Backspace. For example, if Delete is remapped to C-d, which deletes
6198 forward, C-Delete is bound to `kill-word', but if Delete is remapped
6199 to DEL, which deletes backward, C-Delete is bound to
6200 `backward-kill-word'.
6202 If not running on a window system, a similar effect is accomplished by
6203 remapping C-h (normally produced by the Backspace key) and DEL via
6204 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6205 to C-d; if it's off, the keys are not remapped.
6207 When not running on a window system, and this mode is turned on, the
6208 former functionality of C-h is available on the F1 key. You should
6209 probably not turn on this mode on a text-only terminal if you don't
6210 have both Backspace, Delete and F1 keys.
6212 See also `normal-erase-is-backspace'."
6214 (let ((enabled (or (and arg (> (prefix-numeric-value arg) 0))
6216 (not (eq 1 (terminal-parameter
6217 nil 'normal-erase-is-backspace)))))))
6218 (set-terminal-parameter nil 'normal-erase-is-backspace
6221 (cond ((or (memq window-system '(x w32 ns pc))
6222 (memq system-type '(ms-dos windows-nt)))
6224 `(([M-delete] [M-backspace])
6225 ([C-M-delete] [C-M-backspace])
6227 [C-delete] [C-backspace])))
6228 (old-state (lookup-key local-function-key-map [delete])))
6232 (define-key local-function-key-map [delete] [?\C-d])
6233 (define-key local-function-key-map [kp-delete] [?\C-d])
6234 (define-key local-function-key-map [backspace] [?\C-?]))
6235 (define-key local-function-key-map [delete] [?\C-?])
6236 (define-key local-function-key-map [kp-delete] [?\C-?])
6237 (define-key local-function-key-map [backspace] [?\C-?]))
6239 ;; Maybe swap bindings of C-delete and C-backspace, etc.
6240 (unless (equal old-state (lookup-key local-function-key-map [delete]))
6241 (dolist (binding bindings)
6242 (let ((map global-map))
6243 (when (keymapp (car binding))
6244 (setq map (car binding) binding (cdr binding)))
6245 (let* ((key1 (nth 0 binding))
6246 (key2 (nth 1 binding))
6247 (binding1 (lookup-key map key1))
6248 (binding2 (lookup-key map key2)))
6249 (define-key map key1 binding2)
6250 (define-key map key2 binding1)))))))
6254 (keyboard-translate ?\C-h ?\C-?)
6255 (keyboard-translate ?\C-? ?\C-d))
6256 (keyboard-translate ?\C-h ?\C-h)
6257 (keyboard-translate ?\C-? ?\C-?))))
6259 (run-hooks 'normal-erase-is-backspace-hook)
6261 (message "Delete key deletes %s"
6262 (if (terminal-parameter nil 'normal-erase-is-backspace)
6263 "forward" "backward")))))
6265 (defvar vis-mode-saved-buffer-invisibility-spec nil
6266 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
6268 (define-minor-mode visible-mode
6269 "Toggle Visible mode.
6270 With argument ARG turn Visible mode on if ARG is positive, otherwise
6273 Enabling Visible mode makes all invisible text temporarily visible.
6274 Disabling Visible mode turns off that effect. Visible mode works by
6275 saving the value of `buffer-invisibility-spec' and setting it to nil."
6277 :group 'editing-basics
6278 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6279 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6280 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
6282 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6283 buffer-invisibility-spec)
6284 (setq buffer-invisibility-spec nil)))
6286 ;; Partial application of functions (similar to "currying").
6287 (defun apply-partially (fun &rest args)
6288 "Return a function that is a partial application of FUN to ARGS.
6289 ARGS is a list of the first N arguments to pass to FUN.
6290 The result is a new function which does the same as FUN, except that
6291 the first N arguments are fixed at the values with which this function
6293 (lexical-let ((fun fun) (args1 args))
6294 (lambda (&rest args2) (apply fun (append args1 args2)))))
6296 ;; Minibuffer prompt stuff.
6298 ;(defun minibuffer-prompt-modification (start end)
6299 ; (error "You cannot modify the prompt"))
6302 ;(defun minibuffer-prompt-insertion (start end)
6303 ; (let ((inhibit-modification-hooks t))
6304 ; (delete-region start end)
6305 ; ;; Discard undo information for the text insertion itself
6306 ; ;; and for the text deletion.above.
6307 ; (when (consp buffer-undo-list)
6308 ; (setq buffer-undo-list (cddr buffer-undo-list)))
6309 ; (message "You cannot modify the prompt")))
6312 ;(setq minibuffer-prompt-properties
6313 ; (list 'modification-hooks '(minibuffer-prompt-modification)
6314 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
6318 ;;;; Problematic external packages.
6320 ;; rms says this should be done by specifying symbols that define
6321 ;; versions together with bad values. This is therefore not as
6322 ;; flexible as it could be. See the thread:
6323 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6324 (defconst bad-packages-alist
6325 ;; Not sure exactly which semantic versions have problems.
6326 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
6327 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
6328 "The version of `semantic' loaded does not work in Emacs 22.
6329 It can cause constant high CPU load.
6330 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
6331 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6332 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6333 ;; provided the `CUA-mode' feature. Since this is no longer true,
6334 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6336 "CUA-mode is now part of the standard GNU Emacs distribution,
6337 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6339 You have loaded an older version of CUA-mode which does not work
6340 correctly with this version of Emacs. You should remove the old
6341 version and use the one distributed with Emacs."))
6342 "Alist of packages known to cause problems in this version of Emacs.
6343 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6344 PACKAGE is either a regular expression to match file names, or a
6345 symbol (a feature name); see the documentation of
6346 `after-load-alist', to which this variable adds functions.
6347 SYMBOL is either the name of a string variable, or `t'. Upon
6348 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6349 warning using STRING as the message.")
6351 (defun bad-package-check (package)
6352 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6354 (let* ((list (assoc package bad-packages-alist))
6355 (symbol (nth 1 list)))
6359 (and (stringp (setq symbol (eval symbol)))
6360 (string-match-p (nth 2 list) symbol)))
6361 (display-warning package (nth 3 list) :warning)))
6364 (mapc (lambda (elem)
6365 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6371 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
6372 ;;; simple.el ends here