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
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 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; A grab-bag of basic Emacs commands not specifically related to some
30 ;; major mode or to file-handling.
35 (autoload 'widget-convert "wid-edit")
36 (autoload 'shell-mode "shell"))
40 "Killing and yanking commands."
43 (defgroup paren-matching nil
44 "Highlight (un)matching of parens and expressions."
47 (define-key global-map [?\C-x right] 'next-buffer)
48 (define-key global-map [?\C-x left] 'prev-buffer)
50 "Switch to the next buffer in cyclic order."
52 (let ((buffer (current-buffer)))
53 (switch-to-buffer (other-buffer buffer))
54 (bury-buffer buffer)))
57 "Switch to the previous buffer in cyclic order."
59 (let ((list (nreverse (buffer-list)))
61 (while (and (not found) list)
62 (let ((buffer (car list)))
63 (if (and (not (get-buffer-window buffer))
64 (not (string-match "\\` " (buffer-name buffer))))
66 (setq list (cdr list)))
67 (switch-to-buffer found)))
69 ;;; next-error support framework
71 (defgroup next-error nil
72 "next-error support framework."
77 '((t (:inherit region)))
78 "Face used to highlight next error locus."
82 (defcustom next-error-highlight 0.1
83 "*Highlighting of locations in selected source buffers.
84 If number, highlight the locus in next-error face for given time in seconds.
85 If t, use persistent overlays fontified in next-error face.
86 If nil, don't highlight the locus in the source buffer.
87 If `fringe-arrow', indicate the locus by the fringe arrow."
88 :type '(choice (number :tag "Delay")
89 (const :tag "Persistent overlay" t)
90 (const :tag "No highlighting" nil)
91 (const :tag "Fringe arrow" 'fringe-arrow))
95 (defcustom next-error-highlight-no-select 0.1
96 "*Highlighting of locations in non-selected source buffers.
97 If number, highlight the locus in next-error face for given time in seconds.
98 If t, use persistent overlays fontified in next-error face.
99 If nil, don't highlight the locus in the source buffer.
100 If `fringe-arrow', indicate the locus by the fringe arrow."
101 :type '(choice (number :tag "Delay")
102 (const :tag "Persistent overlay" t)
103 (const :tag "No highlighting" nil)
104 (const :tag "Fringe arrow" 'fringe-arrow))
108 (defvar next-error-last-buffer nil
109 "The most recent next-error buffer.
110 A buffer becomes most recent when its compilation, grep, or
111 similar mode is started, or when it is used with \\[next-error]
112 or \\[compile-goto-error].")
114 (defvar next-error-function nil
115 "Function to use to find the next error in the current buffer.
116 The function is called with 2 parameters:
117 ARG is an integer specifying by how many errors to move.
118 RESET is a boolean which, if non-nil, says to go back to the beginning
119 of the errors before moving.
120 Major modes providing compile-like functionality should set this variable
121 to indicate to `next-error' that this is a candidate buffer and how
124 (make-variable-buffer-local 'next-error-function)
126 (defsubst next-error-buffer-p (buffer
127 &optional avoid-current
129 extra-test-exclusive)
130 "Test if BUFFER is a next-error capable buffer.
132 If AVOID-CURRENT is non-nil, treat the current buffer
133 as an absolute last resort only.
135 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
136 that normally would not qualify. If it returns t, the buffer
137 in question is treated as usable.
139 The function EXTRA-TEST-EXCLUSIVE, if non-nil is called in each buffer
140 that would normally be considered usable. if it returns nil,
141 that buffer is rejected."
142 (and (buffer-name buffer) ;First make sure it's live.
143 (not (and avoid-current (eq buffer (current-buffer))))
144 (with-current-buffer buffer
145 (if next-error-function ; This is the normal test.
146 ;; Optionally reject some buffers.
147 (if extra-test-exclusive
148 (funcall extra-test-exclusive)
150 ;; Optionally accept some other buffers.
151 (and extra-test-inclusive
152 (funcall extra-test-inclusive))))))
154 (defun next-error-find-buffer (&optional avoid-current
156 extra-test-exclusive)
157 "Return a next-error capable buffer.
158 If AVOID-CURRENT is non-nil, treat the current buffer
159 as an absolute last resort only.
161 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffers
162 that normally would not qualify. If it returns t, the buffer
163 in question is treated as usable.
165 The function EXTRA-TEST-EXCLUSIVE, if non-nil is called in each buffer
166 that would normally be considered usable. If it returns nil,
167 that buffer is rejected."
169 ;; 1. If one window on the selected frame displays such buffer, return it.
170 (let ((window-buffers
172 (delq nil (mapcar (lambda (w)
173 (if (next-error-buffer-p
176 extra-test-inclusive extra-test-exclusive)
179 (if (eq (length window-buffers) 1)
180 (car window-buffers)))
181 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
182 (if (and next-error-last-buffer
183 (next-error-buffer-p next-error-last-buffer avoid-current
184 extra-test-inclusive extra-test-exclusive))
185 next-error-last-buffer)
186 ;; 3. If the current buffer is acceptable, choose it.
187 (if (next-error-buffer-p (current-buffer) avoid-current
188 extra-test-inclusive extra-test-exclusive)
190 ;; 4. Look for any acceptable buffer.
191 (let ((buffers (buffer-list)))
193 (not (next-error-buffer-p
194 (car buffers) avoid-current
195 extra-test-inclusive extra-test-exclusive)))
196 (setq buffers (cdr buffers)))
198 ;; 5. Use the current buffer as a last resort if it qualifies,
199 ;; even despite AVOID-CURRENT.
201 (next-error-buffer-p (current-buffer) nil
202 extra-test-inclusive extra-test-exclusive)
204 (message "This is the only next-error capable buffer")
207 (error "No next-error capable buffer found")))
209 (defun next-error (&optional arg reset)
210 "Visit next next-error message and corresponding source code.
212 If all the error messages parsed so far have been processed already,
213 the message buffer is checked for new ones.
215 A prefix ARG specifies how many error messages to move;
216 negative means move back to previous error messages.
217 Just \\[universal-argument] as a prefix means reparse the error message buffer
218 and start at the first error.
220 The RESET argument specifies that we should restart from the beginning.
222 \\[next-error] normally uses the most recently started
223 compilation, grep, or occur buffer. It can also operate on any
224 buffer with output from the \\[compile], \\[grep] commands, or,
225 more generally, on any buffer in Compilation mode or with
226 Compilation Minor mode enabled, or any buffer in which
227 `next-error-function' is bound to an appropriate function.
228 To specify use of a particular buffer for error messages, type
229 \\[next-error] in that buffer when it is the only one displayed
230 in the current frame.
232 Once \\[next-error] has chosen the buffer for error messages,
233 it stays with that buffer until you use it in some other buffer which
234 uses Compilation mode or Compilation Minor mode.
236 See variables `compilation-parse-errors-function' and
237 \`compilation-error-regexp-alist' for customization ideas."
239 (if (consp arg) (setq reset t arg nil))
240 (when (setq next-error-last-buffer (next-error-find-buffer))
241 ;; we know here that next-error-function is a valid symbol we can funcall
242 (with-current-buffer next-error-last-buffer
243 (funcall next-error-function (prefix-numeric-value arg) reset))))
245 (defalias 'goto-next-locus 'next-error)
246 (defalias 'next-match 'next-error)
248 (define-key ctl-x-map "`" 'next-error)
250 (defun previous-error (&optional n)
251 "Visit previous next-error message and corresponding source code.
253 Prefix arg N says how many error messages to move backwards (or
254 forwards, if negative).
256 This operates on the output from the \\[compile] and \\[grep] commands."
258 (next-error (- (or n 1))))
260 (defun first-error (&optional n)
261 "Restart at the first error.
262 Visit corresponding source code.
263 With prefix arg N, visit the source code of the Nth error.
264 This operates on the output from the \\[compile] command, for instance."
268 (defun next-error-no-select (&optional n)
269 "Move point to the next error in the next-error buffer and highlight match.
270 Prefix arg N says how many error messages to move forwards (or
271 backwards, if negative).
272 Finds and highlights the source line like \\[next-error], but does not
273 select the source buffer."
275 (let ((next-error-highlight next-error-highlight-no-select))
277 (pop-to-buffer next-error-last-buffer))
279 (defun previous-error-no-select (&optional n)
280 "Move point to the previous error in the next-error buffer and highlight match.
281 Prefix arg N says how many error messages to move backwards (or
282 forwards, if negative).
283 Finds and highlights the source line like \\[previous-error], but does not
284 select the source buffer."
286 (next-error-no-select (- (or n 1))))
288 ;;; Internal variable for `next-error-follow-mode-post-command-hook'.
289 (defvar next-error-follow-last-line nil)
291 (define-minor-mode next-error-follow-minor-mode
292 "Minor mode for compilation, occur and diff modes.
293 When turned on, cursor motion in the compilation, grep, occur or diff
294 buffer causes automatic display of the corresponding source code
297 (if (not next-error-follow-minor-mode)
298 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
299 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
300 (make-variable-buffer-local 'next-error-follow-last-line)))
302 ;;; Used as a `post-command-hook' by `next-error-follow-mode'
303 ;;; for the *Compilation* *grep* and *Occur* buffers.
304 (defun next-error-follow-mode-post-command-hook ()
305 (unless (equal next-error-follow-last-line (line-number-at-pos))
306 (setq next-error-follow-last-line (line-number-at-pos))
308 (let ((compilation-context-lines nil))
309 (setq compilation-current-error (point))
310 (next-error-no-select 0))
316 (defun fundamental-mode ()
317 "Major mode not specialized for anything in particular.
318 Other major modes are defined by comparison with this one."
320 (kill-all-local-variables)
321 (run-hooks 'after-change-major-mode-hook))
323 ;; Making and deleting lines.
325 (defun newline (&optional arg)
326 "Insert a newline, and move to left margin of the new line if it's blank.
327 If `use-hard-newlines' is non-nil, the newline is marked with the
328 text-property `hard'.
329 With ARG, insert that many newlines.
330 Call `auto-fill-function' if the current column number is greater
331 than the value of `fill-column' and ARG is nil."
333 (barf-if-buffer-read-only)
334 ;; Inserting a newline at the end of a line produces better redisplay in
335 ;; try_window_id than inserting at the beginning of a line, and the textual
336 ;; result is the same. So, if we're at beginning of line, pretend to be at
337 ;; the end of the previous line.
338 (let ((flag (and (not (bobp))
340 ;; Make sure no functions want to be told about
341 ;; the range of the changes.
342 (not after-change-functions)
343 (not before-change-functions)
344 ;; Make sure there are no markers here.
345 (not (buffer-has-markers-at (1- (point))))
346 (not (buffer-has-markers-at (point)))
347 ;; Make sure no text properties want to know
348 ;; where the change was.
349 (not (get-char-property (1- (point)) 'modification-hooks))
350 (not (get-char-property (1- (point)) 'insert-behind-hooks))
352 (not (get-char-property (point) 'insert-in-front-hooks)))
353 ;; Make sure the newline before point isn't intangible.
354 (not (get-char-property (1- (point)) 'intangible))
355 ;; Make sure the newline before point isn't read-only.
356 (not (get-char-property (1- (point)) 'read-only))
357 ;; Make sure the newline before point isn't invisible.
358 (not (get-char-property (1- (point)) 'invisible))
359 ;; Make sure the newline before point has the same
360 ;; properties as the char before it (if any).
361 (< (or (previous-property-change (point)) -2)
363 (was-page-start (and (bolp)
364 (looking-at page-delimiter)))
366 (if flag (backward-char 1))
367 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
368 ;; Set last-command-char to tell self-insert what to insert.
369 (let ((last-command-char ?\n)
370 ;; Don't auto-fill if we have a numeric argument.
371 ;; Also not if flag is true (it would fill wrong line);
372 ;; there is no need to since we're at BOL.
373 (auto-fill-function (if (or arg flag) nil auto-fill-function)))
375 (self-insert-command (prefix-numeric-value arg))
376 ;; If we get an error in self-insert-command, put point at right place.
377 (if flag (forward-char 1))))
378 ;; Even if we did *not* get an error, keep that forward-char;
379 ;; all further processing should apply to the newline that the user
380 ;; thinks he inserted.
382 ;; Mark the newline(s) `hard'.
383 (if use-hard-newlines
384 (set-hard-newline-properties
385 (- (point) (if arg (prefix-numeric-value arg) 1)) (point)))
386 ;; If the newline leaves the previous line blank,
387 ;; and we have a left margin, delete that from the blank line.
390 (goto-char beforepos)
392 (and (looking-at "[ \t]$")
393 (> (current-left-margin) 0)
394 (delete-region (point) (progn (end-of-line) (point))))))
395 ;; Indent the line after the newline, except in one case:
396 ;; when we added the newline at the beginning of a line
397 ;; which starts a page.
399 (move-to-left-margin nil t)))
402 (defun set-hard-newline-properties (from to)
403 (let ((sticky (get-text-property from 'rear-nonsticky)))
404 (put-text-property from to 'hard 't)
405 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
406 (if (and (listp sticky) (not (memq 'hard sticky)))
407 (put-text-property from (point) 'rear-nonsticky
408 (cons 'hard sticky)))))
411 "Insert a newline and leave point before it.
412 If there is a fill prefix and/or a left-margin, insert them on the new line
413 if the line would have been blank.
414 With arg N, insert N newlines."
416 (let* ((do-fill-prefix (and fill-prefix (bolp)))
417 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
419 ;; Don't expand an abbrev before point.
425 (if do-left-margin (indent-to (current-left-margin)))
426 (if do-fill-prefix (insert-and-inherit fill-prefix))))
432 (defun split-line (&optional arg)
433 "Split current line, moving portion beyond point vertically down.
434 If the current line starts with `fill-prefix', insert it on the new
435 line as well. With prefix ARG, don't insert fill-prefix on new line.
437 When called from Lisp code, ARG may be a prefix string to copy."
439 (skip-chars-forward " \t")
440 (let* ((col (current-column))
442 ;; What prefix should we check for (nil means don't).
443 (prefix (cond ((stringp arg) arg)
446 ;; Does this line start with it?
447 (have-prfx (and prefix
450 (looking-at (regexp-quote prefix))))))
452 (if have-prfx (insert-and-inherit prefix))
456 (defun delete-indentation (&optional arg)
457 "Join this line to previous and fix up whitespace at join.
458 If there is a fill prefix, delete it from the beginning of this line.
459 With argument, join this line to following line."
462 (if arg (forward-line 1))
463 (if (eq (preceding-char) ?\n)
465 (delete-region (point) (1- (point)))
466 ;; If the second line started with the fill prefix,
467 ;; delete the prefix.
469 (<= (+ (point) (length fill-prefix)) (point-max))
471 (buffer-substring (point)
472 (+ (point) (length fill-prefix)))))
473 (delete-region (point) (+ (point) (length fill-prefix))))
474 (fixup-whitespace))))
476 (defalias 'join-line #'delete-indentation) ; easier to find
478 (defun delete-blank-lines ()
479 "On blank line, delete all surrounding blank lines, leaving just one.
480 On isolated blank line, delete that one.
481 On nonblank line, delete any immediately following blank lines."
483 (let (thisblank singleblank)
486 (setq thisblank (looking-at "[ \t]*$"))
487 ;; Set singleblank if there is just one blank line here.
490 (not (looking-at "[ \t]*\n[ \t]*$"))
492 (progn (forward-line -1)
493 (not (looking-at "[ \t]*$")))))))
494 ;; Delete preceding blank lines, and this one too if it's the only one.
498 (if singleblank (forward-line 1))
499 (delete-region (point)
500 (if (re-search-backward "[^ \t\n]" nil t)
501 (progn (forward-line 1) (point))
503 ;; Delete following blank lines, unless the current line is blank
504 ;; and there are no following blank lines.
505 (if (not (and thisblank singleblank))
509 (delete-region (point)
510 (if (re-search-forward "[^ \t\n]" nil t)
511 (progn (beginning-of-line) (point))
513 ;; Handle the special case where point is followed by newline and eob.
514 ;; Delete the line, leaving point at eob.
515 (if (looking-at "^[ \t]*\n\\'")
516 (delete-region (point) (point-max)))))
518 (defun delete-trailing-whitespace ()
519 "Delete all the trailing whitespace across the current buffer.
520 All whitespace after the last non-whitespace character in a line is deleted.
521 This respects narrowing, created by \\[narrow-to-region] and friends.
522 A formfeed is not considered whitespace by this function."
526 (goto-char (point-min))
527 (while (re-search-forward "\\s-$" nil t)
528 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
529 ;; Don't delete formfeeds, even if they are considered whitespace.
531 (if (looking-at ".*\f")
532 (goto-char (match-end 0))))
533 (delete-region (point) (match-end 0))))))
535 (defun newline-and-indent ()
536 "Insert a newline, then indent according to major mode.
537 Indentation is done using the value of `indent-line-function'.
538 In programming language modes, this is the same as TAB.
539 In some text modes, where TAB inserts a tab, this command indents to the
540 column specified by the function `current-left-margin'."
542 (delete-horizontal-space t)
544 (indent-according-to-mode))
546 (defun reindent-then-newline-and-indent ()
547 "Reindent current line, insert newline, then indent the new line.
548 Indentation of both lines is done according to the current major mode,
549 which means calling the current value of `indent-line-function'.
550 In programming language modes, this is the same as TAB.
551 In some text modes, where TAB inserts a tab, this indents to the
552 column specified by the function `current-left-margin'."
555 ;; Be careful to insert the newline before indenting the line.
556 ;; Otherwise, the indentation might be wrong.
560 (indent-according-to-mode)
561 (delete-horizontal-space t))
562 (indent-according-to-mode)))
564 (defun quoted-insert (arg)
565 "Read next input character and insert it.
566 This is useful for inserting control characters.
568 If the first character you type after this command is an octal digit,
569 you should type a sequence of octal digits which specify a character code.
570 Any nondigit terminates the sequence. If the terminator is a RET,
571 it is discarded; any other terminator is used itself as input.
572 The variable `read-quoted-char-radix' specifies the radix for this feature;
573 set it to 10 or 16 to use decimal or hex instead of octal.
575 In overwrite mode, this function inserts the character anyway, and
576 does not handle octal digits specially. This means that if you use
577 overwrite as your normal editing mode, you can use this function to
578 insert characters when necessary.
580 In binary overwrite mode, this function does overwrite, and octal
581 digits are interpreted as a character code. This is intended to be
582 useful for editing binary files."
584 (let* ((char (let (translation-table-for-input)
585 (if (or (not overwrite-mode)
586 (eq overwrite-mode 'overwrite-mode-binary))
589 ;; Assume character codes 0240 - 0377 stand for characters in some
590 ;; single-byte character set, and convert them to Emacs
592 (if (and enable-multibyte-characters
595 (setq char (unibyte-char-to-multibyte char)))
597 (if (eq overwrite-mode 'overwrite-mode-binary)
600 (insert-and-inherit char)
601 (setq arg (1- arg)))))
603 (defun forward-to-indentation (&optional arg)
604 "Move forward ARG lines and position at first nonblank character."
606 (forward-line (or arg 1))
607 (skip-chars-forward " \t"))
609 (defun backward-to-indentation (&optional arg)
610 "Move backward ARG lines and position at first nonblank character."
612 (forward-line (- (or arg 1)))
613 (skip-chars-forward " \t"))
615 (defun back-to-indentation ()
616 "Move point to the first non-whitespace character on this line."
618 (beginning-of-line 1)
619 (skip-syntax-forward " " (line-end-position))
620 ;; Move back over chars that have whitespace syntax but have the p flag.
621 (backward-prefix-chars))
623 (defun fixup-whitespace ()
624 "Fixup white space between objects around point.
625 Leave one space or none, according to the context."
628 (delete-horizontal-space)
629 (if (or (looking-at "^\\|\\s)")
630 (save-excursion (forward-char -1)
631 (looking-at "$\\|\\s(\\|\\s'")))
635 (defun delete-horizontal-space (&optional backward-only)
636 "Delete all spaces and tabs around point.
637 If BACKWARD-ONLY is non-nil, only delete spaces before point."
639 (let ((orig-pos (point)))
644 (skip-chars-forward " \t")
645 (constrain-to-field nil orig-pos t)))
647 (skip-chars-backward " \t")
648 (constrain-to-field nil orig-pos)))))
650 (defun just-one-space (&optional n)
651 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
653 (let ((orig-pos (point)))
654 (skip-chars-backward " \t")
655 (constrain-to-field nil orig-pos)
656 (dotimes (i (or n 1))
657 (if (= (following-char) ?\ )
663 (skip-chars-forward " \t")
664 (constrain-to-field nil orig-pos t)))))
666 (defun beginning-of-buffer (&optional arg)
667 "Move point to the beginning of the buffer; leave mark at previous position.
668 With \\[universal-argument] prefix, do not set mark at previous position.
669 With numeric arg N, put point N/10 of the way from the beginning.
671 If the buffer is narrowed, this command uses the beginning and size
672 of the accessible part of the buffer.
674 Don't use this command in Lisp programs!
675 \(goto-char (point-min)) is faster and avoids clobbering the mark."
678 (and transient-mark-mode mark-active)
680 (let ((size (- (point-max) (point-min))))
681 (goto-char (if (and arg (not (consp arg)))
684 ;; Avoid overflow for large buffer sizes!
685 (* (prefix-numeric-value arg)
687 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
689 (if arg (forward-line 1)))
691 (defun end-of-buffer (&optional arg)
692 "Move point to the end of the buffer; leave mark at previous position.
693 With \\[universal-argument] prefix, do not set mark at previous position.
694 With numeric arg N, put point N/10 of the way from the end.
696 If the buffer is narrowed, this command uses the beginning and size
697 of the accessible part of the buffer.
699 Don't use this command in Lisp programs!
700 \(goto-char (point-max)) is faster and avoids clobbering the mark."
703 (and transient-mark-mode mark-active)
705 (let ((size (- (point-max) (point-min))))
706 (goto-char (if (and arg (not (consp arg)))
709 ;; Avoid overflow for large buffer sizes!
710 (* (prefix-numeric-value arg)
712 (/ (* size (prefix-numeric-value arg)) 10)))
714 ;; If we went to a place in the middle of the buffer,
715 ;; adjust it to the beginning of a line.
716 (cond (arg (forward-line 1))
717 ((> (point) (window-end nil t))
718 ;; If the end of the buffer is not already on the screen,
719 ;; then scroll specially to put it near, but not at, the bottom.
720 (overlay-recenter (point))
723 (defun mark-whole-buffer ()
724 "Put point at beginning and mark at end of buffer.
725 You probably should not use this function in Lisp programs;
726 it is usually a mistake for a Lisp function to use any subroutine
727 that uses or sets the mark."
730 (push-mark (point-max) nil t)
731 (goto-char (point-min)))
734 ;; Counting lines, one way or another.
736 (defun goto-line (arg)
737 "Goto line ARG, counting from line 1 at beginning of buffer."
738 (interactive "NGoto line: ")
739 (setq arg (prefix-numeric-value arg))
743 (if (eq selective-display t)
744 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
745 (forward-line (1- arg)))))
747 (defun count-lines-region (start end)
748 "Print number of lines and characters in the region."
750 (message "Region has %d lines, %d characters"
751 (count-lines start end) (- end start)))
754 "Print the current buffer line number and narrowed line number of point."
756 (let ((start (point-min))
757 (n (line-number-at-pos)))
759 (message "Line %d" n)
763 (message "line %d (narrowed line %d)"
764 (+ n (line-number-at-pos start) -1) n))))))
766 (defun count-lines (start end)
767 "Return number of lines between START and END.
768 This is usually the number of newlines between them,
769 but can be one more if START is not equal to END
770 and the greater of them is not at the start of a line."
773 (narrow-to-region start end)
774 (goto-char (point-min))
775 (if (eq selective-display t)
778 (while (re-search-forward "[\n\C-m]" nil t 40)
779 (setq done (+ 40 done)))
780 (while (re-search-forward "[\n\C-m]" nil t 1)
781 (setq done (+ 1 done)))
782 (goto-char (point-max))
783 (if (and (/= start end)
787 (- (buffer-size) (forward-line (buffer-size)))))))
789 (defun line-number-at-pos (&optional pos)
790 "Return (narrowed) buffer line number at position POS.
791 If POS is nil, use current buffer location."
792 (let ((opoint (or pos (point))) start)
794 (goto-char (point-min))
798 (1+ (count-lines start (point))))))
800 (defun what-cursor-position (&optional detail)
801 "Print info on cursor position (on screen and within buffer).
802 Also describe the character after point, and give its character code
803 in octal, decimal and hex.
805 For a non-ASCII multibyte character, also give its encoding in the
806 buffer's selected coding system if the coding system encodes the
807 character safely. If the character is encoded into one byte, that
808 code is shown in hex. If the character is encoded into more than one
809 byte, just \"...\" is shown.
811 In addition, with prefix argument, show details about that character
812 in *Help* buffer. See also the command `describe-char'."
814 (let* ((char (following-char))
818 (total (buffer-size))
819 (percent (if (> total 50000)
820 ;; Avoid overflow from multiplying by 100!
821 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
822 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
823 (hscroll (if (= (window-hscroll) 0)
825 (format " Hscroll=%d" (window-hscroll))))
826 (col (current-column)))
828 (if (or (/= beg 1) (/= end (1+ total)))
829 (message "point=%d of %d (%d%%) <%d - %d> column %d %s"
830 pos total percent beg end col hscroll)
831 (message "point=%d of %d (%d%%) column %d %s"
832 pos total percent col hscroll))
833 (let ((coding buffer-file-coding-system)
834 encoded encoding-msg)
836 (eq (coding-system-type coding) t))
837 (setq coding default-buffer-file-coding-system))
838 (if (not (char-valid-p char))
840 (format "(0%o, %d, 0x%x, invalid)" char char char))
841 (setq encoded (and (>= char 128) (encode-coding-char char coding)))
844 (format "(0%o, %d, 0x%x, file %s)"
846 (if (> (length encoded) 1)
848 (encoded-string-description encoded coding)))
849 (format "(0%o, %d, 0x%x)" char char char))))
851 ;; We show the detailed information about CHAR.
852 (describe-char (point)))
853 (if (or (/= beg 1) (/= end (1+ total)))
854 (message "Char: %s %s point=%d of %d (%d%%) <%d - %d> column %d %s"
856 (single-key-description char)
857 (buffer-substring-no-properties (point) (1+ (point))))
858 encoding-msg pos total percent beg end col hscroll)
859 (message "Char: %s %s point=%d of %d (%d%%) column %d %s"
861 (single-key-description char)
862 (buffer-substring-no-properties (point) (1+ (point))))
863 encoding-msg pos total percent col hscroll))))))
865 (defvar read-expression-map
866 (let ((m (make-sparse-keymap)))
867 (define-key m "\M-\t" 'lisp-complete-symbol)
868 (set-keymap-parent m minibuffer-local-map)
870 "Minibuffer keymap used for reading Lisp expressions.")
872 (defvar read-expression-history nil)
874 (defcustom eval-expression-print-level 4
875 "*Value to use for `print-level' when printing value in `eval-expression'.
876 A value of nil means no limit."
878 :type '(choice (const :tag "No Limit" nil) integer)
881 (defcustom eval-expression-print-length 12
882 "*Value to use for `print-length' when printing value in `eval-expression'.
883 A value of nil means no limit."
885 :type '(choice (const :tag "No Limit" nil) integer)
888 (defcustom eval-expression-debug-on-error t
889 "*Non-nil means set `debug-on-error' when evaluating in `eval-expression'.
890 If nil, don't change the value of `debug-on-error'."
895 (defun eval-expression-print-format (value)
896 "Format VALUE as a result of evaluated expression.
897 Return a formatted string which is displayed in the echo area
898 in addition to the value printed by prin1 in functions which
899 display the result of expression evaluation."
900 (if (and (integerp value)
901 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
902 (eq this-command last-command)
903 (if (boundp 'edebug-active) edebug-active)))
905 (if (or (if (boundp 'edebug-active) edebug-active)
906 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
907 (prin1-char value))))
909 (format " (0%o, 0x%x) = %s" value value char-string)
910 (format " (0%o, 0x%x)" value value)))))
912 ;; We define this, rather than making `eval' interactive,
913 ;; for the sake of completion of names like eval-region, eval-current-buffer.
914 (defun eval-expression (eval-expression-arg
915 &optional eval-expression-insert-value)
916 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
917 Value is also consed on to front of the variable `values'.
918 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
919 insert the result into the current buffer instead of printing it in
922 (list (read-from-minibuffer "Eval: "
923 nil read-expression-map t
924 'read-expression-history)
927 (if (null eval-expression-debug-on-error)
928 (setq values (cons (eval eval-expression-arg) values))
929 (let ((old-value (make-symbol "t")) new-value)
930 ;; Bind debug-on-error to something unique so that we can
931 ;; detect when evaled code changes it.
932 (let ((debug-on-error old-value))
933 (setq values (cons (eval eval-expression-arg) values))
934 (setq new-value debug-on-error))
935 ;; If evaled code has changed the value of debug-on-error,
936 ;; propagate that change to the global binding.
937 (unless (eq old-value new-value)
938 (setq debug-on-error new-value))))
940 (let ((print-length eval-expression-print-length)
941 (print-level eval-expression-print-level))
942 (if eval-expression-insert-value
944 (let ((standard-output (current-buffer)))
945 (eval-last-sexp-print-value (car values))))
947 (prin1 (car values) t)
948 (let ((str (eval-expression-print-format (car values))))
949 (if str (princ str t)))))))
951 (defun edit-and-eval-command (prompt command)
952 "Prompting with PROMPT, let user edit COMMAND and eval result.
953 COMMAND is a Lisp expression. Let user edit that expression in
954 the minibuffer, then read and evaluate the result."
956 (let ((print-level nil)
957 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
959 (read-from-minibuffer prompt
960 (prin1-to-string command)
961 read-expression-map t
963 ;; If command was added to command-history as a string,
964 ;; get rid of that. We want only evaluable expressions there.
965 (if (stringp (car command-history))
966 (setq command-history (cdr command-history)))))))
968 ;; If command to be redone does not match front of history,
969 ;; add it to the history.
970 (or (equal command (car command-history))
971 (setq command-history (cons command command-history)))
974 (defun repeat-complex-command (arg)
975 "Edit and re-evaluate last complex command, or ARGth from last.
976 A complex command is one which used the minibuffer.
977 The command is placed in the minibuffer as a Lisp form for editing.
978 The result is executed, repeating the command as changed.
979 If the command has been changed or is not the most recent previous command
980 it is added to the front of the command history.
981 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
982 to get different commands to edit and resubmit."
984 (let ((elt (nth (1- arg) command-history))
989 (let ((print-level nil)
990 (minibuffer-history-position arg)
991 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
993 (read-from-minibuffer
994 "Redo: " (prin1-to-string elt) read-expression-map t
995 (cons 'command-history arg))
997 ;; If command was added to command-history as a
998 ;; string, get rid of that. We want only
999 ;; evaluable expressions there.
1000 (if (stringp (car command-history))
1001 (setq command-history (cdr command-history))))))
1003 ;; If command to be redone does not match front of history,
1004 ;; add it to the history.
1005 (or (equal newcmd (car command-history))
1006 (setq command-history (cons newcmd command-history)))
1009 (error "Argument %d is beyond length of command history" arg)
1010 (error "There are no previous complex commands to repeat")))))
1012 (defvar minibuffer-history nil
1013 "Default minibuffer history list.
1014 This is used for all minibuffer input
1015 except when an alternate history list is specified.")
1016 (defvar minibuffer-history-sexp-flag nil
1017 "Control whether history list elements are expressions or strings.
1018 If the value of this variable equals current minibuffer depth,
1019 they are expressions; otherwise they are strings.
1020 \(That convention is designed to do the right thing fora
1021 recursive uses of the minibuffer.)")
1022 (setq minibuffer-history-variable 'minibuffer-history)
1023 (setq minibuffer-history-position nil)
1024 (defvar minibuffer-history-search-history nil)
1026 (defvar minibuffer-text-before-history nil
1027 "Text that was in this minibuffer before any history commands.
1028 This is nil if there have not yet been any history commands
1029 in this use of the minibuffer.")
1031 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1033 (defun minibuffer-history-initialize ()
1034 (setq minibuffer-text-before-history nil))
1036 (defun minibuffer-avoid-prompt (new old)
1037 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1038 (constrain-to-field nil (point-max)))
1040 (defcustom minibuffer-history-case-insensitive-variables nil
1041 "*Minibuffer history variables for which matching should ignore case.
1042 If a history variable is a member of this list, then the
1043 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1044 commands ignore case when searching it, regardless of `case-fold-search'."
1045 :type '(repeat variable)
1048 (defun previous-matching-history-element (regexp n)
1049 "Find the previous history element that matches REGEXP.
1050 \(Previous history elements refer to earlier actions.)
1051 With prefix argument N, search for Nth previous match.
1052 If N is negative, find the next or Nth next match.
1053 Normally, history elements are matched case-insensitively if
1054 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1055 makes the search case-sensitive.
1056 See also `minibuffer-history-case-insensitive-variables'."
1058 (let* ((enable-recursive-minibuffers t)
1059 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1061 minibuffer-local-map
1063 'minibuffer-history-search-history
1064 (car minibuffer-history-search-history))))
1065 ;; Use the last regexp specified, by default, if input is empty.
1066 (list (if (string= regexp "")
1067 (if minibuffer-history-search-history
1068 (car minibuffer-history-search-history)
1069 (error "No previous history search regexp"))
1071 (prefix-numeric-value current-prefix-arg))))
1073 (if (and (zerop minibuffer-history-position)
1074 (null minibuffer-text-before-history))
1075 (setq minibuffer-text-before-history
1076 (minibuffer-contents-no-properties)))
1077 (let ((history (symbol-value minibuffer-history-variable))
1079 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1080 ;; On some systems, ignore case for file names.
1081 (if (memq minibuffer-history-variable
1082 minibuffer-history-case-insensitive-variables)
1084 ;; Respect the user's setting for case-fold-search:
1090 (pos minibuffer-history-position))
1093 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1094 (when (= pos prevpos)
1095 (error (if (= pos 1)
1096 "No later matching history item"
1097 "No earlier matching history item")))
1099 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1100 (let ((print-level nil))
1101 (prin1-to-string (nth (1- pos) history)))
1102 (nth (1- pos) history)))
1105 (and (string-match regexp match-string)
1107 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1108 (match-beginning 1))))
1110 (setq n (+ n (if (< n 0) 1 -1)))))
1111 (setq minibuffer-history-position pos)
1112 (goto-char (point-max))
1113 (delete-minibuffer-contents)
1114 (insert match-string)
1115 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1116 (if (memq (car (car command-history)) '(previous-matching-history-element
1117 next-matching-history-element))
1118 (setq command-history (cdr command-history))))
1120 (defun next-matching-history-element (regexp n)
1121 "Find the next history element that matches REGEXP.
1122 \(The next history element refers to a more recent action.)
1123 With prefix argument N, search for Nth next match.
1124 If N is negative, find the previous or Nth previous match.
1125 Normally, history elements are matched case-insensitively if
1126 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1127 makes the search case-sensitive."
1129 (let* ((enable-recursive-minibuffers t)
1130 (regexp (read-from-minibuffer "Next element matching (regexp): "
1132 minibuffer-local-map
1134 'minibuffer-history-search-history
1135 (car minibuffer-history-search-history))))
1136 ;; Use the last regexp specified, by default, if input is empty.
1137 (list (if (string= regexp "")
1138 (if minibuffer-history-search-history
1139 (car minibuffer-history-search-history)
1140 (error "No previous history search regexp"))
1142 (prefix-numeric-value current-prefix-arg))))
1143 (previous-matching-history-element regexp (- n)))
1145 (defvar minibuffer-temporary-goal-position nil)
1147 (defun next-history-element (n)
1148 "Insert the next element of the minibuffer history into the minibuffer."
1151 (let ((narg (- minibuffer-history-position n))
1152 (minimum (if minibuffer-default -1 0))
1153 elt minibuffer-returned-to-present)
1154 (if (and (zerop minibuffer-history-position)
1155 (null minibuffer-text-before-history))
1156 (setq minibuffer-text-before-history
1157 (minibuffer-contents-no-properties)))
1158 (if (< narg minimum)
1159 (if minibuffer-default
1160 (error "End of history; no next item")
1161 (error "End of history; no default available")))
1162 (if (> narg (length (symbol-value minibuffer-history-variable)))
1163 (error "Beginning of history; no preceding item"))
1164 (unless (memq last-command '(next-history-element
1165 previous-history-element))
1166 (let ((prompt-end (minibuffer-prompt-end)))
1167 (set (make-local-variable 'minibuffer-temporary-goal-position)
1168 (cond ((<= (point) prompt-end) prompt-end)
1171 (goto-char (point-max))
1172 (delete-minibuffer-contents)
1173 (setq minibuffer-history-position narg)
1175 (setq elt minibuffer-default))
1177 (setq elt (or minibuffer-text-before-history ""))
1178 (setq minibuffer-returned-to-present t)
1179 (setq minibuffer-text-before-history nil))
1180 (t (setq elt (nth (1- minibuffer-history-position)
1181 (symbol-value minibuffer-history-variable)))))
1183 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1184 (not minibuffer-returned-to-present))
1185 (let ((print-level nil))
1186 (prin1-to-string elt))
1188 (goto-char (or minibuffer-temporary-goal-position (point-max))))))
1190 (defun previous-history-element (n)
1191 "Inserts the previous element of the minibuffer history into the minibuffer."
1193 (next-history-element (- n)))
1195 (defun next-complete-history-element (n)
1196 "Get next history element which completes the minibuffer before the point.
1197 The contents of the minibuffer after the point are deleted, and replaced
1198 by the new completion."
1200 (let ((point-at-start (point)))
1201 (next-matching-history-element
1203 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1205 ;; next-matching-history-element always puts us at (point-min).
1206 ;; Move to the position we were at before changing the buffer contents.
1207 ;; This is still sensical, because the text before point has not changed.
1208 (goto-char point-at-start)))
1210 (defun previous-complete-history-element (n)
1212 Get previous history element which completes the minibuffer before the point.
1213 The contents of the minibuffer after the point are deleted, and replaced
1214 by the new completion."
1216 (next-complete-history-element (- n)))
1218 ;; For compatibility with the old subr of the same name.
1219 (defun minibuffer-prompt-width ()
1220 "Return the display width of the minibuffer prompt.
1221 Return 0 if current buffer is not a mini-buffer."
1222 ;; Return the width of everything before the field at the end of
1223 ;; the buffer; this should be 0 for normal buffers.
1224 (1- (minibuffer-prompt-end)))
1226 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1227 (defalias 'advertised-undo 'undo)
1229 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1230 "Table mapping redo records to the corresponding undo one.")
1232 (defvar undo-in-region nil
1233 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1235 (defvar undo-no-redo nil
1236 "If t, `undo' doesn't go through redo entries.")
1238 (defvar pending-undo-list nil
1239 "Within a run of consecutive undo commands, list remaining to be undone.
1240 t if we undid all the way to the end of it.")
1242 (defun undo (&optional arg)
1243 "Undo some previous changes.
1244 Repeat this command to undo more changes.
1245 A numeric argument serves as a repeat count.
1247 In Transient Mark mode when the mark is active, only undo changes within
1248 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1249 as an argument limits undo to changes within the current region."
1251 ;; Make last-command indicate for the next command that this was an undo.
1252 ;; That way, another undo will undo more.
1253 ;; If we get to the end of the undo history and get an error,
1254 ;; another undo command will find the undo history empty
1255 ;; and will get another error. To begin undoing the undos,
1256 ;; you must type some other command.
1257 (let ((modified (buffer-modified-p))
1258 (recent-save (recent-auto-save-p)))
1259 ;; If we get an error in undo-start,
1260 ;; the next command should not be a "consecutive undo".
1261 ;; So set `this-command' to something other than `undo'.
1262 (setq this-command 'undo-start)
1264 (unless (and (eq last-command 'undo)
1265 (or (eq pending-undo-list t)
1266 ;; If something (a timer or filter?) changed the buffer
1267 ;; since the previous command, don't continue the undo seq.
1268 (let ((list buffer-undo-list))
1269 (while (eq (car list) nil)
1270 (setq list (cdr list)))
1271 ;; If the last undo record made was made by undo
1272 ;; it shows nothing else happened in between.
1273 (gethash list undo-equiv-table))))
1274 (setq undo-in-region
1275 (if transient-mark-mode mark-active (and arg (not (numberp arg)))))
1277 (undo-start (region-beginning) (region-end))
1279 ;; get rid of initial undo boundary
1281 ;; If we got this far, the next command should be a consecutive undo.
1282 (setq this-command 'undo)
1283 ;; Check to see whether we're hitting a redo record, and if
1284 ;; so, ask the user whether she wants to skip the redo/undo pair.
1285 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1286 (or (eq (selected-window) (minibuffer-window))
1287 (message (if undo-in-region
1288 (if equiv "Redo in region!" "Undo in region!")
1289 (if equiv "Redo!" "Undo!"))))
1290 (when (and equiv undo-no-redo)
1291 ;; The equiv entry might point to another redo record if we have done
1292 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1293 (while (let ((next (gethash equiv undo-equiv-table)))
1294 (if next (setq equiv next))))
1295 (setq pending-undo-list equiv)))
1297 (if (or transient-mark-mode (numberp arg))
1298 (prefix-numeric-value arg)
1300 ;; Record the fact that the just-generated undo records come from an
1301 ;; undo operation, so we can skip them later on.
1302 ;; I don't know how to do that in the undo-in-region case.
1303 (unless undo-in-region
1304 (puthash buffer-undo-list pending-undo-list undo-equiv-table))
1305 ;; Don't specify a position in the undo record for the undo command.
1306 ;; Instead, undoing this should move point to where the change is.
1307 (let ((tail buffer-undo-list)
1310 (when (integerp (car tail))
1311 (let ((pos (car tail)))
1313 (setcdr prev (cdr tail))
1314 (setq buffer-undo-list (cdr tail)))
1315 (setq tail (cdr tail))
1317 (if (eq pos (car tail))
1319 (setcdr prev (cdr tail))
1320 (setq buffer-undo-list (cdr tail)))
1322 (setq tail (cdr tail)))
1324 (setq prev tail tail (cdr tail))))
1325 ;; Record what the current undo list says,
1326 ;; so the next command can tell if the buffer was modified in between.
1327 (and modified (not (buffer-modified-p))
1328 (delete-auto-save-file-if-necessary recent-save))))
1330 (defun buffer-disable-undo (&optional buffer)
1331 "Make BUFFER stop keeping undo information.
1332 No argument or nil as argument means do this for the current buffer."
1334 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
1335 (setq buffer-undo-list t)))
1337 (defun undo-only (&optional arg)
1338 "Undo some previous changes.
1339 Repeat this command to undo more changes.
1340 A numeric argument serves as a repeat count.
1341 Contrary to `undo', this will not redo a previous undo."
1343 (let ((undo-no-redo t)) (undo arg)))
1344 ;; Richard said that we should not use C-x <uppercase letter> and I have
1345 ;; no idea whereas to bind it. Any suggestion welcome. -stef
1346 ;; (define-key ctl-x-map "U" 'undo-only)
1348 (defvar undo-in-progress nil
1349 "Non-nil while performing an undo.
1350 Some change-hooks test this variable to do something different.")
1352 (defun undo-more (count)
1353 "Undo back N undo-boundaries beyond what was already undone recently.
1354 Call `undo-start' to get ready to undo recent changes,
1355 then call `undo-more' one or more times to undo them."
1356 (or (listp pending-undo-list)
1357 (error (format "No further undo information%s"
1358 (if (and transient-mark-mode mark-active)
1359 " for region" ""))))
1360 (let ((undo-in-progress t))
1361 (setq pending-undo-list (primitive-undo count pending-undo-list))
1362 (if (null pending-undo-list)
1363 (setq pending-undo-list t))))
1365 ;; Deep copy of a list
1366 (defun undo-copy-list (list)
1367 "Make a copy of undo list LIST."
1368 (mapcar 'undo-copy-list-1 list))
1370 (defun undo-copy-list-1 (elt)
1372 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1375 (defun undo-start (&optional beg end)
1376 "Set `pending-undo-list' to the front of the undo list.
1377 The next call to `undo-more' will undo the most recently made change.
1378 If BEG and END are specified, then only undo elements
1379 that apply to text between BEG and END are used; other undo elements
1380 are ignored. If BEG and END are nil, all undo elements are used."
1381 (if (eq buffer-undo-list t)
1382 (error "No undo information in this buffer"))
1383 (setq pending-undo-list
1384 (if (and beg end (not (= beg end)))
1385 (undo-make-selective-list (min beg end) (max beg end))
1388 (defvar undo-adjusted-markers)
1390 (defun undo-make-selective-list (start end)
1391 "Return a list of undo elements for the region START to END.
1392 The elements come from `buffer-undo-list', but we keep only
1393 the elements inside this region, and discard those outside this region.
1394 If we find an element that crosses an edge of this region,
1395 we stop and ignore all further elements."
1396 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1397 (undo-list (list nil))
1398 undo-adjusted-markers
1400 undo-elt undo-elt temp-undo-list delta)
1401 (while undo-list-copy
1402 (setq undo-elt (car undo-list-copy))
1404 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1405 ;; This is a "was unmodified" element.
1406 ;; Keep it if we have kept everything thus far.
1407 (not some-rejected))
1409 (undo-elt-in-region undo-elt start end)))))
1412 (setq end (+ end (cdr (undo-delta undo-elt))))
1413 ;; Don't put two nils together in the list
1414 (if (not (and (eq (car undo-list) nil)
1416 (setq undo-list (cons undo-elt undo-list))))
1417 (if (undo-elt-crosses-region undo-elt start end)
1418 (setq undo-list-copy nil)
1419 (setq some-rejected t)
1420 (setq temp-undo-list (cdr undo-list-copy))
1421 (setq delta (undo-delta undo-elt))
1423 (when (/= (cdr delta) 0)
1424 (let ((position (car delta))
1425 (offset (cdr delta)))
1427 ;; Loop down the earlier events adjusting their buffer
1428 ;; positions to reflect the fact that a change to the buffer
1429 ;; isn't being undone. We only need to process those element
1430 ;; types which undo-elt-in-region will return as being in
1431 ;; the region since only those types can ever get into the
1434 (while temp-undo-list
1435 (setq undo-elt (car temp-undo-list))
1436 (cond ((integerp undo-elt)
1437 (if (>= undo-elt position)
1438 (setcar temp-undo-list (- undo-elt offset))))
1439 ((atom undo-elt) nil)
1440 ((stringp (car undo-elt))
1441 ;; (TEXT . POSITION)
1442 (let ((text-pos (abs (cdr undo-elt)))
1443 (point-at-end (< (cdr undo-elt) 0 )))
1444 (if (>= text-pos position)
1445 (setcdr undo-elt (* (if point-at-end -1 1)
1446 (- text-pos offset))))))
1447 ((integerp (car undo-elt))
1449 (when (>= (car undo-elt) position)
1450 (setcar undo-elt (- (car undo-elt) offset))
1451 (setcdr undo-elt (- (cdr undo-elt) offset))))
1452 ((null (car undo-elt))
1453 ;; (nil PROPERTY VALUE BEG . END)
1454 (let ((tail (nthcdr 3 undo-elt)))
1455 (when (>= (car tail) position)
1456 (setcar tail (- (car tail) offset))
1457 (setcdr tail (- (cdr tail) offset))))))
1458 (setq temp-undo-list (cdr temp-undo-list))))))))
1459 (setq undo-list-copy (cdr undo-list-copy)))
1460 (nreverse undo-list)))
1462 (defun undo-elt-in-region (undo-elt start end)
1463 "Determine whether UNDO-ELT falls inside the region START ... END.
1464 If it crosses the edge, we return nil."
1465 (cond ((integerp undo-elt)
1466 (and (>= undo-elt start)
1472 ((stringp (car undo-elt))
1473 ;; (TEXT . POSITION)
1474 (and (>= (abs (cdr undo-elt)) start)
1475 (< (abs (cdr undo-elt)) end)))
1476 ((and (consp undo-elt) (markerp (car undo-elt)))
1477 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1478 ;; See if MARKER is inside the region.
1479 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1481 (setq alist-elt (cons (car undo-elt)
1482 (marker-position (car undo-elt))))
1483 (setq undo-adjusted-markers
1484 (cons alist-elt undo-adjusted-markers)))
1485 (and (cdr alist-elt)
1486 (>= (cdr alist-elt) start)
1487 (<= (cdr alist-elt) end))))
1488 ((null (car undo-elt))
1489 ;; (nil PROPERTY VALUE BEG . END)
1490 (let ((tail (nthcdr 3 undo-elt)))
1491 (and (>= (car tail) start)
1492 (<= (cdr tail) end))))
1493 ((integerp (car undo-elt))
1495 (and (>= (car undo-elt) start)
1496 (<= (cdr undo-elt) end)))))
1498 (defun undo-elt-crosses-region (undo-elt start end)
1499 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1500 This assumes we have already decided that UNDO-ELT
1501 is not *inside* the region START...END."
1502 (cond ((atom undo-elt) nil)
1503 ((null (car undo-elt))
1504 ;; (nil PROPERTY VALUE BEG . END)
1505 (let ((tail (nthcdr 3 undo-elt)))
1506 (not (or (< (car tail) end)
1507 (> (cdr tail) start)))))
1508 ((integerp (car undo-elt))
1510 (not (or (< (car undo-elt) end)
1511 (> (cdr undo-elt) start))))))
1513 ;; Return the first affected buffer position and the delta for an undo element
1514 ;; delta is defined as the change in subsequent buffer positions if we *did*
1516 (defun undo-delta (undo-elt)
1517 (if (consp undo-elt)
1518 (cond ((stringp (car undo-elt))
1519 ;; (TEXT . POSITION)
1520 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1521 ((integerp (car undo-elt))
1523 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1528 (defcustom undo-ask-before-discard t
1529 "If non-nil ask about discarding undo info for the current command.
1530 Normally, Emacs discards the undo info for the current command if
1531 it exceeds `undo-outer-limit'. But if you set this option
1532 non-nil, it asks in the echo area whether to discard the info.
1533 If you answer no, there a slight risk that Emacs might crash, so
1534 only do it if you really want to undo the command.
1536 This option is mainly intended for debugging. You have to be
1537 careful if you use it for other purposes. Garbage collection is
1538 inhibited while the question is asked, meaning that Emacs might
1539 leak memory. So you should make sure that you do not wait
1540 excessively long before answering the question."
1545 (defvar undo-extra-outer-limit nil
1546 "If non-nil, an extra level of size that's ok in an undo item.
1547 We don't ask the user about truncating the undo list until the
1548 current item gets bigger than this amount.
1550 This variable only matters if `undo-ask-before-discard' is non-nil.")
1551 (make-variable-buffer-local 'undo-extra-outer-limit)
1553 ;; When the first undo batch in an undo list is longer than
1554 ;; undo-outer-limit, this function gets called to warn the user that
1555 ;; the undo info for the current command was discarded. Garbage
1556 ;; collection is inhibited around the call, so it had better not do a
1558 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
1559 (defun undo-outer-limit-truncate (size)
1560 (if undo-ask-before-discard
1561 (when (or (null undo-extra-outer-limit)
1562 (> size undo-extra-outer-limit))
1563 ;; Don't ask the question again unless it gets even bigger.
1564 ;; This applies, in particular, if the user quits from the question.
1565 ;; Such a quit quits out of GC, but something else will call GC
1566 ;; again momentarily. It will call this function again,
1567 ;; but we don't want to ask the question again.
1568 (setq undo-extra-outer-limit (+ size 50000))
1569 (if (let (use-dialog-box track-mouse executing-kbd-macro )
1570 (yes-or-no-p (format "Buffer %s undo info is %d bytes long; discard it? "
1571 (buffer-name) size)))
1572 (progn (setq buffer-undo-list nil)
1573 (setq undo-extra-outer-limit nil)
1576 (display-warning '(undo discard-info)
1578 (format "Buffer %s undo info was %d bytes long.\n"
1580 "The undo info was discarded because it exceeded \
1583 This is normal if you executed a command that made a huge change
1584 to the buffer. In that case, to prevent similar problems in the
1585 future, set `undo-outer-limit' to a value that is large enough to
1586 cover the maximum size of normal changes you expect a single
1587 command to make, but not so large that it might exceed the
1588 maximum memory allotted to Emacs.
1590 If you did not execute any such command, the situation is
1591 probably due to a bug and you should report it.
1593 You can disable the popping up of this buffer by adding the entry
1594 \(undo discard-info) to the user option `warning-suppress-types'.\n")
1596 (setq buffer-undo-list nil)
1599 (defvar shell-command-history nil
1600 "History list for some commands that read shell commands.")
1602 (defvar shell-command-switch "-c"
1603 "Switch used to have the shell execute its command line argument.")
1605 (defvar shell-command-default-error-buffer nil
1606 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1607 This buffer is used when `shell-command' or `shell-command-on-region'
1608 is run interactively. A value of nil means that output to stderr and
1609 stdout will be intermixed in the output stream.")
1611 (defun shell-command (command &optional output-buffer error-buffer)
1612 "Execute string COMMAND in inferior shell; display output, if any.
1613 With prefix argument, insert the COMMAND's output at point.
1615 If COMMAND ends in ampersand, execute it asynchronously.
1616 The output appears in the buffer `*Async Shell Command*'.
1617 That buffer is in shell mode.
1619 Otherwise, COMMAND is executed synchronously. The output appears in
1620 the buffer `*Shell Command Output*'. If the output is short enough to
1621 display in the echo area (which is determined by the variables
1622 `resize-mini-windows' and `max-mini-window-height'), it is shown
1623 there, but it is nonetheless available in buffer `*Shell Command
1624 Output*' even though that buffer is not automatically displayed.
1626 To specify a coding system for converting non-ASCII characters
1627 in the shell command output, use \\[universal-coding-system-argument]
1628 before this command.
1630 Noninteractive callers can specify coding systems by binding
1631 `coding-system-for-read' and `coding-system-for-write'.
1633 The optional second argument OUTPUT-BUFFER, if non-nil,
1634 says to put the output in some other buffer.
1635 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1636 If OUTPUT-BUFFER is not a buffer and not nil,
1637 insert output in current buffer. (This cannot be done asynchronously.)
1638 In either case, the output is inserted after point (leaving mark after it).
1640 If the command terminates without error, but generates output,
1641 and you did not specify \"insert it in the current buffer\",
1642 the output can be displayed in the echo area or in its buffer.
1643 If the output is short enough to display in the echo area
1644 \(determined by the variable `max-mini-window-height' if
1645 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
1646 the buffer containing the output is displayed.
1648 If there is output and an error, and you did not specify \"insert it
1649 in the current buffer\", a message about the error goes at the end
1652 If there is no output, or if output is inserted in the current buffer,
1653 then `*Shell Command Output*' is deleted.
1655 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1656 or buffer name to which to direct the command's standard error output.
1657 If it is nil, error output is mingled with regular output.
1658 In an interactive call, the variable `shell-command-default-error-buffer'
1659 specifies the value of ERROR-BUFFER."
1661 (interactive (list (read-from-minibuffer "Shell command: "
1662 nil nil nil 'shell-command-history)
1664 shell-command-default-error-buffer))
1665 ;; Look for a handler in case default-directory is a remote file name.
1667 (find-file-name-handler (directory-file-name default-directory)
1670 (funcall handler 'shell-command command output-buffer error-buffer)
1671 (if (and output-buffer
1672 (not (or (bufferp output-buffer) (stringp output-buffer))))
1673 ;; Output goes in current buffer.
1677 (expand-file-name "scor"
1678 (or small-temporary-file-directory
1679 temporary-file-directory)))
1681 (barf-if-buffer-read-only)
1683 ;; We do not use -f for csh; we will not support broken use of
1684 ;; .cshrcs. Even the BSD csh manual says to use
1685 ;; "if ($?prompt) exit" before things which are not useful
1686 ;; non-interactively. Besides, if someone wants their other
1687 ;; aliases for shell commands then they can still have them.
1688 (call-process shell-file-name nil
1692 nil shell-command-switch command)
1693 (when (and error-file (file-exists-p error-file))
1694 (if (< 0 (nth 7 (file-attributes error-file)))
1695 (with-current-buffer (get-buffer-create error-buffer)
1696 (let ((pos-from-end (- (point-max) (point))))
1699 ;; Do no formatting while reading error file,
1700 ;; because that can run a shell command, and we
1701 ;; don't want that to cause an infinite recursion.
1702 (format-insert-file error-file nil)
1703 ;; Put point after the inserted errors.
1704 (goto-char (- (point-max) pos-from-end)))
1705 (display-buffer (current-buffer))))
1706 (delete-file error-file))
1707 ;; This is like exchange-point-and-mark, but doesn't
1708 ;; activate the mark. It is cleaner to avoid activation,
1709 ;; even though the command loop would deactivate the mark
1710 ;; because we inserted text.
1711 (goto-char (prog1 (mark t)
1712 (set-marker (mark-marker) (point)
1713 (current-buffer)))))
1714 ;; Output goes in a separate buffer.
1715 ;; Preserve the match data in case called from a program.
1717 (if (string-match "[ \t]*&[ \t]*\\'" command)
1718 ;; Command ending with ampersand means asynchronous.
1719 (let ((buffer (get-buffer-create
1720 (or output-buffer "*Async Shell Command*")))
1721 (directory default-directory)
1723 ;; Remove the ampersand.
1724 (setq command (substring command 0 (match-beginning 0)))
1725 ;; If will kill a process, query first.
1726 (setq proc (get-buffer-process buffer))
1728 (if (yes-or-no-p "A command is running. Kill it? ")
1730 (error "Shell command in progress")))
1731 (with-current-buffer buffer
1732 (setq buffer-read-only nil)
1734 (display-buffer buffer)
1735 (setq default-directory directory)
1736 (setq proc (start-process "Shell" buffer shell-file-name
1737 shell-command-switch command))
1738 (setq mode-line-process '(":%s"))
1739 (require 'shell) (shell-mode)
1740 (set-process-sentinel proc 'shell-command-sentinel)
1742 (shell-command-on-region (point) (point) command
1743 output-buffer nil error-buffer)))))))
1745 (defun display-message-or-buffer (message
1746 &optional buffer-name not-this-window frame)
1747 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1748 MESSAGE may be either a string or a buffer.
1750 A buffer is displayed using `display-buffer' if MESSAGE is too long for
1751 the maximum height of the echo area, as defined by `max-mini-window-height'
1752 if `resize-mini-windows' is non-nil.
1754 Returns either the string shown in the echo area, or when a pop-up
1755 buffer is used, the window used to display it.
1757 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1758 name of the buffer used to display it in the case where a pop-up buffer
1759 is used, defaulting to `*Message*'. In the case where MESSAGE is a
1760 string and it is displayed in the echo area, it is not specified whether
1761 the contents are inserted into the buffer anyway.
1763 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1764 and only used if a buffer is displayed."
1765 (cond ((and (stringp message) (not (string-match "\n" message)))
1766 ;; Trivial case where we can use the echo area
1767 (message "%s" message))
1768 ((and (stringp message)
1769 (= (string-match "\n" message) (1- (length message))))
1770 ;; Trivial case where we can just remove single trailing newline
1771 (message "%s" (substring message 0 (1- (length message)))))
1774 (with-current-buffer
1775 (if (bufferp message)
1777 (get-buffer-create (or buffer-name "*Message*")))
1779 (unless (bufferp message)
1784 (if (= (buffer-size) 0)
1786 (count-lines (point-min) (point-max)))))
1788 ((and (or (<= lines 1)
1790 (if resize-mini-windows
1791 (cond ((floatp max-mini-window-height)
1793 max-mini-window-height))
1794 ((integerp max-mini-window-height)
1795 max-mini-window-height)
1799 ;; Don't use the echo area if the output buffer is
1800 ;; already dispayed in the selected frame.
1801 (not (get-buffer-window (current-buffer))))
1803 (goto-char (point-max))
1806 (message "%s" (buffer-substring (point-min) (point))))
1809 (goto-char (point-min))
1810 (display-buffer (current-buffer)
1811 not-this-window frame))))))))
1814 ;; We have a sentinel to prevent insertion of a termination message
1815 ;; in the buffer itself.
1816 (defun shell-command-sentinel (process signal)
1817 (if (memq (process-status process) '(exit signal))
1819 (car (cdr (cdr (process-command process))))
1820 (substring signal 0 -1))))
1822 (defun shell-command-on-region (start end command
1823 &optional output-buffer replace
1824 error-buffer display-error-buffer)
1825 "Execute string COMMAND in inferior shell with region as input.
1826 Normally display output (if any) in temp buffer `*Shell Command Output*';
1827 Prefix arg means replace the region with it. Return the exit code of
1830 To specify a coding system for converting non-ASCII characters
1831 in the input and output to the shell command, use \\[universal-coding-system-argument]
1832 before this command. By default, the input (from the current buffer)
1833 is encoded in the same coding system that will be used to save the file,
1834 `buffer-file-coding-system'. If the output is going to replace the region,
1835 then it is decoded from that same coding system.
1837 The noninteractive arguments are START, END, COMMAND,
1838 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
1839 Noninteractive callers can specify coding systems by binding
1840 `coding-system-for-read' and `coding-system-for-write'.
1842 If the command generates output, the output may be displayed
1843 in the echo area or in a buffer.
1844 If the output is short enough to display in the echo area
1845 \(determined by the variable `max-mini-window-height' if
1846 `resize-mini-windows' is non-nil), it is shown there. Otherwise
1847 it is displayed in the buffer `*Shell Command Output*'. The output
1848 is available in that buffer in both cases.
1850 If there is output and an error, a message about the error
1851 appears at the end of the output.
1853 If there is no output, or if output is inserted in the current buffer,
1854 then `*Shell Command Output*' is deleted.
1856 If the optional fourth argument OUTPUT-BUFFER is non-nil,
1857 that says to put the output in some other buffer.
1858 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1859 If OUTPUT-BUFFER is not a buffer and not nil,
1860 insert output in the current buffer.
1861 In either case, the output is inserted after point (leaving mark after it).
1863 If REPLACE, the optional fifth argument, is non-nil, that means insert
1864 the output in place of text from START to END, putting point and mark
1867 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
1868 or buffer name to which to direct the command's standard error output.
1869 If it is nil, error output is mingled with regular output.
1870 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
1871 were any errors. (This is always t, interactively.)
1872 In an interactive call, the variable `shell-command-default-error-buffer'
1873 specifies the value of ERROR-BUFFER."
1874 (interactive (let (string)
1876 (error "The mark is not set now, so there is no region"))
1877 ;; Do this before calling region-beginning
1878 ;; and region-end, in case subprocess output
1879 ;; relocates them while we are in the minibuffer.
1880 (setq string (read-from-minibuffer "Shell command on region: "
1882 'shell-command-history))
1883 ;; call-interactively recognizes region-beginning and
1884 ;; region-end specially, leaving them in the history.
1885 (list (region-beginning) (region-end)
1889 shell-command-default-error-buffer
1894 (expand-file-name "scor"
1895 (or small-temporary-file-directory
1896 temporary-file-directory)))
1901 (not (or (bufferp output-buffer) (stringp output-buffer)))))
1902 ;; Replace specified region with output from command.
1903 (let ((swap (and replace (< start end))))
1904 ;; Don't muck with mark unless REPLACE says we should.
1906 (and replace (push-mark (point) 'nomsg))
1908 (call-process-region start end shell-file-name t
1912 nil shell-command-switch command))
1913 ;; It is rude to delete a buffer which the command is not using.
1914 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
1915 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
1916 ;; (kill-buffer shell-buffer)))
1917 ;; Don't muck with mark unless REPLACE says we should.
1918 (and replace swap (exchange-point-and-mark)))
1919 ;; No prefix argument: put the output in a temp buffer,
1920 ;; replacing its entire contents.
1921 (let ((buffer (get-buffer-create
1922 (or output-buffer "*Shell Command Output*"))))
1924 (if (eq buffer (current-buffer))
1925 ;; If the input is the same buffer as the output,
1926 ;; delete everything but the specified region,
1927 ;; then replace that region with the output.
1928 (progn (setq buffer-read-only nil)
1929 (delete-region (max start end) (point-max))
1930 (delete-region (point-min) (min start end))
1932 (call-process-region (point-min) (point-max)
1937 nil shell-command-switch
1939 ;; Clear the output buffer, then run the command with
1941 (let ((directory default-directory))
1944 (setq buffer-read-only nil)
1945 (if (not output-buffer)
1946 (setq default-directory directory))
1949 (call-process-region start end shell-file-name nil
1951 (list buffer error-file)
1953 nil shell-command-switch command)))
1954 ;; Report the output.
1955 (with-current-buffer buffer
1956 (setq mode-line-process
1957 (cond ((null exit-status)
1959 ((stringp exit-status)
1960 (format " - Signal [%s]" exit-status))
1961 ((not (equal 0 exit-status))
1962 (format " - Exit [%d]" exit-status)))))
1963 (if (with-current-buffer buffer (> (point-max) (point-min)))
1964 ;; There's some output, display it
1965 (display-message-or-buffer buffer)
1966 ;; No output; error?
1969 (< 0 (nth 7 (file-attributes error-file))))
1972 (cond ((null exit-status)
1973 (message "(Shell command failed with error)"))
1974 ((equal 0 exit-status)
1975 (message "(Shell command succeeded with %s)"
1977 ((stringp exit-status)
1978 (message "(Shell command killed by signal %s)"
1981 (message "(Shell command failed with code %d and %s)"
1982 exit-status output))))
1983 ;; Don't kill: there might be useful info in the undo-log.
1984 ;; (kill-buffer buffer)
1987 (when (and error-file (file-exists-p error-file))
1988 (if (< 0 (nth 7 (file-attributes error-file)))
1989 (with-current-buffer (get-buffer-create error-buffer)
1990 (let ((pos-from-end (- (point-max) (point))))
1993 ;; Do no formatting while reading error file,
1994 ;; because that can run a shell command, and we
1995 ;; don't want that to cause an infinite recursion.
1996 (format-insert-file error-file nil)
1997 ;; Put point after the inserted errors.
1998 (goto-char (- (point-max) pos-from-end)))
1999 (and display-error-buffer
2000 (display-buffer (current-buffer)))))
2001 (delete-file error-file))
2004 (defun shell-command-to-string (command)
2005 "Execute shell command COMMAND and return its output as a string."
2006 (with-output-to-string
2007 (with-current-buffer
2009 (call-process shell-file-name nil t nil shell-command-switch command))))
2011 (defun process-file (program &optional infile buffer display &rest args)
2012 "Process files synchronously in a separate process.
2013 Similar to `call-process', but may invoke a file handler based on
2014 `default-directory'. The current working directory of the
2015 subprocess is `default-directory'.
2017 File names in INFILE and BUFFER are handled normally, but file
2018 names in ARGS should be relative to `default-directory', as they
2019 are passed to the process verbatim. \(This is a difference to
2020 `call-process' which does not support file handlers for INFILE
2023 Some file handlers might not support all variants, for example
2024 they might behave as if DISPLAY was nil, regardless of the actual
2026 (let ((fh (find-file-name-handler default-directory 'process-file))
2029 (if fh (apply fh 'process-file program infile buffer display args)
2030 (when infile (setq lc (file-local-copy infile)))
2031 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
2032 (make-temp-file "emacs")))
2034 (apply 'call-process program
2036 (if stderr-file (list (car buffer) stderr-file) buffer)
2038 (when stderr-file (copy-file stderr-file (cadr buffer)))))
2039 (when stderr-file (delete-file stderr-file))
2040 (when lc (delete-file lc)))))
2044 (defvar universal-argument-map
2045 (let ((map (make-sparse-keymap)))
2046 (define-key map [t] 'universal-argument-other-key)
2047 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2048 (define-key map [switch-frame] nil)
2049 (define-key map [?\C-u] 'universal-argument-more)
2050 (define-key map [?-] 'universal-argument-minus)
2051 (define-key map [?0] 'digit-argument)
2052 (define-key map [?1] 'digit-argument)
2053 (define-key map [?2] 'digit-argument)
2054 (define-key map [?3] 'digit-argument)
2055 (define-key map [?4] 'digit-argument)
2056 (define-key map [?5] 'digit-argument)
2057 (define-key map [?6] 'digit-argument)
2058 (define-key map [?7] 'digit-argument)
2059 (define-key map [?8] 'digit-argument)
2060 (define-key map [?9] 'digit-argument)
2061 (define-key map [kp-0] 'digit-argument)
2062 (define-key map [kp-1] 'digit-argument)
2063 (define-key map [kp-2] 'digit-argument)
2064 (define-key map [kp-3] 'digit-argument)
2065 (define-key map [kp-4] 'digit-argument)
2066 (define-key map [kp-5] 'digit-argument)
2067 (define-key map [kp-6] 'digit-argument)
2068 (define-key map [kp-7] 'digit-argument)
2069 (define-key map [kp-8] 'digit-argument)
2070 (define-key map [kp-9] 'digit-argument)
2071 (define-key map [kp-subtract] 'universal-argument-minus)
2073 "Keymap used while processing \\[universal-argument].")
2075 (defvar universal-argument-num-events nil
2076 "Number of argument-specifying events read by `universal-argument'.
2077 `universal-argument-other-key' uses this to discard those events
2078 from (this-command-keys), and reread only the final command.")
2080 (defvar overriding-map-is-bound nil
2081 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2083 (defvar saved-overriding-map nil
2084 "The saved value of `overriding-terminal-local-map'.
2085 That variable gets restored to this value on exiting \"universal
2088 (defun ensure-overriding-map-is-bound ()
2089 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2090 (unless overriding-map-is-bound
2091 (setq saved-overriding-map overriding-terminal-local-map)
2092 (setq overriding-terminal-local-map universal-argument-map)
2093 (setq overriding-map-is-bound t)))
2095 (defun restore-overriding-map ()
2096 "Restore `overriding-terminal-local-map' to its saved value."
2097 (setq overriding-terminal-local-map saved-overriding-map)
2098 (setq overriding-map-is-bound nil))
2100 (defun universal-argument ()
2101 "Begin a numeric argument for the following command.
2102 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2103 \\[universal-argument] following the digits or minus sign ends the argument.
2104 \\[universal-argument] without digits or minus sign provides 4 as argument.
2105 Repeating \\[universal-argument] without digits or minus sign
2106 multiplies the argument by 4 each time.
2107 For some commands, just \\[universal-argument] by itself serves as a flag
2108 which is different in effect from any particular numeric argument.
2109 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2111 (setq prefix-arg (list 4))
2112 (setq universal-argument-num-events (length (this-command-keys)))
2113 (ensure-overriding-map-is-bound))
2115 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2116 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2117 (defun universal-argument-more (arg)
2120 (setq prefix-arg (list (* 4 (car arg))))
2122 (setq prefix-arg (list -4))
2123 (setq prefix-arg arg)
2124 (restore-overriding-map)))
2125 (setq universal-argument-num-events (length (this-command-keys))))
2127 (defun negative-argument (arg)
2128 "Begin a negative numeric argument for the next command.
2129 \\[universal-argument] following digits or minus sign ends the argument."
2131 (cond ((integerp arg)
2132 (setq prefix-arg (- arg)))
2134 (setq prefix-arg nil))
2136 (setq prefix-arg '-)))
2137 (setq universal-argument-num-events (length (this-command-keys)))
2138 (ensure-overriding-map-is-bound))
2140 (defun digit-argument (arg)
2141 "Part of the numeric argument for the next command.
2142 \\[universal-argument] following digits or minus sign ends the argument."
2144 (let* ((char (if (integerp last-command-char)
2146 (get last-command-char 'ascii-character)))
2147 (digit (- (logand char ?\177) ?0)))
2148 (cond ((integerp arg)
2149 (setq prefix-arg (+ (* arg 10)
2150 (if (< arg 0) (- digit) digit))))
2152 ;; Treat -0 as just -, so that -01 will work.
2153 (setq prefix-arg (if (zerop digit) '- (- digit))))
2155 (setq prefix-arg digit))))
2156 (setq universal-argument-num-events (length (this-command-keys)))
2157 (ensure-overriding-map-is-bound))
2159 ;; For backward compatibility, minus with no modifiers is an ordinary
2160 ;; command if digits have already been entered.
2161 (defun universal-argument-minus (arg)
2164 (universal-argument-other-key arg)
2165 (negative-argument arg)))
2167 ;; Anything else terminates the argument and is left in the queue to be
2168 ;; executed as a command.
2169 (defun universal-argument-other-key (arg)
2171 (setq prefix-arg arg)
2172 (let* ((key (this-command-keys))
2173 (keylist (listify-key-sequence key)))
2174 (setq unread-command-events
2175 (append (nthcdr universal-argument-num-events keylist)
2176 unread-command-events)))
2177 (reset-this-command-lengths)
2178 (restore-overriding-map))
2180 ;;;; Window system cut and paste hooks.
2182 (defvar interprogram-cut-function nil
2183 "Function to call to make a killed region available to other programs.
2185 Most window systems provide some sort of facility for cutting and
2186 pasting text between the windows of different programs.
2187 This variable holds a function that Emacs calls whenever text
2188 is put in the kill ring, to make the new kill available to other
2191 The function takes one or two arguments.
2192 The first argument, TEXT, is a string containing
2193 the text which should be made available.
2194 The second, optional, argument PUSH, has the same meaning as the
2195 similar argument to `x-set-cut-buffer', which see.")
2197 (make-variable-frame-local 'interprogram-cut-function)
2199 (defvar interprogram-paste-function nil
2200 "Function to call to get text cut from other programs.
2202 Most window systems provide some sort of facility for cutting and
2203 pasting text between the windows of different programs.
2204 This variable holds a function that Emacs calls to obtain
2205 text that other programs have provided for pasting.
2207 The function should be called with no arguments. If the function
2208 returns nil, then no other program has provided such text, and the top
2209 of the Emacs kill ring should be used. If the function returns a
2210 string, then the caller of the function \(usually `current-kill')
2211 should put this string in the kill ring as the latest kill.
2213 Note that the function should return a string only if a program other
2214 than Emacs has provided a string for pasting; if Emacs provided the
2215 most recent string, the function should return nil. If it is
2216 difficult to tell whether Emacs or some other program provided the
2217 current string, it is probably good enough to return nil if the string
2218 is equal (according to `string=') to the last text Emacs provided.")
2220 (make-variable-frame-local 'interprogram-paste-function)
2224 ;;;; The kill ring data structure.
2226 (defvar kill-ring nil
2227 "List of killed text sequences.
2228 Since the kill ring is supposed to interact nicely with cut-and-paste
2229 facilities offered by window systems, use of this variable should
2230 interact nicely with `interprogram-cut-function' and
2231 `interprogram-paste-function'. The functions `kill-new',
2232 `kill-append', and `current-kill' are supposed to implement this
2233 interaction; you may want to use them instead of manipulating the kill
2236 (defcustom kill-ring-max 60
2237 "*Maximum length of kill ring before oldest elements are thrown away."
2241 (defvar kill-ring-yank-pointer nil
2242 "The tail of the kill ring whose car is the last thing yanked.")
2244 (defun kill-new (string &optional replace yank-handler)
2245 "Make STRING the latest kill in the kill ring.
2246 Set `kill-ring-yank-pointer' to point to it.
2247 If `interprogram-cut-function' is non-nil, apply it to STRING.
2248 Optional second argument REPLACE non-nil means that STRING will replace
2249 the front of the kill ring, rather than being added to the list.
2251 Optional third arguments YANK-HANDLER controls how the STRING is later
2252 inserted into a buffer; see `insert-for-yank' for details.
2253 When a yank handler is specified, STRING must be non-empty (the yank
2254 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2256 When the yank handler has a non-nil PARAM element, the original STRING
2257 argument is not used by `insert-for-yank'. However, since Lisp code
2258 may access and use elements from the kill-ring directly, the STRING
2259 argument should still be a \"useful\" string for such uses."
2260 (if (> (length string) 0)
2262 (put-text-property 0 (length string)
2263 'yank-handler yank-handler string))
2265 (signal 'args-out-of-range
2266 (list string "yank-handler specified for empty string"))))
2267 (if (fboundp 'menu-bar-update-yank-menu)
2268 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2269 (if (and replace kill-ring)
2270 (setcar kill-ring string)
2271 (setq kill-ring (cons string kill-ring))
2272 (if (> (length kill-ring) kill-ring-max)
2273 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2274 (setq kill-ring-yank-pointer kill-ring)
2275 (if interprogram-cut-function
2276 (funcall interprogram-cut-function string (not replace))))
2278 (defun kill-append (string before-p &optional yank-handler)
2279 "Append STRING to the end of the latest kill in the kill ring.
2280 If BEFORE-P is non-nil, prepend STRING to the kill.
2281 Optional third argument YANK-HANDLER, if non-nil, specifies the
2282 yank-handler text property to be set on the combined kill ring
2283 string. If the specified yank-handler arg differs from the
2284 yank-handler property of the latest kill string, this function
2285 adds the combined string to the kill ring as a new element,
2286 instead of replacing the last kill with it.
2287 If `interprogram-cut-function' is set, pass the resulting kill to it."
2288 (let* ((cur (car kill-ring)))
2289 (kill-new (if before-p (concat string cur) (concat cur string))
2290 (or (= (length cur) 0)
2291 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2294 (defun current-kill (n &optional do-not-move)
2295 "Rotate the yanking point by N places, and then return that kill.
2296 If N is zero, `interprogram-paste-function' is set, and calling it
2297 returns a string, then that string is added to the front of the
2298 kill ring and returned as the latest kill.
2299 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
2300 yanking point; just return the Nth kill forward."
2301 (let ((interprogram-paste (and (= n 0)
2302 interprogram-paste-function
2303 (funcall interprogram-paste-function))))
2304 (if interprogram-paste
2306 ;; Disable the interprogram cut function when we add the new
2307 ;; text to the kill ring, so Emacs doesn't try to own the
2308 ;; selection, with identical text.
2309 (let ((interprogram-cut-function nil))
2310 (kill-new interprogram-paste))
2312 (or kill-ring (error "Kill ring is empty"))
2313 (let ((ARGth-kill-element
2314 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2318 (setq kill-ring-yank-pointer ARGth-kill-element))
2319 (car ARGth-kill-element)))))
2323 ;;;; Commands for manipulating the kill ring.
2325 (defcustom kill-read-only-ok nil
2326 "*Non-nil means don't signal an error for killing read-only text."
2330 (put 'text-read-only 'error-conditions
2331 '(text-read-only buffer-read-only error))
2332 (put 'text-read-only 'error-message "Text is read-only")
2334 (defun kill-region (beg end &optional yank-handler)
2335 "Kill between point and mark.
2336 The text is deleted but saved in the kill ring.
2337 The command \\[yank] can retrieve it from there.
2338 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2340 If you want to append the killed region to the last killed text,
2341 use \\[append-next-kill] before \\[kill-region].
2343 If the buffer is read-only, Emacs will beep and refrain from deleting
2344 the text, but put the text in the kill ring anyway. This means that
2345 you can use the killing commands to copy text from a read-only buffer.
2347 This is the primitive for programs to kill text (as opposed to deleting it).
2348 Supply two arguments, character positions indicating the stretch of text
2350 Any command that calls this function is a \"kill command\".
2351 If the previous command was also a kill command,
2352 the text killed this time appends to the text killed last time
2353 to make one entry in the kill ring.
2355 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2356 specifies the yank-handler text property to be set on the killed
2357 text. See `insert-for-yank'."
2360 (let ((string (delete-and-extract-region beg end)))
2361 (when string ;STRING is nil if BEG = END
2362 ;; Add that string to the kill ring, one way or another.
2363 (if (eq last-command 'kill-region)
2364 (kill-append string (< end beg) yank-handler)
2365 (kill-new string nil yank-handler)))
2366 (when (or string (eq last-command 'kill-region))
2367 (setq this-command 'kill-region))
2369 ((buffer-read-only text-read-only)
2370 ;; The code above failed because the buffer, or some of the characters
2371 ;; in the region, are read-only.
2372 ;; We should beep, in case the user just isn't aware of this.
2373 ;; However, there's no harm in putting
2374 ;; the region's text in the kill ring, anyway.
2375 (copy-region-as-kill beg end)
2376 ;; Set this-command now, so it will be set even if we get an error.
2377 (setq this-command 'kill-region)
2378 ;; This should barf, if appropriate, and give us the correct error.
2379 (if kill-read-only-ok
2380 (progn (message "Read only text copied to kill ring") nil)
2381 ;; Signal an error if the buffer is read-only.
2382 (barf-if-buffer-read-only)
2383 ;; If the buffer isn't read-only, the text is.
2384 (signal 'text-read-only (list (current-buffer)))))))
2386 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2387 ;; to get two copies of the text when the user accidentally types M-w and
2388 ;; then corrects it with the intended C-w.
2389 (defun copy-region-as-kill (beg end)
2390 "Save the region as if killed, but don't kill it.
2391 In Transient Mark mode, deactivate the mark.
2392 If `interprogram-cut-function' is non-nil, also save the text for a window
2393 system cut and paste."
2395 (if (eq last-command 'kill-region)
2396 (kill-append (buffer-substring beg end) (< end beg))
2397 (kill-new (buffer-substring beg end)))
2398 (if transient-mark-mode
2399 (setq deactivate-mark t))
2402 (defun kill-ring-save (beg end)
2403 "Save the region as if killed, but don't kill it.
2404 In Transient Mark mode, deactivate the mark.
2405 If `interprogram-cut-function' is non-nil, also save the text for a window
2406 system cut and paste.
2408 If you want to append the killed line to the last killed text,
2409 use \\[append-next-kill] before \\[kill-ring-save].
2411 This command is similar to `copy-region-as-kill', except that it gives
2412 visual feedback indicating the extent of the region being copied."
2414 (copy-region-as-kill beg end)
2415 ;; This use of interactive-p is correct
2416 ;; because the code it controls just gives the user visual feedback.
2418 (let ((other-end (if (= (point) beg) end beg))
2420 ;; Inhibit quitting so we can make a quit here
2421 ;; look like a C-g typed as a command.
2423 (if (pos-visible-in-window-p other-end (selected-window))
2424 (unless (and transient-mark-mode
2425 (face-background 'region))
2426 ;; Swap point and mark.
2427 (set-marker (mark-marker) (point) (current-buffer))
2428 (goto-char other-end)
2429 (sit-for blink-matching-delay)
2431 (set-marker (mark-marker) other-end (current-buffer))
2433 ;; If user quit, deactivate the mark
2434 ;; as C-g would as a command.
2435 (and quit-flag mark-active
2437 (let* ((killed-text (current-kill 0))
2438 (message-len (min (length killed-text) 40)))
2440 ;; Don't say "killed"; that is misleading.
2441 (message "Saved text until \"%s\""
2442 (substring killed-text (- message-len)))
2443 (message "Saved text from \"%s\""
2444 (substring killed-text 0 message-len))))))))
2446 (defun append-next-kill (&optional interactive)
2447 "Cause following command, if it kills, to append to previous kill.
2448 The argument is used for internal purposes; do not supply one."
2450 ;; We don't use (interactive-p), since that breaks kbd macros.
2453 (setq this-command 'kill-region)
2454 (message "If the next command is a kill, it will append"))
2455 (setq last-command 'kill-region)))
2459 ;; This is actually used in subr.el but defcustom does not work there.
2460 (defcustom yank-excluded-properties
2461 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2463 "*Text properties to discard when yanking.
2464 The value should be a list of text properties to discard or t,
2465 which means to discard all text properties."
2466 :type '(choice (const :tag "All" t) (repeat symbol))
2470 (defvar yank-window-start nil)
2471 (defvar yank-undo-function nil
2472 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2473 Function is called with two parameters, START and END corresponding to
2474 the value of the mark and point; it is guaranteed that START <= END.
2475 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2477 (defun yank-pop (&optional arg)
2478 "Replace just-yanked stretch of killed text with a different stretch.
2479 This command is allowed only immediately after a `yank' or a `yank-pop'.
2480 At such a time, the region contains a stretch of reinserted
2481 previously-killed text. `yank-pop' deletes that text and inserts in its
2482 place a different stretch of killed text.
2484 With no argument, the previous kill is inserted.
2485 With argument N, insert the Nth previous kill.
2486 If N is negative, this is a more recent kill.
2488 The sequence of kills wraps around, so that after the oldest one
2489 comes the newest one."
2491 (if (not (eq last-command 'yank))
2492 (error "Previous command was not a yank"))
2493 (setq this-command 'yank)
2494 (unless arg (setq arg 1))
2495 (let ((inhibit-read-only t)
2496 (before (< (point) (mark t))))
2498 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2499 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2500 (setq yank-undo-function nil)
2501 (set-marker (mark-marker) (point) (current-buffer))
2502 (insert-for-yank (current-kill arg))
2503 ;; Set the window start back where it was in the yank command,
2505 (set-window-start (selected-window) yank-window-start t)
2507 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2508 ;; It is cleaner to avoid activation, even though the command
2509 ;; loop would deactivate the mark because we inserted text.
2510 (goto-char (prog1 (mark t)
2511 (set-marker (mark-marker) (point) (current-buffer))))))
2514 (defun yank (&optional arg)
2515 "Reinsert the last stretch of killed text.
2516 More precisely, reinsert the stretch of killed text most recently
2517 killed OR yanked. Put point at end, and set mark at beginning.
2518 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2519 With argument N, reinsert the Nth most recently killed stretch of killed
2521 See also the command \\[yank-pop]."
2523 (setq yank-window-start (window-start))
2524 ;; If we don't get all the way thru, make last-command indicate that
2525 ;; for the following command.
2526 (setq this-command t)
2528 (insert-for-yank (current-kill (cond
2533 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2534 ;; It is cleaner to avoid activation, even though the command
2535 ;; loop would deactivate the mark because we inserted text.
2536 (goto-char (prog1 (mark t)
2537 (set-marker (mark-marker) (point) (current-buffer)))))
2538 ;; If we do get all the way thru, make this-command indicate that.
2539 (if (eq this-command t)
2540 (setq this-command 'yank))
2543 (defun rotate-yank-pointer (arg)
2544 "Rotate the yanking point in the kill ring.
2545 With argument, rotate that many kills forward (or backward, if negative)."
2549 ;; Some kill commands.
2551 ;; Internal subroutine of delete-char
2552 (defun kill-forward-chars (arg)
2553 (if (listp arg) (setq arg (car arg)))
2554 (if (eq arg '-) (setq arg -1))
2555 (kill-region (point) (forward-point arg)))
2557 ;; Internal subroutine of backward-delete-char
2558 (defun kill-backward-chars (arg)
2559 (if (listp arg) (setq arg (car arg)))
2560 (if (eq arg '-) (setq arg -1))
2561 (kill-region (point) (forward-point (- arg))))
2563 (defcustom backward-delete-char-untabify-method 'untabify
2564 "*The method for untabifying when deleting backward.
2565 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2566 `hungry' -- delete all whitespace, both tabs and spaces;
2567 `all' -- delete all whitespace, including tabs, spaces and newlines;
2568 nil -- just delete one character."
2569 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2573 (defun backward-delete-char-untabify (arg &optional killp)
2574 "Delete characters backward, changing tabs into spaces.
2575 The exact behavior depends on `backward-delete-char-untabify-method'.
2576 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2577 Interactively, ARG is the prefix arg (default 1)
2578 and KILLP is t if a prefix arg was specified."
2579 (interactive "*p\nP")
2580 (when (eq backward-delete-char-untabify-method 'untabify)
2583 (while (and (> count 0) (not (bobp)))
2584 (if (= (preceding-char) ?\t)
2585 (let ((col (current-column)))
2587 (setq col (- col (current-column)))
2588 (insert-char ?\ col)
2591 (setq count (1- count))))))
2592 (delete-backward-char
2593 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2594 ((eq backward-delete-char-untabify-method 'all)
2597 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2599 (+ arg (if (zerop wh) 0 (1- wh))))
2603 (defun zap-to-char (arg char)
2604 "Kill up to and including ARG'th occurrence of CHAR.
2605 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2606 Goes backward if ARG is negative; error if CHAR not found."
2607 (interactive "p\ncZap to char: ")
2608 (kill-region (point) (progn
2609 (search-forward (char-to-string char) nil nil arg)
2610 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2613 ;; kill-line and its subroutines.
2615 (defcustom kill-whole-line nil
2616 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2620 (defun kill-line (&optional arg)
2621 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2622 With prefix argument, kill that many lines from point.
2623 Negative arguments kill lines backward.
2624 With zero argument, kills the text before point on the current line.
2626 When calling from a program, nil means \"no arg\",
2627 a number counts as a prefix arg.
2629 To kill a whole line, when point is not at the beginning, type \
2630 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2632 If `kill-whole-line' is non-nil, then this command kills the whole line
2633 including its terminating newline, when used at the beginning of a line
2634 with no argument. As a consequence, you can always kill a whole line
2635 by typing \\[beginning-of-line] \\[kill-line].
2637 If you want to append the killed line to the last killed text,
2638 use \\[append-next-kill] before \\[kill-line].
2640 If the buffer is read-only, Emacs will beep and refrain from deleting
2641 the line, but put the line in the kill ring anyway. This means that
2642 you can use this command to copy text from a read-only buffer.
2643 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2646 (kill-region (point)
2647 ;; It is better to move point to the other end of the kill
2648 ;; before killing. That way, in a read-only buffer, point
2649 ;; moves across the text that is copied to the kill ring.
2650 ;; The choice has no effect on undo now that undo records
2651 ;; the value of point from before the command was run.
2654 (forward-visible-line (prefix-numeric-value arg))
2656 (signal 'end-of-buffer nil))
2659 (end-of-visible-line) (point))))
2660 (if (or (save-excursion
2661 ;; If trailing whitespace is visible,
2662 ;; don't treat it as nothing.
2663 (unless show-trailing-whitespace
2664 (skip-chars-forward " \t" end))
2666 (and kill-whole-line (bolp)))
2667 (forward-visible-line 1)
2671 (defun kill-whole-line (&optional arg)
2673 With prefix arg, kill that many lines starting from the current line.
2674 If arg is negative, kill backward. Also kill the preceding newline.
2675 \(This is meant to make C-x z work well with negative arguments.\)
2676 If arg is zero, kill current line but exclude the trailing newline."
2678 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2679 (signal 'end-of-buffer nil))
2680 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2681 (signal 'beginning-of-buffer nil))
2682 (unless (eq last-command 'kill-region)
2684 (setq last-command 'kill-region))
2686 ;; We need to kill in two steps, because the previous command
2687 ;; could have been a kill command, in which case the text
2688 ;; before point needs to be prepended to the current kill
2689 ;; ring entry and the text after point appended. Also, we
2690 ;; need to use save-excursion to avoid copying the same text
2691 ;; twice to the kill ring in read-only buffers.
2693 (kill-region (point) (progn (forward-visible-line 0) (point))))
2694 (kill-region (point) (progn (end-of-visible-line) (point))))
2697 (kill-region (point) (progn (end-of-visible-line) (point))))
2698 (kill-region (point)
2699 (progn (forward-visible-line (1+ arg))
2700 (unless (bobp) (backward-char))
2704 (kill-region (point) (progn (forward-visible-line 0) (point))))
2705 (kill-region (point)
2706 (progn (forward-visible-line arg) (point))))))
2708 (defun forward-visible-line (arg)
2709 "Move forward by ARG lines, ignoring currently invisible newlines only.
2710 If ARG is negative, move backward -ARG lines.
2711 If ARG is zero, move to the beginning of the current line."
2716 (or (zerop (forward-line 1))
2717 (signal 'end-of-buffer nil))
2718 ;; If the newline we just skipped is invisible,
2721 (get-char-property (1- (point)) 'invisible)))
2722 (if (if (eq buffer-invisibility-spec t)
2724 (or (memq prop buffer-invisibility-spec)
2725 (assq prop buffer-invisibility-spec)))
2726 (setq arg (1+ arg))))
2727 (setq arg (1- arg)))
2728 ;; If invisible text follows, and it is a number of complete lines,
2730 (let ((opoint (point)))
2731 (while (and (not (eobp))
2733 (get-char-property (point) 'invisible)))
2734 (if (eq buffer-invisibility-spec t)
2736 (or (memq prop buffer-invisibility-spec)
2737 (assq prop buffer-invisibility-spec)))))
2739 (if (get-text-property (point) 'invisible)
2740 (or (next-single-property-change (point) 'invisible)
2742 (next-overlay-change (point)))))
2744 (goto-char opoint))))
2746 (while (or first (<= arg 0))
2749 (or (zerop (forward-line -1))
2750 (signal 'beginning-of-buffer nil)))
2751 ;; If the newline we just moved to is invisible,
2755 (get-char-property (1- (point)) 'invisible)))
2756 (unless (if (eq buffer-invisibility-spec t)
2758 (or (memq prop buffer-invisibility-spec)
2759 (assq prop buffer-invisibility-spec)))
2760 (setq arg (1+ arg)))))
2762 ;; If invisible text follows, and it is a number of complete lines,
2764 (let ((opoint (point)))
2765 (while (and (not (bobp))
2767 (get-char-property (1- (point)) 'invisible)))
2768 (if (eq buffer-invisibility-spec t)
2770 (or (memq prop buffer-invisibility-spec)
2771 (assq prop buffer-invisibility-spec)))))
2773 (if (get-text-property (1- (point)) 'invisible)
2774 (or (previous-single-property-change (point) 'invisible)
2776 (previous-overlay-change (point)))))
2778 (goto-char opoint)))))
2779 ((beginning-of-buffer end-of-buffer)
2782 (defun end-of-visible-line ()
2783 "Move to end of current visible line."
2785 ;; If the following character is currently invisible,
2786 ;; skip all characters with that same `invisible' property value,
2787 ;; then find the next newline.
2788 (while (and (not (eobp))
2790 (skip-chars-forward "^\n")
2792 (get-char-property (point) 'invisible)))
2793 (if (eq buffer-invisibility-spec t)
2795 (or (memq prop buffer-invisibility-spec)
2796 (assq prop buffer-invisibility-spec))))))
2797 (skip-chars-forward "^\n")
2798 (if (get-text-property (point) 'invisible)
2799 (goto-char (next-single-property-change (point) 'invisible))
2800 (goto-char (next-overlay-change (point))))
2803 (defun insert-buffer (buffer)
2804 "Insert after point the contents of BUFFER.
2805 Puts mark after the inserted text.
2806 BUFFER may be a buffer or a buffer name.
2808 This function is meant for the user to run interactively.
2809 Don't call it from programs: use `insert-buffer-substring' instead!"
2813 (barf-if-buffer-read-only)
2814 (read-buffer "Insert buffer: "
2815 (if (eq (selected-window) (next-window (selected-window)))
2816 (other-buffer (current-buffer))
2817 (window-buffer (next-window (selected-window))))
2821 (insert-buffer-substring (get-buffer buffer))
2825 (defun append-to-buffer (buffer start end)
2826 "Append to specified buffer the text of the region.
2827 It is inserted into that buffer before its point.
2829 When calling from a program, give three arguments:
2830 BUFFER (or buffer name), START and END.
2831 START and END specify the portion of the current buffer to be copied."
2833 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
2834 (region-beginning) (region-end)))
2835 (let ((oldbuf (current-buffer)))
2837 (let* ((append-to (get-buffer-create buffer))
2838 (windows (get-buffer-window-list append-to t t))
2840 (set-buffer append-to)
2841 (setq point (point))
2842 (barf-if-buffer-read-only)
2843 (insert-buffer-substring oldbuf start end)
2844 (dolist (window windows)
2845 (when (= (window-point window) point)
2846 (set-window-point window (point))))))))
2848 (defun prepend-to-buffer (buffer start end)
2849 "Prepend to specified buffer the text of the region.
2850 It is inserted into that buffer after its point.
2852 When calling from a program, give three arguments:
2853 BUFFER (or buffer name), START and END.
2854 START and END specify the portion of the current buffer to be copied."
2855 (interactive "BPrepend to buffer: \nr")
2856 (let ((oldbuf (current-buffer)))
2858 (set-buffer (get-buffer-create buffer))
2859 (barf-if-buffer-read-only)
2861 (insert-buffer-substring oldbuf start end)))))
2863 (defun copy-to-buffer (buffer start end)
2864 "Copy to specified buffer the text of the region.
2865 It is inserted into that buffer, replacing existing text there.
2867 When calling from a program, give three arguments:
2868 BUFFER (or buffer name), START and END.
2869 START and END specify the portion of the current buffer to be copied."
2870 (interactive "BCopy to buffer: \nr")
2871 (let ((oldbuf (current-buffer)))
2873 (set-buffer (get-buffer-create buffer))
2874 (barf-if-buffer-read-only)
2877 (insert-buffer-substring oldbuf start end)))))
2879 (put 'mark-inactive 'error-conditions '(mark-inactive error))
2880 (put 'mark-inactive 'error-message "The mark is not active now")
2882 (defun mark (&optional force)
2883 "Return this buffer's mark value as integer; error if mark inactive.
2884 If optional argument FORCE is non-nil, access the mark value
2885 even if the mark is not currently active, and return nil
2886 if there is no mark at all.
2888 If you are using this in an editing command, you are most likely making
2889 a mistake; see the documentation of `set-mark'."
2890 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
2891 (marker-position (mark-marker))
2892 (signal 'mark-inactive nil)))
2894 ;; Many places set mark-active directly, and several of them failed to also
2895 ;; run deactivate-mark-hook. This shorthand should simplify.
2896 (defsubst deactivate-mark ()
2897 "Deactivate the mark by setting `mark-active' to nil.
2898 \(That makes a difference only in Transient Mark mode.)
2899 Also runs the hook `deactivate-mark-hook'."
2901 ((eq transient-mark-mode 'lambda)
2902 (setq transient-mark-mode nil))
2903 (transient-mark-mode
2904 (setq mark-active nil)
2905 (run-hooks 'deactivate-mark-hook))))
2907 (defun set-mark (pos)
2908 "Set this buffer's mark to POS. Don't use this function!
2909 That is to say, don't use this function unless you want
2910 the user to see that the mark has moved, and you want the previous
2911 mark position to be lost.
2913 Normally, when a new mark is set, the old one should go on the stack.
2914 This is why most applications should use push-mark, not set-mark.
2916 Novice Emacs Lisp programmers often try to use the mark for the wrong
2917 purposes. The mark saves a location for the user's convenience.
2918 Most editing commands should not alter the mark.
2919 To remember a location for internal use in the Lisp program,
2920 store it in a Lisp variable. Example:
2922 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
2926 (setq mark-active t)
2927 (run-hooks 'activate-mark-hook)
2928 (set-marker (mark-marker) pos (current-buffer)))
2929 ;; Normally we never clear mark-active except in Transient Mark mode.
2930 ;; But when we actually clear out the mark value too,
2931 ;; we must clear mark-active in any mode.
2932 (setq mark-active nil)
2933 (run-hooks 'deactivate-mark-hook)
2934 (set-marker (mark-marker) nil)))
2936 (defvar mark-ring nil
2937 "The list of former marks of the current buffer, most recent first.")
2938 (make-variable-buffer-local 'mark-ring)
2939 (put 'mark-ring 'permanent-local t)
2941 (defcustom mark-ring-max 16
2942 "*Maximum size of mark ring. Start discarding off end if gets this big."
2944 :group 'editing-basics)
2946 (defvar global-mark-ring nil
2947 "The list of saved global marks, most recent first.")
2949 (defcustom global-mark-ring-max 16
2950 "*Maximum size of global mark ring. \
2951 Start discarding off end if gets this big."
2953 :group 'editing-basics)
2955 (defun pop-to-mark-command ()
2956 "Jump to mark, and pop a new position for mark off the ring
2957 \(does not affect global mark ring\)."
2960 (error "No mark set in this buffer")
2961 (goto-char (mark t))
2964 (defun push-mark-command (arg &optional nomsg)
2965 "Set mark at where point is.
2966 If no prefix arg and mark is already set there, just activate it.
2967 Display `Mark set' unless the optional second arg NOMSG is non-nil."
2969 (let ((mark (marker-position (mark-marker))))
2970 (if (or arg (null mark) (/= mark (point)))
2971 (push-mark nil nomsg t)
2972 (setq mark-active t)
2974 (message "Mark activated")))))
2976 (defun set-mark-command (arg)
2977 "Set mark at where point is, or jump to mark.
2978 With no prefix argument, set mark, and push old mark position on local
2979 mark ring; also push mark on global mark ring if last mark was set in
2980 another buffer. Immediately repeating the command activates
2981 `transient-mark-mode' temporarily.
2983 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
2984 jump to mark, and pop a new position
2985 for mark off the local mark ring \(this does not affect the global
2986 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
2987 mark ring \(see `pop-global-mark'\).
2989 Repeating the \\[set-mark-command] command without the prefix jumps to
2990 the next position off the local (or global) mark ring.
2992 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
2993 \\[universal-argument] \\[set-mark-command], unconditionally
2994 set mark where point is.
2996 Novice Emacs Lisp programmers often try to use the mark for the wrong
2997 purposes. See the documentation of `set-mark' for more information."
2999 (if (eq transient-mark-mode 'lambda)
3000 (setq transient-mark-mode nil))
3002 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3003 (push-mark-command nil))
3004 ((not (eq this-command 'set-mark-command))
3006 (pop-to-mark-command)
3007 (push-mark-command t)))
3008 ((eq last-command 'pop-to-mark-command)
3009 (setq this-command 'pop-to-mark-command)
3010 (pop-to-mark-command))
3011 ((and (eq last-command 'pop-global-mark) (not arg))
3012 (setq this-command 'pop-global-mark)
3015 (setq this-command 'pop-to-mark-command)
3016 (pop-to-mark-command))
3017 ((and (eq last-command 'set-mark-command)
3018 mark-active (null transient-mark-mode))
3019 (setq transient-mark-mode 'lambda)
3020 (message "Transient-mark-mode temporarily enabled"))
3022 (push-mark-command nil))))
3024 (defun push-mark (&optional location nomsg activate)
3025 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3026 If the last global mark pushed was not in the current buffer,
3027 also push LOCATION on the global mark ring.
3028 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3029 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
3031 Novice Emacs Lisp programmers often try to use the mark for the wrong
3032 purposes. See the documentation of `set-mark' for more information.
3034 In Transient Mark mode, this does not activate the mark."
3035 (unless (null (mark t))
3036 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3037 (when (> (length mark-ring) mark-ring-max)
3038 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3039 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3040 (set-marker (mark-marker) (or location (point)) (current-buffer))
3041 ;; Now push the mark on the global mark ring.
3042 (if (and global-mark-ring
3043 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3044 ;; The last global mark pushed was in this same buffer.
3045 ;; Don't push another one.
3047 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3048 (when (> (length global-mark-ring) global-mark-ring-max)
3049 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3050 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3051 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3052 (message "Mark set"))
3053 (if (or activate (not transient-mark-mode))
3054 (set-mark (mark t)))
3058 "Pop off mark ring into the buffer's actual mark.
3059 Does not set point. Does nothing if mark ring is empty."
3061 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3062 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3063 (move-marker (car mark-ring) nil)
3064 (if (null (mark t)) (ding))
3065 (setq mark-ring (cdr mark-ring)))
3068 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3069 (defun exchange-point-and-mark (&optional arg)
3070 "Put the mark where point is now, and point where the mark is now.
3071 This command works even when the mark is not active,
3072 and it reactivates the mark.
3073 With prefix arg, `transient-mark-mode' is enabled temporarily."
3077 (if (null transient-mark-mode)
3078 (setq transient-mark-mode 'lambda))
3081 (let ((omark (mark t)))
3083 (error "No mark set in this buffer"))
3088 (define-minor-mode transient-mark-mode
3089 "Toggle Transient Mark mode.
3090 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
3092 In Transient Mark mode, when the mark is active, the region is highlighted.
3093 Changing the buffer \"deactivates\" the mark.
3094 So do certain other operations that set the mark
3095 but whose main purpose is something else--for example,
3096 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3098 You can also deactivate the mark by typing \\[keyboard-quit] or
3099 \\[keyboard-escape-quit].
3101 Many commands change their behavior when Transient Mark mode is in effect
3102 and the mark is active, by acting on the region instead of their usual
3103 default part of the buffer's text. Examples of such commands include
3104 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3105 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3106 Invoke \\[apropos-documentation] and type \"transient\" or
3107 \"mark.*active\" at the prompt, to see the documentation of
3108 commands which are sensitive to the Transient Mark mode."
3109 :global t :group 'editing-basics :require nil)
3111 (defun pop-global-mark ()
3112 "Pop off global mark ring and jump to the top location."
3114 ;; Pop entries which refer to non-existent buffers.
3115 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3116 (setq global-mark-ring (cdr global-mark-ring)))
3117 (or global-mark-ring
3118 (error "No global mark set"))
3119 (let* ((marker (car global-mark-ring))
3120 (buffer (marker-buffer marker))
3121 (position (marker-position marker)))
3122 (setq global-mark-ring (nconc (cdr global-mark-ring)
3123 (list (car global-mark-ring))))
3125 (or (and (>= position (point-min))
3126 (<= position (point-max)))
3128 (goto-char position)
3129 (switch-to-buffer buffer)))
3131 (defcustom next-line-add-newlines nil
3132 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3135 :group 'editing-basics)
3137 (defun next-line (&optional arg)
3138 "Move cursor vertically down ARG lines.
3139 If there is no character in the target line exactly under the current column,
3140 the cursor is positioned after the character in that line which spans this
3141 column, or at the end of the line if it is not long enough.
3142 If there is no line in the buffer after this one, behavior depends on the
3143 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3144 to create a line, and moves the cursor to that line. Otherwise it moves the
3145 cursor to the end of the buffer.
3147 The command \\[set-goal-column] can be used to create
3148 a semipermanent goal column for this command.
3149 Then instead of trying to move exactly vertically (or as close as possible),
3150 this command moves to the specified goal column (or as close as possible).
3151 The goal column is stored in the variable `goal-column', which is nil
3152 when there is no goal column.
3154 If you are thinking of using this in a Lisp program, consider
3155 using `forward-line' instead. It is usually easier to use
3156 and more reliable (no dependence on goal column, etc.)."
3158 (or arg (setq arg 1))
3159 (if (and next-line-add-newlines (= arg 1))
3160 (if (save-excursion (end-of-line) (eobp))
3161 ;; When adding a newline, don't expand an abbrev.
3162 (let ((abbrev-mode nil))
3165 (line-move arg nil nil t))
3168 (line-move arg nil nil t)
3169 ((beginning-of-buffer end-of-buffer) (ding)))
3170 (line-move arg nil nil t)))
3173 (defun previous-line (&optional arg)
3174 "Move cursor vertically up ARG lines.
3175 If there is no character in the target line exactly over the current column,
3176 the cursor is positioned after the character in that line which spans this
3177 column, or at the end of the line if it is not long enough.
3179 The command \\[set-goal-column] can be used to create
3180 a semipermanent goal column for this command.
3181 Then instead of trying to move exactly vertically (or as close as possible),
3182 this command moves to the specified goal column (or as close as possible).
3183 The goal column is stored in the variable `goal-column', which is nil
3184 when there is no goal column.
3186 If you are thinking of using this in a Lisp program, consider using
3187 `forward-line' with a negative argument instead. It is usually easier
3188 to use and more reliable (no dependence on goal column, etc.)."
3190 (or arg (setq arg 1))
3193 (line-move (- arg) nil nil t)
3194 ((beginning-of-buffer end-of-buffer) (ding)))
3195 (line-move (- arg) nil nil t))
3198 (defcustom track-eol nil
3199 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
3200 This means moving to the end of each line moved onto.
3201 The beginning of a blank line does not count as the end of a line."
3203 :group 'editing-basics)
3205 (defcustom goal-column nil
3206 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3207 :type '(choice integer
3208 (const :tag "None" nil))
3209 :group 'editing-basics)
3210 (make-variable-buffer-local 'goal-column)
3212 (defvar temporary-goal-column 0
3213 "Current goal column for vertical motion.
3214 It is the column where point was
3215 at the start of current run of vertical motion commands.
3216 When the `track-eol' feature is doing its job, the value is 9999.")
3218 (defcustom line-move-ignore-invisible t
3219 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3220 Outline mode sets this."
3222 :group 'editing-basics)
3224 (defun line-move-invisible-p (pos)
3225 "Return non-nil if the character after POS is currently invisible."
3227 (get-char-property pos 'invisible)))
3228 (if (eq buffer-invisibility-spec t)
3230 (or (memq prop buffer-invisibility-spec)
3231 (assq prop buffer-invisibility-spec)))))
3233 ;; Perform vertical scrolling of tall images if necessary.
3234 (defun line-move (arg &optional noerror to-end try-vscroll)
3235 (if (and auto-window-vscroll try-vscroll)
3236 (let ((forward (> arg 0))
3237 (part (nth 2 (pos-visible-in-window-p (point) nil t))))
3238 (if (and (consp part)
3239 (> (setq part (if forward (cdr part) (car part))) 0))
3240 (set-window-vscroll nil
3242 (+ (window-vscroll nil t)
3244 (* (frame-char-height) arg)))
3246 (- (window-vscroll nil t)
3248 (* (frame-char-height) (- arg))))))
3250 (set-window-vscroll nil 0)
3251 (when (line-move-1 arg noerror to-end)
3253 (if (and (not forward)
3254 (setq part (nth 2 (pos-visible-in-window-p
3255 (line-beginning-position) nil t)))
3257 (set-window-vscroll nil (cdr part) t))
3259 (line-move-1 arg noerror to-end)))
3261 ;; This is the guts of next-line and previous-line.
3262 ;; Arg says how many lines to move.
3263 ;; The value is t if we can move the specified number of lines.
3264 (defun line-move-1 (arg &optional noerror to-end)
3265 ;; Don't run any point-motion hooks, and disregard intangibility,
3266 ;; for intermediate positions.
3267 (let ((inhibit-point-motion-hooks t)
3269 (forward (> arg 0)))
3272 (if (not (memq last-command '(next-line previous-line)))
3273 (setq temporary-goal-column
3274 (if (and track-eol (eolp)
3275 ;; Don't count beg of empty line as end of line
3276 ;; unless we just did explicit end-of-line.
3277 (or (not (bolp)) (eq last-command 'end-of-line)))
3281 (if (and (not (integerp selective-display))
3282 (not line-move-ignore-invisible))
3283 ;; Use just newline characters.
3284 ;; Set ARG to 0 if we move as many lines as requested.
3286 (progn (if (> arg 1) (forward-line (1- arg)))
3287 ;; This way of moving forward ARG lines
3288 ;; verifies that we have a newline after the last one.
3289 ;; It doesn't get confused by intangible text.
3291 (if (zerop (forward-line 1))
3293 (and (zerop (forward-line arg))
3297 (signal (if (< arg 0)
3298 'beginning-of-buffer
3301 ;; Move by arg lines, but ignore invisible ones.
3303 (while (and (> arg 0) (not done))
3304 ;; If the following character is currently invisible,
3305 ;; skip all characters with that same `invisible' property value.
3306 (while (and (not (eobp)) (line-move-invisible-p (point)))
3307 (goto-char (next-char-property-change (point))))
3310 (and (zerop (vertical-motion 1))
3312 (signal 'end-of-buffer nil)
3315 (setq arg (1- arg))))
3316 (while (and (< arg 0) (not done))
3319 (if (zerop (vertical-motion -1))
3321 (signal 'beginning-of-buffer nil)
3325 (while (and ;; Don't move over previous invis lines
3326 ;; if our target is the middle of this line.
3327 (or (zerop (or goal-column temporary-goal-column))
3329 (not (bobp)) (line-move-invisible-p (1- (point))))
3330 (goto-char (previous-char-property-change (point))))))))
3331 ;; This is the value the function returns.
3335 ;; If we did not move down as far as desired,
3336 ;; at least go to end of line.
3339 ;; If we did not move down as far as desired,
3340 ;; at least go to end of line.
3341 (beginning-of-line))
3343 (line-move-finish (or goal-column temporary-goal-column)
3344 opoint forward))))))
3346 (defun line-move-finish (column opoint forward)
3349 ;; Set REPEAT to t to repeat the whole thing.
3353 (line-beg (save-excursion (beginning-of-line) (point)))
3355 ;; Compute the end of the line
3356 ;; ignoring effectively invisible newlines.
3359 (while (and (not (eobp)) (line-move-invisible-p (point)))
3360 (goto-char (next-char-property-change (point)))
3364 ;; Move to the desired column.
3365 (line-move-to-column column)
3368 ;; Process intangibility within a line.
3369 ;; Move to the chosen destination position from above,
3370 ;; with intangibility processing enabled.
3372 (goto-char (point-min))
3373 (let ((inhibit-point-motion-hooks nil))
3376 ;; If intangibility moves us to a different (later) place
3377 ;; in the same line, use that as the destination.
3378 (if (<= (point) line-end)
3380 ;; If that position is "too late",
3381 ;; try the previous allowable position.
3385 ;; If going forward, don't accept the previous
3386 ;; allowable position if it is before the target line.
3387 (< line-beg (point))
3388 ;; If going backward, don't accept the previous
3389 ;; allowable position if it is still after the target line.
3390 (<= (point) line-end))
3392 ;; As a last resort, use the end of the line.
3393 (setq new line-end))))
3395 ;; Now move to the updated destination, processing fields
3396 ;; as well as intangibility.
3398 (let ((inhibit-point-motion-hooks nil))
3400 (constrain-to-field new opoint nil t
3401 'inhibit-line-move-field-capture)))
3403 ;; If all this moved us to a different line,
3404 ;; retry everything within that new line.
3405 (when (or (< (point) line-beg) (> (point) line-end))
3406 ;; Repeat the intangibility and field processing.
3407 (setq repeat t))))))
3409 (defun line-move-to-column (col)
3410 "Try to find column COL, considering invisibility.
3411 This function works only in certain cases,
3412 because what we really need is for `move-to-column'
3413 and `current-column' to be able to ignore invisible text."
3416 (move-to-column col))
3418 (when (and line-move-ignore-invisible
3419 (not (bolp)) (line-move-invisible-p (1- (point))))
3420 (let ((normal-location (point))
3421 (normal-column (current-column)))
3422 ;; If the following character is currently invisible,
3423 ;; skip all characters with that same `invisible' property value.
3424 (while (and (not (eobp))
3425 (line-move-invisible-p (point)))
3426 (goto-char (next-char-property-change (point))))
3427 ;; Have we advanced to a larger column position?
3428 (if (> (current-column) normal-column)
3429 ;; We have made some progress towards the desired column.
3430 ;; See if we can make any further progress.
3431 (line-move-to-column (+ (current-column) (- col normal-column)))
3432 ;; Otherwise, go to the place we originally found
3433 ;; and move back over invisible text.
3434 ;; that will get us to the same place on the screen
3435 ;; but with a more reasonable buffer position.
3436 (goto-char normal-location)
3437 (let ((line-beg (save-excursion (beginning-of-line) (point))))
3438 (while (and (not (bolp)) (line-move-invisible-p (1- (point))))
3439 (goto-char (previous-char-property-change (point) line-beg))))))))
3441 (defun move-end-of-line (arg)
3442 "Move point to end of current line.
3443 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3444 If point reaches the beginning or end of buffer, it stops there.
3445 To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3447 This command does not move point across a field boundary unless doing so
3448 would move beyond there to a different line; if ARG is nil or 1, and
3449 point starts at a field boundary, point does not move. To ignore field
3450 boundaries bind `inhibit-field-text-motion' to t."
3452 (or arg (setq arg 1))
3457 (let ((goal-column 0))
3458 (and (line-move arg t)
3461 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3462 (goto-char (previous-char-property-change (point))))
3466 (if (and (> (point) newpos)
3467 (eq (preceding-char) ?\n))
3469 (if (and (> (point) newpos) (not (eobp))
3470 (not (eq (following-char) ?\n)))
3471 ;; If we skipped something intangible
3472 ;; and now we're not really at eol,
3477 ;;; Many people have said they rarely use this feature, and often type
3478 ;;; it by accident. Maybe it shouldn't even be on a key.
3479 (put 'set-goal-column 'disabled t)
3481 (defun set-goal-column (arg)
3482 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3483 Those commands will move to this position in the line moved to
3484 rather than trying to keep the same horizontal position.
3485 With a non-nil argument, clears out the goal column
3486 so that \\[next-line] and \\[previous-line] resume vertical motion.
3487 The goal column is stored in the variable `goal-column'."
3491 (setq goal-column nil)
3492 (message "No goal column"))
3493 (setq goal-column (current-column))
3494 (message (substitute-command-keys
3495 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3500 (defun scroll-other-window-down (lines)
3501 "Scroll the \"other window\" down.
3502 For more details, see the documentation for `scroll-other-window'."
3504 (scroll-other-window
3505 ;; Just invert the argument's meaning.
3506 ;; We can do that without knowing which window it will be.
3507 (if (eq lines '-) nil
3509 (- (prefix-numeric-value lines))))))
3510 (define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
3512 (defun beginning-of-buffer-other-window (arg)
3513 "Move point to the beginning of the buffer in the other window.
3514 Leave mark at previous position.
3515 With arg N, put point N/10 of the way from the true beginning."
3517 (let ((orig-window (selected-window))
3518 (window (other-window-for-scrolling)))
3519 ;; We use unwind-protect rather than save-window-excursion
3520 ;; because the latter would preserve the things we want to change.
3523 (select-window window)
3524 ;; Set point and mark in that window's buffer.
3526 (beginning-of-buffer arg))
3527 ;; Set point accordingly.
3529 (select-window orig-window))))
3531 (defun end-of-buffer-other-window (arg)
3532 "Move point to the end of the buffer in the other window.
3533 Leave mark at previous position.
3534 With arg N, put point N/10 of the way from the true end."
3536 ;; See beginning-of-buffer-other-window for comments.
3537 (let ((orig-window (selected-window))
3538 (window (other-window-for-scrolling)))
3541 (select-window window)
3543 (end-of-buffer arg))
3545 (select-window orig-window))))
3547 (defun transpose-chars (arg)
3548 "Interchange characters around point, moving forward one character.
3549 With prefix arg ARG, effect is to take character before point
3550 and drag it forward past ARG other characters (backward if ARG negative).
3551 If no argument and at end of line, the previous two chars are exchanged."
3553 (and (null arg) (eolp) (forward-char -1))
3554 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3556 (defun transpose-words (arg)
3557 "Interchange words around point, leaving point at end of them.
3558 With prefix arg ARG, effect is to take word before or around point
3559 and drag it forward past ARG other words (backward if ARG negative).
3560 If ARG is zero, the words around or after point and around or after mark
3562 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3564 (transpose-subr 'forward-word arg))
3566 (defun transpose-sexps (arg)
3567 "Like \\[transpose-words] but applies to sexps.
3568 Does not work on a sexp that point is in the middle of
3569 if it is a list or string."
3573 ;; Here we should try to simulate the behavior of
3574 ;; (cons (progn (forward-sexp x) (point))
3575 ;; (progn (forward-sexp (- x)) (point)))
3576 ;; Except that we don't want to rely on the second forward-sexp
3577 ;; putting us back to where we want to be, since forward-sexp-function
3578 ;; might do funny things like infix-precedence.
3580 (looking-at "\\sw\\|\\s_")
3582 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3583 ;; Jumping over a symbol. We might be inside it, mind you.
3584 (progn (funcall (if (> arg 0)
3585 'skip-syntax-backward 'skip-syntax-forward)
3587 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3588 ;; Otherwise, we're between sexps. Take a step back before jumping
3589 ;; to make sure we'll obey the same precedence no matter which direction
3591 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3592 (cons (save-excursion (forward-sexp arg) (point))
3593 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3594 (not (zerop (funcall (if (> arg 0)
3595 'skip-syntax-forward
3596 'skip-syntax-backward)
3601 (defun transpose-lines (arg)
3602 "Exchange current line and previous line, leaving point after both.
3603 With argument ARG, takes previous line and moves it past ARG lines.
3604 With argument 0, interchanges line point is in with line mark is in."
3606 (transpose-subr (function
3610 ;; Move forward over ARG lines,
3611 ;; but create newlines if necessary.
3612 (setq arg (forward-line arg))
3613 (if (/= (preceding-char) ?\n)
3614 (setq arg (1+ arg)))
3617 (forward-line arg))))
3620 (defun transpose-subr (mover arg &optional special)
3621 (let ((aux (if special mover
3623 (cons (progn (funcall mover x) (point))
3624 (progn (funcall mover (- x)) (point))))))
3629 (setq pos1 (funcall aux 1))
3631 (setq pos2 (funcall aux 1))
3632 (transpose-subr-1 pos1 pos2))
3633 (exchange-point-and-mark))
3635 (setq pos1 (funcall aux -1))
3636 (setq pos2 (funcall aux arg))
3637 (transpose-subr-1 pos1 pos2)
3638 (goto-char (car pos2)))
3640 (setq pos1 (funcall aux -1))
3641 (goto-char (car pos1))
3642 (setq pos2 (funcall aux arg))
3643 (transpose-subr-1 pos1 pos2)))))
3645 (defun transpose-subr-1 (pos1 pos2)
3646 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3647 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3648 (when (> (car pos1) (car pos2))
3650 (setq pos1 pos2 pos2 swap)))
3651 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3652 (atomic-change-group
3654 ;; FIXME: We first delete the two pieces of text, so markers that
3655 ;; used to point to after the text end up pointing to before it :-(
3656 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3657 (goto-char (car pos2))
3658 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3659 (goto-char (car pos1))
3662 (defun backward-word (&optional arg)
3663 "Move backward until encountering the beginning of a word.
3664 With argument, do this that many times."
3666 (forward-word (- (or arg 1))))
3668 (defun mark-word (&optional arg allow-extend)
3669 "Set mark ARG words away from point.
3670 The place mark goes is the same place \\[forward-word] would
3671 move to with the same argument.
3672 Interactively, if this command is repeated
3673 or (in Transient Mark mode) if the mark is active,
3674 it marks the next ARG words after the ones already marked."
3675 (interactive "P\np")
3676 (cond ((and allow-extend
3677 (or (and (eq last-command this-command) (mark t))
3678 (and transient-mark-mode mark-active)))
3679 (setq arg (if arg (prefix-numeric-value arg)
3680 (if (< (mark) (point)) -1 1)))
3689 (forward-word (prefix-numeric-value arg))
3693 (defun kill-word (arg)
3694 "Kill characters forward until encountering the end of a word.
3695 With argument, do this that many times."
3697 (kill-region (point) (progn (forward-word arg) (point))))
3699 (defun backward-kill-word (arg)
3700 "Kill characters backward until encountering the end of a word.
3701 With argument, do this that many times."
3703 (kill-word (- arg)))
3705 (defun current-word (&optional strict really-word)
3706 "Return the symbol or word that point is on (or a nearby one) as a string.
3707 The return value includes no text properties.
3708 If optional arg STRICT is non-nil, return nil unless point is within
3709 or adjacent to a symbol or word. In all cases the value can be nil
3710 if there is no word nearby.
3711 The function, belying its name, normally finds a symbol.
3712 If optional arg REALLY-WORD is non-nil, it finds just a word."
3714 (let* ((oldpoint (point)) (start (point)) (end (point))
3715 (syntaxes (if really-word "w" "w_"))
3716 (not-syntaxes (concat "^" syntaxes)))
3717 (skip-syntax-backward syntaxes) (setq start (point))
3718 (goto-char oldpoint)
3719 (skip-syntax-forward syntaxes) (setq end (point))
3720 (when (and (eq start oldpoint) (eq end oldpoint)
3721 ;; Point is neither within nor adjacent to a word.
3723 ;; Look for preceding word in same line.
3724 (skip-syntax-backward not-syntaxes
3725 (save-excursion (beginning-of-line)
3728 ;; No preceding word in same line.
3729 ;; Look for following word in same line.
3731 (skip-syntax-forward not-syntaxes
3732 (save-excursion (end-of-line)
3734 (setq start (point))
3735 (skip-syntax-forward syntaxes)
3738 (skip-syntax-backward syntaxes)
3739 (setq start (point))))
3740 ;; If we found something nonempty, return it as a string.
3741 (unless (= start end)
3742 (buffer-substring-no-properties start end)))))
3744 (defcustom fill-prefix nil
3745 "*String for filling to insert at front of new line, or nil for none."
3746 :type '(choice (const :tag "None" nil)
3749 (make-variable-buffer-local 'fill-prefix)
3751 (defcustom auto-fill-inhibit-regexp nil
3752 "*Regexp to match lines which should not be auto-filled."
3753 :type '(choice (const :tag "None" nil)
3757 (defvar comment-line-break-function 'comment-indent-new-line
3758 "*Mode-specific function which line breaks and continues a comment.
3760 This function is only called during auto-filling of a comment section.
3761 The function should take a single optional argument, which is a flag
3762 indicating whether it should use soft newlines.
3764 Setting this variable automatically makes it local to the current buffer.")
3766 ;; This function is used as the auto-fill-function of a buffer
3767 ;; when Auto-Fill mode is enabled.
3768 ;; It returns t if it really did any work.
3769 ;; (Actually some major modes use a different auto-fill function,
3770 ;; but this one is the default one.)
3771 (defun do-auto-fill ()
3772 (let (fc justify give-up
3773 (fill-prefix fill-prefix))
3774 (if (or (not (setq justify (current-justification)))
3775 (null (setq fc (current-fill-column)))
3776 (and (eq justify 'left)
3777 (<= (current-column) fc))
3778 (and auto-fill-inhibit-regexp
3779 (save-excursion (beginning-of-line)
3780 (looking-at auto-fill-inhibit-regexp))))
3781 nil ;; Auto-filling not required
3782 (if (memq justify '(full center right))
3783 (save-excursion (unjustify-current-line)))
3785 ;; Choose a fill-prefix automatically.
3786 (when (and adaptive-fill-mode
3787 (or (null fill-prefix) (string= fill-prefix "")))
3789 (fill-context-prefix
3790 (save-excursion (backward-paragraph 1) (point))
3791 (save-excursion (forward-paragraph 1) (point)))))
3792 (and prefix (not (equal prefix ""))
3793 ;; Use auto-indentation rather than a guessed empty prefix.
3794 (not (and fill-indent-according-to-mode
3795 (string-match "\\`[ \t]*\\'" prefix)))
3796 (setq fill-prefix prefix))))
3798 (while (and (not give-up) (> (current-column) fc))
3799 ;; Determine where to split the line.
3804 (setq after-prefix (point))
3806 (looking-at (regexp-quote fill-prefix))
3807 (setq after-prefix (match-end 0)))
3808 (move-to-column (1+ fc))
3809 (fill-move-to-break-point after-prefix)
3812 ;; See whether the place we found is any good.
3814 (goto-char fill-point)
3816 ;; There is no use breaking at end of line.
3817 (save-excursion (skip-chars-forward " ") (eolp))
3818 ;; It is futile to split at the end of the prefix
3819 ;; since we would just insert the prefix again.
3820 (and after-prefix (<= (point) after-prefix))
3821 ;; Don't split right after a comment starter
3822 ;; since we would just make another comment starter.
3823 (and comment-start-skip
3824 (let ((limit (point)))
3826 (and (re-search-forward comment-start-skip
3828 (eq (point) limit))))))
3829 ;; No good place to break => stop trying.
3831 ;; Ok, we have a useful place to break the line. Do it.
3832 (let ((prev-column (current-column)))
3833 ;; If point is at the fill-point, do not `save-excursion'.
3834 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
3835 ;; point will end up before it rather than after it.
3837 (skip-chars-backward " \t")
3838 (= (point) fill-point))
3839 (funcall comment-line-break-function t)
3841 (goto-char fill-point)
3842 (funcall comment-line-break-function t)))
3843 ;; Now do justification, if required
3844 (if (not (eq justify 'left))
3847 (justify-current-line justify nil t)))
3848 ;; If making the new line didn't reduce the hpos of
3849 ;; the end of the line, then give up now;
3850 ;; trying again will not help.
3851 (if (>= (current-column) prev-column)
3852 (setq give-up t))))))
3853 ;; Justify last line.
3854 (justify-current-line justify t t)
3857 (defvar normal-auto-fill-function 'do-auto-fill
3858 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
3859 Some major modes set this.")
3861 ;; FIXME: turn into a proper minor mode.
3862 ;; Add a global minor mode version of it.
3863 (defun auto-fill-mode (&optional arg)
3864 "Toggle Auto Fill mode.
3865 With arg, turn Auto Fill mode on if and only if arg is positive.
3866 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
3867 automatically breaks the line at a previous space.
3869 The value of `normal-auto-fill-function' specifies the function to use
3870 for `auto-fill-function' when turning Auto Fill mode on."
3872 (prog1 (setq auto-fill-function
3874 (not auto-fill-function)
3875 (> (prefix-numeric-value arg) 0))
3876 normal-auto-fill-function
3878 (force-mode-line-update)))
3880 ;; This holds a document string used to document auto-fill-mode.
3881 (defun auto-fill-function ()
3882 "Automatically break line at a previous space, in insertion of text."
3885 (defun turn-on-auto-fill ()
3886 "Unconditionally turn on Auto Fill mode."
3889 (defun turn-off-auto-fill ()
3890 "Unconditionally turn off Auto Fill mode."
3891 (auto-fill-mode -1))
3893 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
3895 (defun set-fill-column (arg)
3896 "Set `fill-column' to specified argument.
3897 Use \\[universal-argument] followed by a number to specify a column.
3898 Just \\[universal-argument] as argument means to use the current column."
3901 (setq arg (current-column)))
3902 (if (not (integerp arg))
3903 ;; Disallow missing argument; it's probably a typo for C-x C-f.
3904 (error "Set-fill-column requires an explicit argument")
3905 (message "Fill column set to %d (was %d)" arg fill-column)
3906 (setq fill-column arg)))
3908 (defun set-selective-display (arg)
3909 "Set `selective-display' to ARG; clear it if no arg.
3910 When the value of `selective-display' is a number > 0,
3911 lines whose indentation is >= that value are not displayed.
3912 The variable `selective-display' has a separate value for each buffer."
3914 (if (eq selective-display t)
3915 (error "selective-display already in use for marked lines"))
3918 (narrow-to-region (point-min) (point))
3919 (goto-char (window-start))
3920 (vertical-motion (window-height)))))
3921 (setq selective-display
3922 (and arg (prefix-numeric-value arg)))
3923 (recenter current-vpos))
3924 (set-window-start (selected-window) (window-start (selected-window)))
3925 (princ "selective-display set to " t)
3926 (prin1 selective-display t)
3929 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
3930 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
3932 (defun toggle-truncate-lines (arg)
3933 "Toggle whether to fold or truncate long lines on the screen.
3934 With arg, truncate long lines iff arg is positive.
3935 Note that in side-by-side windows, truncation is always enabled."
3937 (setq truncate-lines
3939 (not truncate-lines)
3940 (> (prefix-numeric-value arg) 0)))
3941 (force-mode-line-update)
3942 (unless truncate-lines
3943 (let ((buffer (current-buffer)))
3944 (walk-windows (lambda (window)
3945 (if (eq buffer (window-buffer window))
3946 (set-window-hscroll window 0)))
3948 (message "Truncate long lines %s"
3949 (if truncate-lines "enabled" "disabled")))
3951 (defvar overwrite-mode-textual " Ovwrt"
3952 "The string displayed in the mode line when in overwrite mode.")
3953 (defvar overwrite-mode-binary " Bin Ovwrt"
3954 "The string displayed in the mode line when in binary overwrite mode.")
3956 (defun overwrite-mode (arg)
3957 "Toggle overwrite mode.
3958 With arg, turn overwrite mode on iff arg is positive.
3959 In overwrite mode, printing characters typed in replace existing text
3960 on a one-for-one basis, rather than pushing it to the right. At the
3961 end of a line, such characters extend the line. Before a tab,
3962 such characters insert until the tab is filled in.
3963 \\[quoted-insert] still inserts characters in overwrite mode; this
3964 is supposed to make it easier to insert characters when necessary."
3966 (setq overwrite-mode
3967 (if (if (null arg) (not overwrite-mode)
3968 (> (prefix-numeric-value arg) 0))
3969 'overwrite-mode-textual))
3970 (force-mode-line-update))
3972 (defun binary-overwrite-mode (arg)
3973 "Toggle binary overwrite mode.
3974 With arg, turn binary overwrite mode on iff arg is positive.
3975 In binary overwrite mode, printing characters typed in replace
3976 existing text. Newlines are not treated specially, so typing at the
3977 end of a line joins the line to the next, with the typed character
3978 between them. Typing before a tab character simply replaces the tab
3979 with the character typed.
3980 \\[quoted-insert] replaces the text at the cursor, just as ordinary
3981 typing characters do.
3983 Note that binary overwrite mode is not its own minor mode; it is a
3984 specialization of overwrite-mode, entered by setting the
3985 `overwrite-mode' variable to `overwrite-mode-binary'."
3987 (setq overwrite-mode
3989 (not (eq overwrite-mode 'overwrite-mode-binary))
3990 (> (prefix-numeric-value arg) 0))
3991 'overwrite-mode-binary))
3992 (force-mode-line-update))
3994 (define-minor-mode line-number-mode
3995 "Toggle Line Number mode.
3996 With arg, turn Line Number mode on iff arg is positive.
3997 When Line Number mode is enabled, the line number appears
4000 Line numbers do not appear for very large buffers and buffers
4001 with very long lines; see variables `line-number-display-limit'
4002 and `line-number-display-limit-width'."
4003 :init-value t :global t :group 'editing-basics :require nil)
4005 (define-minor-mode column-number-mode
4006 "Toggle Column Number mode.
4007 With arg, turn Column Number mode on iff arg is positive.
4008 When Column Number mode is enabled, the column number appears
4010 :global t :group 'editing-basics :require nil)
4012 (define-minor-mode size-indication-mode
4013 "Toggle Size Indication mode.
4014 With arg, turn Size Indication mode on iff arg is positive. When
4015 Size Indication mode is enabled, the size of the accessible part
4016 of the buffer appears in the mode line."
4017 :global t :group 'editing-basics :require nil)
4019 (defgroup paren-blinking nil
4020 "Blinking matching of parens and expressions."
4021 :prefix "blink-matching-"
4022 :group 'paren-matching)
4024 (defcustom blink-matching-paren t
4025 "*Non-nil means show matching open-paren when close-paren is inserted."
4027 :group 'paren-blinking)
4029 (defcustom blink-matching-paren-on-screen t
4030 "*Non-nil means show matching open-paren when it is on screen.
4031 If nil, means don't show it (but the open-paren can still be shown
4032 when it is off screen)."
4034 :group 'paren-blinking)
4036 (defcustom blink-matching-paren-distance (* 25 1024)
4037 "*If non-nil, is maximum distance to search for matching open-paren."
4039 :group 'paren-blinking)
4041 (defcustom blink-matching-delay 1
4042 "*Time in seconds to delay after showing a matching paren."
4044 :group 'paren-blinking)
4046 (defcustom blink-matching-paren-dont-ignore-comments nil
4047 "*Non-nil means `blink-matching-paren' will not ignore comments."
4049 :group 'paren-blinking)
4051 (defun blink-matching-open ()
4052 "Move cursor momentarily to the beginning of the sexp before point."
4054 (and (> (point) (1+ (point-min)))
4055 blink-matching-paren
4056 ;; Verify an even number of quoting characters precede the close.
4057 (= 1 (logand 1 (- (point)
4060 (skip-syntax-backward "/\\")
4062 (let* ((oldpos (point))
4068 (if blink-matching-paren-distance
4069 (narrow-to-region (max (point-min)
4070 (- (point) blink-matching-paren-distance))
4073 (let ((parse-sexp-ignore-comments
4074 (and parse-sexp-ignore-comments
4075 (not blink-matching-paren-dont-ignore-comments))))
4076 (setq blinkpos (scan-sexps oldpos -1)))
4079 (not (eq (car (syntax-after blinkpos)) 8)) ;Not syntax '$'.
4080 (setq matching-paren
4081 (let ((syntax (syntax-after blinkpos)))
4083 (eq (logand (car syntax) 255) 4)
4086 (or (null matching-paren)
4087 (/= (char-after (1- oldpos))
4089 (if mismatch (setq blinkpos nil))
4091 ;; Don't log messages about paren matching.
4092 (let (message-log-max)
4093 (goto-char blinkpos)
4094 (if (pos-visible-in-window-p)
4095 (and blink-matching-paren-on-screen
4096 (sit-for blink-matching-delay))
4097 (goto-char blinkpos)
4100 ;; Show what precedes the open in its line, if anything.
4102 (skip-chars-backward " \t")
4104 (buffer-substring (progn (beginning-of-line) (point))
4106 ;; Show what follows the open in its line, if anything.
4109 (skip-chars-forward " \t")
4111 (buffer-substring blinkpos
4112 (progn (end-of-line) (point)))
4113 ;; Otherwise show the previous nonblank line,
4116 (skip-chars-backward "\n \t")
4119 (buffer-substring (progn
4120 (skip-chars-backward "\n \t")
4123 (progn (end-of-line)
4124 (skip-chars-backward " \t")
4126 ;; Replace the newline and other whitespace with `...'.
4128 (buffer-substring blinkpos (1+ blinkpos)))
4129 ;; There is nothing to show except the char itself.
4130 (buffer-substring blinkpos (1+ blinkpos))))))))
4132 (message "Mismatched parentheses"))
4133 ((not blink-matching-paren-distance)
4134 (message "Unmatched parenthesis"))))))))
4136 ;Turned off because it makes dbx bomb out.
4137 (setq blink-paren-function 'blink-matching-open)
4139 ;; This executes C-g typed while Emacs is waiting for a command.
4140 ;; Quitting out of a program does not go through here;
4141 ;; that happens in the QUIT macro at the C code level.
4142 (defun keyboard-quit ()
4143 "Signal a `quit' condition.
4144 During execution of Lisp code, this character causes a quit directly.
4145 At top-level, as an editor command, this simply beeps."
4148 (if (fboundp 'kmacro-keyboard-quit)
4149 (kmacro-keyboard-quit))
4150 (setq defining-kbd-macro nil)
4153 (define-key global-map "\C-g" 'keyboard-quit)
4155 (defvar buffer-quit-function nil
4156 "Function to call to \"quit\" the current buffer, or nil if none.
4157 \\[keyboard-escape-quit] calls this function when its more local actions
4158 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4160 (defun keyboard-escape-quit ()
4161 "Exit the current \"mode\" (in a generalized sense of the word).
4162 This command can exit an interactive command such as `query-replace',
4163 can clear out a prefix argument or a region,
4164 can get out of the minibuffer or other recursive edit,
4165 cancel the use of the current buffer (for special-purpose buffers),
4166 or go back to just one window (by deleting all but the selected window)."
4168 (cond ((eq last-command 'mode-exited) nil)
4169 ((> (minibuffer-depth) 0)
4170 (abort-recursive-edit))
4173 ((and transient-mark-mode mark-active)
4175 ((> (recursion-depth) 0)
4176 (exit-recursive-edit))
4177 (buffer-quit-function
4178 (funcall buffer-quit-function))
4179 ((not (one-window-p t))
4180 (delete-other-windows))
4181 ((string-match "^ \\*" (buffer-name (current-buffer)))
4184 (defun play-sound-file (file &optional volume device)
4185 "Play sound stored in FILE.
4186 VOLUME and DEVICE correspond to the keywords of the sound
4187 specification for `play-sound'."
4188 (interactive "fPlay sound file: ")
4189 (let ((sound (list :file file)))
4191 (plist-put sound :volume volume))
4193 (plist-put sound :device device))
4195 (play-sound sound)))
4197 (define-key global-map "\e\e\e" 'keyboard-escape-quit)
4199 (defcustom read-mail-command 'rmail
4200 "*Your preference for a mail reading package.
4201 This is used by some keybindings which support reading mail.
4202 See also `mail-user-agent' concerning sending mail."
4203 :type '(choice (function-item rmail)
4204 (function-item gnus)
4205 (function-item mh-rmail)
4206 (function :tag "Other"))
4210 (defcustom mail-user-agent 'sendmail-user-agent
4211 "*Your preference for a mail composition package.
4212 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
4213 outgoing email message. This variable lets you specify which
4214 mail-sending package you prefer.
4216 Valid values include:
4218 `sendmail-user-agent' -- use the default Emacs Mail package.
4219 See Info node `(emacs)Sending Mail'.
4220 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
4221 See Info node `(mh-e)'.
4222 `message-user-agent' -- use the Gnus Message package.
4223 See Info node `(message)'.
4224 `gnus-user-agent' -- like `message-user-agent', but with Gnus
4225 paraphernalia, particularly the Gcc: header for
4228 Additional valid symbols may be available; check with the author of
4229 your package for details. The function should return non-nil if it
4232 See also `read-mail-command' concerning reading mail."
4233 :type '(radio (function-item :tag "Default Emacs mail"
4235 sendmail-user-agent)
4236 (function-item :tag "Emacs interface to MH"
4239 (function-item :tag "Gnus Message package"
4242 (function-item :tag "Gnus Message with full Gnus features"
4245 (function :tag "Other"))
4248 (define-mail-user-agent 'sendmail-user-agent
4249 'sendmail-user-agent-compose
4250 'mail-send-and-exit)
4252 (defun rfc822-goto-eoh ()
4253 ;; Go to header delimiter line in a mail message, following RFC822 rules
4254 (goto-char (point-min))
4255 (when (re-search-forward
4256 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
4257 (goto-char (match-beginning 0))))
4259 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
4260 switch-function yank-action
4263 (let ((special-display-buffer-names nil)
4264 (special-display-regexps nil)
4265 (same-window-buffer-names nil)
4266 (same-window-regexps nil))
4267 (funcall switch-function "*mail*")))
4268 (let ((cc (cdr (assoc-string "cc" other-headers t)))
4269 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
4270 (body (cdr (assoc-string "body" other-headers t))))
4271 (or (mail continue to subject in-reply-to cc yank-action send-actions)
4273 (error "Message aborted"))
4276 (while other-headers
4277 (unless (member-ignore-case (car (car other-headers))
4278 '("in-reply-to" "cc" "body"))
4279 (insert (car (car other-headers)) ": "
4280 (cdr (car other-headers)) "\n"))
4281 (setq other-headers (cdr other-headers)))
4287 (define-mail-user-agent 'mh-e-user-agent
4288 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
4289 'mh-before-send-letter-hook)
4291 (defun compose-mail (&optional to subject other-headers continue
4292 switch-function yank-action send-actions)
4293 "Start composing a mail message to send.
4294 This uses the user's chosen mail composition package
4295 as selected with the variable `mail-user-agent'.
4296 The optional arguments TO and SUBJECT specify recipients
4297 and the initial Subject field, respectively.
4299 OTHER-HEADERS is an alist specifying additional
4300 header fields. Elements look like (HEADER . VALUE) where both
4301 HEADER and VALUE are strings.
4303 CONTINUE, if non-nil, says to continue editing a message already
4306 SWITCH-FUNCTION, if non-nil, is a function to use to
4307 switch to and display the buffer used for mail composition.
4309 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
4310 to insert the raw text of the message being replied to.
4311 It has the form (FUNCTION . ARGS). The user agent will apply
4312 FUNCTION to ARGS, to insert the raw text of the original message.
4313 \(The user agent will also run `mail-citation-hook', *after* the
4314 original text has been inserted in this way.)
4316 SEND-ACTIONS is a list of actions to call when the message is sent.
4317 Each action has the form (FUNCTION . ARGS)."
4319 (list nil nil nil current-prefix-arg))
4320 (let ((function (get mail-user-agent 'composefunc)))
4321 (funcall function to subject other-headers continue
4322 switch-function yank-action send-actions)))
4324 (defun compose-mail-other-window (&optional to subject other-headers continue
4325 yank-action send-actions)
4326 "Like \\[compose-mail], but edit the outgoing message in another window."
4328 (list nil nil nil current-prefix-arg))
4329 (compose-mail to subject other-headers continue
4330 'switch-to-buffer-other-window yank-action send-actions))
4333 (defun compose-mail-other-frame (&optional to subject other-headers continue
4334 yank-action send-actions)
4335 "Like \\[compose-mail], but edit the outgoing message in another frame."
4337 (list nil nil nil current-prefix-arg))
4338 (compose-mail to subject other-headers continue
4339 'switch-to-buffer-other-frame yank-action send-actions))
4341 (defvar set-variable-value-history nil
4342 "History of values entered with `set-variable'.")
4344 (defun set-variable (var val &optional make-local)
4345 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4346 When using this interactively, enter a Lisp object for VALUE.
4347 If you want VALUE to be a string, you must surround it with doublequotes.
4348 VALUE is used literally, not evaluated.
4350 If VARIABLE has a `variable-interactive' property, that is used as if
4351 it were the arg to `interactive' (which see) to interactively read VALUE.
4353 If VARIABLE has been defined with `defcustom', then the type information
4354 in the definition is used to check that VALUE is valid.
4356 With a prefix argument, set VARIABLE to VALUE buffer-locally."
4358 (let* ((default-var (variable-at-point))
4359 (var (if (symbolp default-var)
4360 (read-variable (format "Set variable (default %s): " default-var)
4362 (read-variable "Set variable: ")))
4363 (minibuffer-help-form '(describe-variable var))
4364 (prop (get var 'variable-interactive))
4365 (prompt (format "Set %s%s to value: " var
4366 (cond ((local-variable-p var)
4368 ((or current-prefix-arg
4369 (local-variable-if-set-p var))
4373 ;; Use VAR's `variable-interactive' property
4374 ;; as an interactive spec for prompting.
4375 (call-interactively `(lambda (arg)
4379 (read-string prompt nil
4380 'set-variable-value-history)))))
4381 (list var val current-prefix-arg)))
4383 (and (custom-variable-p var)
4384 (not (get var 'custom-type))
4385 (custom-load-symbol var))
4386 (let ((type (get var 'custom-type)))
4388 ;; Match with custom type.
4390 (setq type (widget-convert type))
4391 (unless (widget-apply type :match val)
4392 (error "Value `%S' does not match type %S of %S"
4393 val (car type) var))))
4396 (make-local-variable var))
4400 ;; Force a thorough redisplay for the case that the variable
4401 ;; has an effect on the display, like `tab-width' has.
4402 (force-mode-line-update))
4404 ;; Define the major mode for lists of completions.
4406 (defvar completion-list-mode-map nil
4407 "Local map for completion list buffers.")
4408 (or completion-list-mode-map
4409 (let ((map (make-sparse-keymap)))
4410 (define-key map [mouse-2] 'mouse-choose-completion)
4411 (define-key map [follow-link] 'mouse-face)
4412 (define-key map [down-mouse-2] nil)
4413 (define-key map "\C-m" 'choose-completion)
4414 (define-key map "\e\e\e" 'delete-completion-window)
4415 (define-key map [left] 'previous-completion)
4416 (define-key map [right] 'next-completion)
4417 (setq completion-list-mode-map map)))
4419 ;; Completion mode is suitable only for specially formatted data.
4420 (put 'completion-list-mode 'mode-class 'special)
4422 (defvar completion-reference-buffer nil
4423 "Record the buffer that was current when the completion list was requested.
4424 This is a local variable in the completion list buffer.
4425 Initial value is nil to avoid some compiler warnings.")
4427 (defvar completion-no-auto-exit nil
4428 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4429 This also applies to other functions such as `choose-completion'
4430 and `mouse-choose-completion'.")
4432 (defvar completion-base-size nil
4433 "Number of chars at beginning of minibuffer not involved in completion.
4434 This is a local variable in the completion list buffer
4435 but it talks about the buffer in `completion-reference-buffer'.
4436 If this is nil, it means to compare text to determine which part
4437 of the tail end of the buffer's text is involved in completion.")
4439 (defun delete-completion-window ()
4440 "Delete the completion list window.
4441 Go to the window from which completion was requested."
4443 (let ((buf completion-reference-buffer))
4444 (if (one-window-p t)
4445 (if (window-dedicated-p (selected-window))
4446 (delete-frame (selected-frame)))
4447 (delete-window (selected-window))
4448 (if (get-buffer-window buf)
4449 (select-window (get-buffer-window buf))))))
4451 (defun previous-completion (n)
4452 "Move to the previous item in the completion list."
4454 (next-completion (- n)))
4456 (defun next-completion (n)
4457 "Move to the next item in the completion list.
4458 With prefix argument N, move N items (negative N means move backward)."
4460 (let ((beg (point-min)) (end (point-max)))
4461 (while (and (> n 0) (not (eobp)))
4462 ;; If in a completion, move to the end of it.
4463 (when (get-text-property (point) 'mouse-face)
4464 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4465 ;; Move to start of next one.
4466 (unless (get-text-property (point) 'mouse-face)
4467 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4469 (while (and (< n 0) (not (bobp)))
4470 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4471 ;; If in a completion, move to the start of it.
4472 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
4473 (goto-char (previous-single-property-change
4474 (point) 'mouse-face nil beg)))
4475 ;; Move to end of the previous completion.
4476 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4477 (goto-char (previous-single-property-change
4478 (point) 'mouse-face nil beg)))
4479 ;; Move to the start of that one.
4480 (goto-char (previous-single-property-change
4481 (point) 'mouse-face nil beg))
4484 (defun choose-completion ()
4485 "Choose the completion that point is in or next to."
4487 (let (beg end completion (buffer completion-reference-buffer)
4488 (base-size completion-base-size))
4489 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4490 (setq end (point) beg (1+ (point))))
4491 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
4492 (setq end (1- (point)) beg (point)))
4494 (error "No completion here"))
4495 (setq beg (previous-single-property-change beg 'mouse-face))
4496 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
4497 (setq completion (buffer-substring beg end))
4498 (let ((owindow (selected-window)))
4499 (if (and (one-window-p t 'selected-frame)
4500 (window-dedicated-p (selected-window)))
4501 ;; This is a special buffer's frame
4502 (iconify-frame (selected-frame))
4503 (or (window-dedicated-p (selected-window))
4505 (select-window owindow))
4506 (choose-completion-string completion buffer base-size)))
4508 ;; Delete the longest partial match for STRING
4509 ;; that can be found before POINT.
4510 (defun choose-completion-delete-max-match (string)
4511 (let ((opoint (point))
4513 ;; Try moving back by the length of the string.
4514 (goto-char (max (- (point) (length string))
4515 (minibuffer-prompt-end)))
4516 ;; See how far back we were actually able to move. That is the
4517 ;; upper bound on how much we can match and delete.
4518 (setq len (- opoint (point)))
4519 (if completion-ignore-case
4520 (setq string (downcase string)))
4521 (while (and (> len 0)
4522 (let ((tail (buffer-substring (point) opoint)))
4523 (if completion-ignore-case
4524 (setq tail (downcase tail)))
4525 (not (string= tail (substring string 0 len)))))
4530 (defvar choose-completion-string-functions nil
4531 "Functions that may override the normal insertion of a completion choice.
4532 These functions are called in order with four arguments:
4533 CHOICE - the string to insert in the buffer,
4534 BUFFER - the buffer in which the choice should be inserted,
4535 MINI-P - non-nil iff BUFFER is a minibuffer, and
4536 BASE-SIZE - the number of characters in BUFFER before
4537 the string being completed.
4539 If a function in the list returns non-nil, that function is supposed
4540 to have inserted the CHOICE in the BUFFER, and possibly exited
4541 the minibuffer; no further functions will be called.
4543 If all functions in the list return nil, that means to use
4544 the default method of inserting the completion in BUFFER.")
4546 (defun choose-completion-string (choice &optional buffer base-size)
4547 "Switch to BUFFER and insert the completion choice CHOICE.
4548 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
4549 to keep. If it is nil, we call `choose-completion-delete-max-match'
4550 to decide what to delete."
4552 ;; If BUFFER is the minibuffer, exit the minibuffer
4553 ;; unless it is reading a file name and CHOICE is a directory,
4554 ;; or completion-no-auto-exit is non-nil.
4556 (let* ((buffer (or buffer completion-reference-buffer))
4557 (mini-p (minibufferp buffer)))
4558 ;; If BUFFER is a minibuffer, barf unless it's the currently
4559 ;; active minibuffer.
4561 (or (not (active-minibuffer-window))
4563 (window-buffer (active-minibuffer-window))))))
4564 (error "Minibuffer is not active for completion")
4565 ;; Set buffer so buffer-local choose-completion-string-functions works.
4567 (unless (run-hook-with-args-until-success
4568 'choose-completion-string-functions
4569 choice buffer mini-p base-size)
4570 ;; Insert the completion into the buffer where it was requested.
4572 (delete-region (+ base-size (if mini-p
4573 (minibuffer-prompt-end)
4576 (choose-completion-delete-max-match choice))
4578 (remove-text-properties (- (point) (length choice)) (point)
4580 ;; Update point in the window that BUFFER is showing in.
4581 (let ((window (get-buffer-window buffer t)))
4582 (set-window-point window (point)))
4583 ;; If completing for the minibuffer, exit it with this choice.
4584 (and (not completion-no-auto-exit)
4585 (equal buffer (window-buffer (minibuffer-window)))
4586 minibuffer-completion-table
4587 ;; If this is reading a file name, and the file name chosen
4588 ;; is a directory, don't exit the minibuffer.
4589 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4590 (file-directory-p (field-string (point-max))))
4591 (let ((mini (active-minibuffer-window)))
4592 (select-window mini)
4593 (when minibuffer-auto-raise
4594 (raise-frame (window-frame mini))))
4595 (exit-minibuffer)))))))
4597 (defun completion-list-mode ()
4598 "Major mode for buffers showing lists of possible completions.
4599 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4600 to select the completion near point.
4601 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4604 (kill-all-local-variables)
4605 (use-local-map completion-list-mode-map)
4606 (setq mode-name "Completion List")
4607 (setq major-mode 'completion-list-mode)
4608 (make-local-variable 'completion-base-size)
4609 (setq completion-base-size nil)
4610 (run-hooks 'completion-list-mode-hook))
4612 (defun completion-list-mode-finish ()
4613 "Finish setup of the completions buffer.
4614 Called from `temp-buffer-show-hook'."
4615 (when (eq major-mode 'completion-list-mode)
4616 (toggle-read-only 1)))
4618 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4620 (defvar completion-setup-hook nil
4621 "Normal hook run at the end of setting up a completion list buffer.
4622 When this hook is run, the current buffer is the one in which the
4623 command to display the completion list buffer was run.
4624 The completion list buffer is available as the value of `standard-output'.")
4626 ;; This function goes in completion-setup-hook, so that it is called
4627 ;; after the text of the completion list buffer is written.
4628 (defface completions-first-difference
4629 '((t (:inherit bold)))
4630 "Face put on the first uncommon character in completions in *Completions* buffer."
4633 (defface completions-common-part
4634 '((t (:inherit default)))
4635 "Face put on the common prefix substring in completions in *Completions* buffer.
4636 The idea of `completions-common-part' is that you can use it to
4637 make the common parts less visible than normal, so that the rest
4638 of the differing parts is, by contrast, slightly highlighted."
4641 ;; This is for packages that need to bind it to a non-default regexp
4642 ;; in order to make the first-differing character highlight work
4644 (defvar completion-root-regexp "^/"
4645 "Regexp to use in `completion-setup-function' to find the root directory.")
4647 (defun completion-setup-function ()
4648 (let ((mainbuf (current-buffer))
4649 (mbuf-contents (minibuffer-contents)))
4650 ;; When reading a file name in the minibuffer,
4651 ;; set default-directory in the minibuffer
4652 ;; so it will get copied into the completion list buffer.
4653 (if minibuffer-completing-file-name
4654 (with-current-buffer mainbuf
4655 (setq default-directory (file-name-directory mbuf-contents))))
4656 ;; If partial-completion-mode is on, point might not be after the
4657 ;; last character in the minibuffer.
4658 ;; FIXME: This still doesn't work if the text to be completed
4659 ;; starts with a `-'.
4660 (when (and partial-completion-mode (not (eobp)))
4662 (substring mbuf-contents 0 (- (point) (point-max)))))
4663 (with-current-buffer standard-output
4664 (completion-list-mode)
4665 (make-local-variable 'completion-reference-buffer)
4666 (setq completion-reference-buffer mainbuf)
4667 (if minibuffer-completing-file-name
4668 ;; For file name completion,
4669 ;; use the number of chars before the start of the
4670 ;; last file name component.
4671 (setq completion-base-size
4672 (with-current-buffer mainbuf
4674 (goto-char (point-max))
4675 (skip-chars-backward completion-root-regexp)
4676 (- (point) (minibuffer-prompt-end)))))
4677 ;; Otherwise, in minibuffer, the whole input is being completed.
4678 (if (minibufferp mainbuf)
4679 (setq completion-base-size 0)))
4680 ;; Put faces on first uncommon characters and common parts.
4681 (when completion-base-size
4682 (let* ((common-string-length
4683 (- (length mbuf-contents) completion-base-size))
4684 (element-start (next-single-property-change
4689 (+ (or element-start nil) common-string-length)))
4691 (while (and element-start (< element-common-end maxp))
4692 (when (and (get-char-property element-start 'mouse-face)
4693 (get-char-property element-common-end 'mouse-face))
4694 (put-text-property element-start element-common-end
4695 'font-lock-face 'completions-common-part)
4696 (put-text-property element-common-end (1+ element-common-end)
4697 'font-lock-face 'completions-first-difference))
4698 (setq element-start (next-single-property-change
4702 (setq element-common-end (+ element-start common-string-length))))))
4703 ;; Insert help string.
4704 (goto-char (point-min))
4705 (if (display-mouse-p)
4706 (insert (substitute-command-keys
4707 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4708 (insert (substitute-command-keys
4709 "In this buffer, type \\[choose-completion] to \
4710 select the completion near point.\n\n")))))
4712 (add-hook 'completion-setup-hook 'completion-setup-function)
4714 (define-key minibuffer-local-completion-map [prior]
4715 'switch-to-completions)
4716 (define-key minibuffer-local-must-match-map [prior]
4717 'switch-to-completions)
4718 (define-key minibuffer-local-completion-map "\M-v"
4719 'switch-to-completions)
4720 (define-key minibuffer-local-must-match-map "\M-v"
4721 'switch-to-completions)
4723 (defun switch-to-completions ()
4724 "Select the completion list window."
4726 ;; Make sure we have a completions window.
4727 (or (get-buffer-window "*Completions*")
4728 (minibuffer-completion-help))
4729 (let ((window (get-buffer-window "*Completions*")))
4731 (select-window window)
4732 (goto-char (point-min))
4733 (search-forward "\n\n")
4736 ;; Support keyboard commands to turn on various modifiers.
4738 ;; These functions -- which are not commands -- each add one modifier
4739 ;; to the following event.
4741 (defun event-apply-alt-modifier (ignore-prompt)
4742 "\\<function-key-map>Add the Alt modifier to the following event.
4743 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
4744 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4745 (defun event-apply-super-modifier (ignore-prompt)
4746 "\\<function-key-map>Add the Super modifier to the following event.
4747 For example, type \\[event-apply-super-modifier] & to enter Super-&."
4748 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4749 (defun event-apply-hyper-modifier (ignore-prompt)
4750 "\\<function-key-map>Add the Hyper modifier to the following event.
4751 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
4752 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4753 (defun event-apply-shift-modifier (ignore-prompt)
4754 "\\<function-key-map>Add the Shift modifier to the following event.
4755 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
4756 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4757 (defun event-apply-control-modifier (ignore-prompt)
4758 "\\<function-key-map>Add the Ctrl modifier to the following event.
4759 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
4760 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4761 (defun event-apply-meta-modifier (ignore-prompt)
4762 "\\<function-key-map>Add the Meta modifier to the following event.
4763 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
4764 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4766 (defun event-apply-modifier (event symbol lshiftby prefix)
4767 "Apply a modifier flag to event EVENT.
4768 SYMBOL is the name of this modifier, as a symbol.
4769 LSHIFTBY is the numeric value of this modifier, in keyboard events.
4770 PREFIX is the string that represents this modifier in an event type symbol."
4772 (cond ((eq symbol 'control)
4773 (if (and (<= (downcase event) ?z)
4774 (>= (downcase event) ?a))
4775 (- (downcase event) ?a -1)
4776 (if (and (<= (downcase event) ?Z)
4777 (>= (downcase event) ?A))
4778 (- (downcase event) ?A -1)
4779 (logior (lsh 1 lshiftby) event))))
4781 (if (and (<= (downcase event) ?z)
4782 (>= (downcase event) ?a))
4784 (logior (lsh 1 lshiftby) event)))
4786 (logior (lsh 1 lshiftby) event)))
4787 (if (memq symbol (event-modifiers event))
4789 (let ((event-type (if (symbolp event) event (car event))))
4790 (setq event-type (intern (concat prefix (symbol-name event-type))))
4793 (cons event-type (cdr event)))))))
4795 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4796 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4797 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4798 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4799 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4800 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
4802 ;;;; Keypad support.
4804 ;;; Make the keypad keys act like ordinary typing keys. If people add
4805 ;;; bindings for the function key symbols, then those bindings will
4806 ;;; override these, so this shouldn't interfere with any existing
4809 ;; Also tell read-char how to handle these keys.
4811 (lambda (keypad-normal)
4812 (let ((keypad (nth 0 keypad-normal))
4813 (normal (nth 1 keypad-normal)))
4814 (put keypad 'ascii-character normal)
4815 (define-key function-key-map (vector keypad) (vector normal))))
4816 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
4817 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
4830 ;;;; forking a twin copy of a buffer.
4833 (defvar clone-buffer-hook nil
4834 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
4836 (defun clone-process (process &optional newname)
4837 "Create a twin copy of PROCESS.
4838 If NEWNAME is nil, it defaults to PROCESS' name;
4839 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4840 If PROCESS is associated with a buffer, the new process will be associated
4841 with the current buffer instead.
4842 Returns nil if PROCESS has already terminated."
4843 (setq newname (or newname (process-name process)))
4844 (if (string-match "<[0-9]+>\\'" newname)
4845 (setq newname (substring newname 0 (match-beginning 0))))
4846 (when (memq (process-status process) '(run stop open))
4847 (let* ((process-connection-type (process-tty-name process))
4849 (if (memq (process-status process) '(open))
4850 (let ((args (process-contact process t)))
4851 (setq args (plist-put args :name newname))
4852 (setq args (plist-put args :buffer
4853 (if (process-buffer process)
4855 (apply 'make-network-process args))
4856 (apply 'start-process newname
4857 (if (process-buffer process) (current-buffer))
4858 (process-command process)))))
4859 (set-process-query-on-exit-flag
4860 new-process (process-query-on-exit-flag process))
4861 (set-process-inherit-coding-system-flag
4862 new-process (process-inherit-coding-system-flag process))
4863 (set-process-filter new-process (process-filter process))
4864 (set-process-sentinel new-process (process-sentinel process))
4865 (set-process-plist new-process (copy-sequence (process-plist process)))
4868 ;; things to maybe add (currently partly covered by `funcall mode'):
4871 (defun clone-buffer (&optional newname display-flag)
4872 "Create and return a twin copy of the current buffer.
4873 Unlike an indirect buffer, the new buffer can be edited
4874 independently of the old one (if it is not read-only).
4875 NEWNAME is the name of the new buffer. It may be modified by
4876 adding or incrementing <N> at the end as necessary to create a
4877 unique buffer name. If nil, it defaults to the name of the
4878 current buffer, with the proper suffix. If DISPLAY-FLAG is
4879 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
4880 clone a file-visiting buffer, or a buffer whose major mode symbol
4881 has a non-nil `no-clone' property, results in an error.
4883 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
4884 current buffer with appropriate suffix. However, if a prefix
4885 argument is given, then the command prompts for NEWNAME in the
4888 This runs the normal hook `clone-buffer-hook' in the new buffer
4889 after it has been set up properly in other respects."
4892 (if buffer-file-name
4893 (error "Cannot clone a file-visiting buffer"))
4894 (if (get major-mode 'no-clone)
4895 (error "Cannot clone a buffer in %s mode" mode-name))
4896 (list (if current-prefix-arg (read-string "Name: "))
4898 (if buffer-file-name
4899 (error "Cannot clone a file-visiting buffer"))
4900 (if (get major-mode 'no-clone)
4901 (error "Cannot clone a buffer in %s mode" mode-name))
4902 (setq newname (or newname (buffer-name)))
4903 (if (string-match "<[0-9]+>\\'" newname)
4904 (setq newname (substring newname 0 (match-beginning 0))))
4905 (let ((buf (current-buffer))
4909 (mk (if mark-active (mark t)))
4910 (modified (buffer-modified-p))
4912 (lvars (buffer-local-variables))
4913 (process (get-buffer-process (current-buffer)))
4914 (new (generate-new-buffer (or newname (buffer-name)))))
4917 (with-current-buffer new
4918 (insert-buffer-substring buf)))
4919 (with-current-buffer new
4920 (narrow-to-region ptmin ptmax)
4922 (if mk (set-mark mk))
4923 (set-buffer-modified-p modified)
4925 ;; Clone the old buffer's process, if any.
4926 (when process (clone-process process))
4928 ;; Now set up the major mode.
4931 ;; Set up other local variables.
4933 (condition-case () ;in case var is read-only
4936 (set (make-local-variable (car v)) (cdr v)))
4940 ;; Run any hooks (typically set up by the major mode
4941 ;; for cloning to work properly).
4942 (run-hooks 'clone-buffer-hook))
4943 (if display-flag (pop-to-buffer new))
4947 (defun clone-indirect-buffer (newname display-flag &optional norecord)
4948 "Create an indirect buffer that is a twin copy of the current buffer.
4950 Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
4951 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
4952 or if not called with a prefix arg, NEWNAME defaults to the current
4953 buffer's name. The name is modified by adding a `<N>' suffix to it
4954 or by incrementing the N in an existing suffix.
4956 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
4957 This is always done when called interactively.
4959 Optional last arg NORECORD non-nil means do not put this buffer at the
4960 front of the list of recently selected ones."
4963 (if (get major-mode 'no-clone-indirect)
4964 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4965 (list (if current-prefix-arg
4966 (read-string "BName of indirect buffer: "))
4968 (if (get major-mode 'no-clone-indirect)
4969 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4970 (setq newname (or newname (buffer-name)))
4971 (if (string-match "<[0-9]+>\\'" newname)
4972 (setq newname (substring newname 0 (match-beginning 0))))
4973 (let* ((name (generate-new-buffer-name newname))
4974 (buffer (make-indirect-buffer (current-buffer) name t)))
4976 (pop-to-buffer buffer norecord))
4980 (defun clone-indirect-buffer-other-window (buffer &optional norecord)
4981 "Create an indirect buffer that is a twin copy of BUFFER.
4982 Select the new buffer in another window.
4983 Optional second arg NORECORD non-nil means do not put this buffer at
4984 the front of the list of recently selected ones."
4985 (interactive "bClone buffer in other window: ")
4986 (let ((pop-up-windows t))
4988 (clone-indirect-buffer nil t norecord)))
4990 (define-key ctl-x-4-map "c" 'clone-indirect-buffer-other-window)
4992 ;;; Handling of Backspace and Delete keys.
4994 (defcustom normal-erase-is-backspace nil
4995 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
4997 On window systems, the default value of this option is chosen
4998 according to the keyboard used. If the keyboard has both a Backspace
4999 key and a Delete key, and both are mapped to their usual meanings, the
5000 option's default value is set to t, so that Backspace can be used to
5001 delete backward, and Delete can be used to delete forward.
5003 If not running under a window system, customizing this option accomplishes
5004 a similar effect by mapping C-h, which is usually generated by the
5005 Backspace key, to DEL, and by mapping DEL to C-d via
5006 `keyboard-translate'. The former functionality of C-h is available on
5007 the F1 key. You should probably not use this setting if you don't
5008 have both Backspace, Delete and F1 keys.
5010 Setting this variable with setq doesn't take effect. Programmatically,
5011 call `normal-erase-is-backspace-mode' (which see) instead."
5013 :group 'editing-basics
5015 :set (lambda (symbol value)
5016 ;; The fboundp is because of a problem with :set when
5017 ;; dumping Emacs. It doesn't really matter.
5018 (if (fboundp 'normal-erase-is-backspace-mode)
5019 (normal-erase-is-backspace-mode (or value 0))
5020 (set-default symbol value))))
5023 (defun normal-erase-is-backspace-mode (&optional arg)
5024 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5026 With numeric arg, turn the mode on if and only if ARG is positive.
5028 On window systems, when this mode is on, Delete is mapped to C-d and
5029 Backspace is mapped to DEL; when this mode is off, both Delete and
5030 Backspace are mapped to DEL. (The remapping goes via
5031 `function-key-map', so binding Delete or Backspace in the global or
5032 local keymap will override that.)
5034 In addition, on window systems, the bindings of C-Delete, M-Delete,
5035 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5036 the global keymap in accordance with the functionality of Delete and
5037 Backspace. For example, if Delete is remapped to C-d, which deletes
5038 forward, C-Delete is bound to `kill-word', but if Delete is remapped
5039 to DEL, which deletes backward, C-Delete is bound to
5040 `backward-kill-word'.
5042 If not running on a window system, a similar effect is accomplished by
5043 remapping C-h (normally produced by the Backspace key) and DEL via
5044 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5045 to C-d; if it's off, the keys are not remapped.
5047 When not running on a window system, and this mode is turned on, the
5048 former functionality of C-h is available on the F1 key. You should
5049 probably not turn on this mode on a text-only terminal if you don't
5050 have both Backspace, Delete and F1 keys.
5052 See also `normal-erase-is-backspace'."
5054 (setq normal-erase-is-backspace
5056 (> (prefix-numeric-value arg) 0)
5057 (not normal-erase-is-backspace)))
5059 (cond ((or (memq window-system '(x w32 mac pc))
5060 (memq system-type '(ms-dos windows-nt)))
5062 `(([C-delete] [C-backspace])
5063 ([M-delete] [M-backspace])
5064 ([C-M-delete] [C-M-backspace])
5066 [C-delete] [C-backspace])))
5067 (old-state (lookup-key function-key-map [delete])))
5069 (if normal-erase-is-backspace
5071 (define-key function-key-map [delete] [?\C-d])
5072 (define-key function-key-map [kp-delete] [?\C-d])
5073 (define-key function-key-map [backspace] [?\C-?]))
5074 (define-key function-key-map [delete] [?\C-?])
5075 (define-key function-key-map [kp-delete] [?\C-?])
5076 (define-key function-key-map [backspace] [?\C-?]))
5078 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5079 (unless (equal old-state (lookup-key function-key-map [delete]))
5080 (dolist (binding bindings)
5081 (let ((map global-map))
5082 (when (keymapp (car binding))
5083 (setq map (car binding) binding (cdr binding)))
5084 (let* ((key1 (nth 0 binding))
5085 (key2 (nth 1 binding))
5086 (binding1 (lookup-key map key1))
5087 (binding2 (lookup-key map key2)))
5088 (define-key map key1 binding2)
5089 (define-key map key2 binding1)))))))
5091 (if normal-erase-is-backspace
5093 (keyboard-translate ?\C-h ?\C-?)
5094 (keyboard-translate ?\C-? ?\C-d))
5095 (keyboard-translate ?\C-h ?\C-h)
5096 (keyboard-translate ?\C-? ?\C-?))))
5098 (run-hooks 'normal-erase-is-backspace-hook)
5100 (message "Delete key deletes %s"
5101 (if normal-erase-is-backspace "forward" "backward"))))
5103 (defcustom idle-update-delay 0.5
5104 "*Idle time delay before updating various things on the screen.
5105 Various Emacs features that update auxiliary information when point moves
5106 wait this many seconds after Emacs becomes idle before doing an update."
5111 (defvar vis-mode-saved-buffer-invisibility-spec nil
5112 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
5114 (define-minor-mode visible-mode
5115 "Toggle Visible mode.
5116 With argument ARG turn Visible mode on iff ARG is positive.
5118 Enabling Visible mode makes all invisible text temporarily visible.
5119 Disabling Visible mode turns off that effect. Visible mode
5120 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
5122 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
5123 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
5124 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
5126 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
5127 buffer-invisibility-spec)
5128 (setq buffer-invisibility-spec nil)))
5130 ;; Minibuffer prompt stuff.
5132 ;(defun minibuffer-prompt-modification (start end)
5133 ; (error "You cannot modify the prompt"))
5136 ;(defun minibuffer-prompt-insertion (start end)
5137 ; (let ((inhibit-modification-hooks t))
5138 ; (delete-region start end)
5139 ; ;; Discard undo information for the text insertion itself
5140 ; ;; and for the text deletion.above.
5141 ; (when (consp buffer-undo-list)
5142 ; (setq buffer-undo-list (cddr buffer-undo-list)))
5143 ; (message "You cannot modify the prompt")))
5146 ;(setq minibuffer-prompt-properties
5147 ; (list 'modification-hooks '(minibuffer-prompt-modification)
5148 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
5153 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
5154 ;;; simple.el ends here