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., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
29 ;; A grab-bag of basic Emacs commands not specifically related to some
30 ;; major mode or to file-handling.
35 (autoload 'widget-convert "wid-edit")
36 (autoload 'shell-mode "shell"))
38 (defcustom idle-update-delay 0.5
39 "*Idle time delay before updating various things on the screen.
40 Various Emacs features that update auxiliary information when point moves
41 wait this many seconds after Emacs becomes idle before doing an update."
47 "Killing and yanking commands."
50 (defgroup paren-matching nil
51 "Highlight (un)matching of parens and expressions."
55 "Switch to the next buffer in cyclic order."
57 (let ((buffer (current-buffer)))
58 (switch-to-buffer (other-buffer buffer))
59 (bury-buffer buffer)))
62 "Switch to the previous buffer in cyclic order."
64 (let ((list (nreverse (buffer-list)))
66 (while (and (not found) list)
67 (let ((buffer (car list)))
68 (if (and (not (get-buffer-window buffer))
69 (not (string-match "\\` " (buffer-name buffer))))
71 (setq list (cdr list)))
72 (switch-to-buffer found)))
74 ;;; next-error support framework
76 (defgroup next-error nil
77 "next-error support framework."
82 '((t (:inherit region)))
83 "Face used to highlight next error locus."
87 (defcustom next-error-highlight 0.1
88 "*Highlighting of locations in selected source buffers.
89 If number, highlight the locus in next-error face for given time in seconds.
90 If t, use persistent overlays fontified in next-error face.
91 If nil, don't highlight the locus in the source buffer.
92 If `fringe-arrow', indicate the locus by the fringe arrow."
93 :type '(choice (number :tag "Delay")
94 (const :tag "Persistent overlay" t)
95 (const :tag "No highlighting" nil)
96 (const :tag "Fringe arrow" 'fringe-arrow))
100 (defcustom next-error-highlight-no-select 0.1
101 "*Highlighting of locations in non-selected source buffers.
102 If number, highlight the locus in next-error face for given time in seconds.
103 If t, use persistent overlays fontified in next-error face.
104 If nil, don't highlight the locus in the source buffer.
105 If `fringe-arrow', indicate the locus by the fringe arrow."
106 :type '(choice (number :tag "Delay")
107 (const :tag "Persistent overlay" t)
108 (const :tag "No highlighting" nil)
109 (const :tag "Fringe arrow" 'fringe-arrow))
113 (defvar next-error-highlight-timer nil)
115 (defvar next-error-overlay-arrow-position nil)
116 (put 'next-error-overlay-arrow-position 'overlay-arrow-string "=>")
117 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
119 (defvar next-error-last-buffer nil
120 "The most recent next-error buffer.
121 A buffer becomes most recent when its compilation, grep, or
122 similar mode is started, or when it is used with \\[next-error]
123 or \\[compile-goto-error].")
125 (defvar next-error-function nil
126 "Function to use to find the next error in the current buffer.
127 The function is called with 2 parameters:
128 ARG is an integer specifying by how many errors to move.
129 RESET is a boolean which, if non-nil, says to go back to the beginning
130 of the errors before moving.
131 Major modes providing compile-like functionality should set this variable
132 to indicate to `next-error' that this is a candidate buffer and how
135 (make-variable-buffer-local 'next-error-function)
137 (defsubst next-error-buffer-p (buffer
138 &optional avoid-current
140 extra-test-exclusive)
141 "Test if BUFFER is a next-error capable buffer.
143 If AVOID-CURRENT is non-nil, treat the current buffer
144 as an absolute last resort only.
146 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
147 that normally would not qualify. If it returns t, the buffer
148 in question is treated as usable.
150 The function EXTRA-TEST-EXCLUSIVE, if non-nil is called in each buffer
151 that would normally be considered usable. If it returns nil,
152 that buffer is rejected."
153 (and (buffer-name buffer) ;First make sure it's live.
154 (not (and avoid-current (eq buffer (current-buffer))))
155 (with-current-buffer buffer
156 (if next-error-function ; This is the normal test.
157 ;; Optionally reject some buffers.
158 (if extra-test-exclusive
159 (funcall extra-test-exclusive)
161 ;; Optionally accept some other buffers.
162 (and extra-test-inclusive
163 (funcall extra-test-inclusive))))))
165 (defun next-error-find-buffer (&optional avoid-current
167 extra-test-exclusive)
168 "Return a next-error capable buffer.
169 If AVOID-CURRENT is non-nil, treat the current buffer
170 as an absolute last resort only.
172 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
173 that normally would not qualify. If it returns t, the buffer
174 in question is treated as usable.
176 The function EXTRA-TEST-EXCLUSIVE, if non-nil is called in each buffer
177 that would normally be considered usable. If it returns nil,
178 that buffer is rejected."
180 ;; 1. If one window on the selected frame displays such buffer, return it.
181 (let ((window-buffers
183 (delq nil (mapcar (lambda (w)
184 (if (next-error-buffer-p
187 extra-test-inclusive extra-test-exclusive)
190 (if (eq (length window-buffers) 1)
191 (car window-buffers)))
192 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
193 (if (and next-error-last-buffer
194 (next-error-buffer-p next-error-last-buffer avoid-current
195 extra-test-inclusive extra-test-exclusive))
196 next-error-last-buffer)
197 ;; 3. If the current buffer is acceptable, choose it.
198 (if (next-error-buffer-p (current-buffer) avoid-current
199 extra-test-inclusive extra-test-exclusive)
201 ;; 4. Look for any acceptable buffer.
202 (let ((buffers (buffer-list)))
204 (not (next-error-buffer-p
205 (car buffers) avoid-current
206 extra-test-inclusive extra-test-exclusive)))
207 (setq buffers (cdr buffers)))
209 ;; 5. Use the current buffer as a last resort if it qualifies,
210 ;; even despite AVOID-CURRENT.
212 (next-error-buffer-p (current-buffer) nil
213 extra-test-inclusive extra-test-exclusive)
215 (message "This is the only next-error capable buffer")
218 (error "No next-error capable buffer found")))
220 (defun next-error (&optional arg reset)
221 "Visit next next-error message and corresponding source code.
223 If all the error messages parsed so far have been processed already,
224 the message buffer is checked for new ones.
226 A prefix ARG specifies how many error messages to move;
227 negative means move back to previous error messages.
228 Just \\[universal-argument] as a prefix means reparse the error message buffer
229 and start at the first error.
231 The RESET argument specifies that we should restart from the beginning.
233 \\[next-error] normally uses the most recently started
234 compilation, grep, or occur buffer. It can also operate on any
235 buffer with output from the \\[compile], \\[grep] commands, or,
236 more generally, on any buffer in Compilation mode or with
237 Compilation Minor mode enabled, or any buffer in which
238 `next-error-function' is bound to an appropriate function.
239 To specify use of a particular buffer for error messages, type
240 \\[next-error] in that buffer when it is the only one displayed
241 in the current frame.
243 Once \\[next-error] has chosen the buffer for error messages,
244 it stays with that buffer until you use it in some other buffer which
245 uses Compilation mode or Compilation Minor mode.
247 See variables `compilation-parse-errors-function' and
248 \`compilation-error-regexp-alist' for customization ideas."
250 (if (consp arg) (setq reset t arg nil))
251 (when (setq next-error-last-buffer (next-error-find-buffer))
252 ;; we know here that next-error-function is a valid symbol we can funcall
253 (with-current-buffer next-error-last-buffer
254 (funcall next-error-function (prefix-numeric-value arg) reset))))
256 (defalias 'goto-next-locus 'next-error)
257 (defalias 'next-match 'next-error)
259 (defun previous-error (&optional n)
260 "Visit previous next-error message and corresponding source code.
262 Prefix arg N says how many error messages to move backwards (or
263 forwards, if negative).
265 This operates on the output from the \\[compile] and \\[grep] commands."
267 (next-error (- (or n 1))))
269 (defun first-error (&optional n)
270 "Restart at the first error.
271 Visit corresponding source code.
272 With prefix arg N, visit the source code of the Nth error.
273 This operates on the output from the \\[compile] command, for instance."
277 (defun next-error-no-select (&optional n)
278 "Move point to the next error in the next-error buffer and highlight match.
279 Prefix arg N says how many error messages to move forwards (or
280 backwards, if negative).
281 Finds and highlights the source line like \\[next-error], but does not
282 select the source buffer."
284 (let ((next-error-highlight next-error-highlight-no-select))
286 (pop-to-buffer next-error-last-buffer))
288 (defun previous-error-no-select (&optional n)
289 "Move point to the previous error in the next-error buffer and highlight match.
290 Prefix arg N says how many error messages to move backwards (or
291 forwards, if negative).
292 Finds and highlights the source line like \\[previous-error], but does not
293 select the source buffer."
295 (next-error-no-select (- (or n 1))))
297 ;;; Internal variable for `next-error-follow-mode-post-command-hook'.
298 (defvar next-error-follow-last-line nil)
300 (define-minor-mode next-error-follow-minor-mode
301 "Minor mode for compilation, occur and diff modes.
302 When turned on, cursor motion in the compilation, grep, occur or diff
303 buffer causes automatic display of the corresponding source code
305 :group 'next-error :init-value " Fol"
306 (if (not next-error-follow-minor-mode)
307 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
308 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
309 (make-variable-buffer-local 'next-error-follow-last-line)))
311 ;;; Used as a `post-command-hook' by `next-error-follow-mode'
312 ;;; for the *Compilation* *grep* and *Occur* buffers.
313 (defun next-error-follow-mode-post-command-hook ()
314 (unless (equal next-error-follow-last-line (line-number-at-pos))
315 (setq next-error-follow-last-line (line-number-at-pos))
317 (let ((compilation-context-lines nil))
318 (setq compilation-current-error (point))
319 (next-error-no-select 0))
325 (defun fundamental-mode ()
326 "Major mode not specialized for anything in particular.
327 Other major modes are defined by comparison with this one."
329 (kill-all-local-variables)
330 (unless delay-mode-hooks
331 (run-hooks 'after-change-major-mode-hook)))
333 ;; Making and deleting lines.
335 (defun newline (&optional arg)
336 "Insert a newline, and move to left margin of the new line if it's blank.
337 If `use-hard-newlines' is non-nil, the newline is marked with the
338 text-property `hard'.
339 With ARG, insert that many newlines.
340 Call `auto-fill-function' if the current column number is greater
341 than the value of `fill-column' and ARG is nil."
343 (barf-if-buffer-read-only)
344 ;; Inserting a newline at the end of a line produces better redisplay in
345 ;; try_window_id than inserting at the beginning of a line, and the textual
346 ;; result is the same. So, if we're at beginning of line, pretend to be at
347 ;; the end of the previous line.
348 (let ((flag (and (not (bobp))
350 ;; Make sure no functions want to be told about
351 ;; the range of the changes.
352 (not after-change-functions)
353 (not before-change-functions)
354 ;; Make sure there are no markers here.
355 (not (buffer-has-markers-at (1- (point))))
356 (not (buffer-has-markers-at (point)))
357 ;; Make sure no text properties want to know
358 ;; where the change was.
359 (not (get-char-property (1- (point)) 'modification-hooks))
360 (not (get-char-property (1- (point)) 'insert-behind-hooks))
362 (not (get-char-property (point) 'insert-in-front-hooks)))
363 ;; Make sure the newline before point isn't intangible.
364 (not (get-char-property (1- (point)) 'intangible))
365 ;; Make sure the newline before point isn't read-only.
366 (not (get-char-property (1- (point)) 'read-only))
367 ;; Make sure the newline before point isn't invisible.
368 (not (get-char-property (1- (point)) 'invisible))
369 ;; Make sure the newline before point has the same
370 ;; properties as the char before it (if any).
371 (< (or (previous-property-change (point)) -2)
373 (was-page-start (and (bolp)
374 (looking-at page-delimiter)))
376 (if flag (backward-char 1))
377 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
378 ;; Set last-command-char to tell self-insert what to insert.
379 (let ((last-command-char ?\n)
380 ;; Don't auto-fill if we have a numeric argument.
381 ;; Also not if flag is true (it would fill wrong line);
382 ;; there is no need to since we're at BOL.
383 (auto-fill-function (if (or arg flag) nil auto-fill-function)))
385 (self-insert-command (prefix-numeric-value arg))
386 ;; If we get an error in self-insert-command, put point at right place.
387 (if flag (forward-char 1))))
388 ;; Even if we did *not* get an error, keep that forward-char;
389 ;; all further processing should apply to the newline that the user
390 ;; thinks he inserted.
392 ;; Mark the newline(s) `hard'.
393 (if use-hard-newlines
394 (set-hard-newline-properties
395 (- (point) (if arg (prefix-numeric-value arg) 1)) (point)))
396 ;; If the newline leaves the previous line blank,
397 ;; and we have a left margin, delete that from the blank line.
400 (goto-char beforepos)
402 (and (looking-at "[ \t]$")
403 (> (current-left-margin) 0)
404 (delete-region (point) (progn (end-of-line) (point))))))
405 ;; Indent the line after the newline, except in one case:
406 ;; when we added the newline at the beginning of a line
407 ;; which starts a page.
409 (move-to-left-margin nil t)))
412 (defun set-hard-newline-properties (from to)
413 (let ((sticky (get-text-property from 'rear-nonsticky)))
414 (put-text-property from to 'hard 't)
415 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
416 (if (and (listp sticky) (not (memq 'hard sticky)))
417 (put-text-property from (point) 'rear-nonsticky
418 (cons 'hard sticky)))))
421 "Insert a newline and leave point before it.
422 If there is a fill prefix and/or a left-margin, insert them on the new line
423 if the line would have been blank.
424 With arg N, insert N newlines."
426 (let* ((do-fill-prefix (and fill-prefix (bolp)))
427 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
429 ;; Don't expand an abbrev before point.
435 (if do-left-margin (indent-to (current-left-margin)))
436 (if do-fill-prefix (insert-and-inherit fill-prefix))))
442 (defun split-line (&optional arg)
443 "Split current line, moving portion beyond point vertically down.
444 If the current line starts with `fill-prefix', insert it on the new
445 line as well. With prefix ARG, don't insert fill-prefix on new line.
447 When called from Lisp code, ARG may be a prefix string to copy."
449 (skip-chars-forward " \t")
450 (let* ((col (current-column))
452 ;; What prefix should we check for (nil means don't).
453 (prefix (cond ((stringp arg) arg)
456 ;; Does this line start with it?
457 (have-prfx (and prefix
460 (looking-at (regexp-quote prefix))))))
462 (if have-prfx (insert-and-inherit prefix))
466 (defun delete-indentation (&optional arg)
467 "Join this line to previous and fix up whitespace at join.
468 If there is a fill prefix, delete it from the beginning of this line.
469 With argument, join this line to following line."
472 (if arg (forward-line 1))
473 (if (eq (preceding-char) ?\n)
475 (delete-region (point) (1- (point)))
476 ;; If the second line started with the fill prefix,
477 ;; delete the prefix.
479 (<= (+ (point) (length fill-prefix)) (point-max))
481 (buffer-substring (point)
482 (+ (point) (length fill-prefix)))))
483 (delete-region (point) (+ (point) (length fill-prefix))))
484 (fixup-whitespace))))
486 (defalias 'join-line #'delete-indentation) ; easier to find
488 (defun delete-blank-lines ()
489 "On blank line, delete all surrounding blank lines, leaving just one.
490 On isolated blank line, delete that one.
491 On nonblank line, delete any immediately following blank lines."
493 (let (thisblank singleblank)
496 (setq thisblank (looking-at "[ \t]*$"))
497 ;; Set singleblank if there is just one blank line here.
500 (not (looking-at "[ \t]*\n[ \t]*$"))
502 (progn (forward-line -1)
503 (not (looking-at "[ \t]*$")))))))
504 ;; Delete preceding blank lines, and this one too if it's the only one.
508 (if singleblank (forward-line 1))
509 (delete-region (point)
510 (if (re-search-backward "[^ \t\n]" nil t)
511 (progn (forward-line 1) (point))
513 ;; Delete following blank lines, unless the current line is blank
514 ;; and there are no following blank lines.
515 (if (not (and thisblank singleblank))
519 (delete-region (point)
520 (if (re-search-forward "[^ \t\n]" nil t)
521 (progn (beginning-of-line) (point))
523 ;; Handle the special case where point is followed by newline and eob.
524 ;; Delete the line, leaving point at eob.
525 (if (looking-at "^[ \t]*\n\\'")
526 (delete-region (point) (point-max)))))
528 (defun delete-trailing-whitespace ()
529 "Delete all the trailing whitespace across the current buffer.
530 All whitespace after the last non-whitespace character in a line is deleted.
531 This respects narrowing, created by \\[narrow-to-region] and friends.
532 A formfeed is not considered whitespace by this function."
536 (goto-char (point-min))
537 (while (re-search-forward "\\s-$" nil t)
538 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
539 ;; Don't delete formfeeds, even if they are considered whitespace.
541 (if (looking-at ".*\f")
542 (goto-char (match-end 0))))
543 (delete-region (point) (match-end 0))))))
545 (defun newline-and-indent ()
546 "Insert a newline, then indent according to major mode.
547 Indentation is done using the value of `indent-line-function'.
548 In programming language modes, this is the same as TAB.
549 In some text modes, where TAB inserts a tab, this command indents to the
550 column specified by the function `current-left-margin'."
552 (delete-horizontal-space t)
554 (indent-according-to-mode))
556 (defun reindent-then-newline-and-indent ()
557 "Reindent current line, insert newline, then indent the new line.
558 Indentation of both lines is done according to the current major mode,
559 which means calling the current value of `indent-line-function'.
560 In programming language modes, this is the same as TAB.
561 In some text modes, where TAB inserts a tab, this indents to the
562 column specified by the function `current-left-margin'."
565 ;; Be careful to insert the newline before indenting the line.
566 ;; Otherwise, the indentation might be wrong.
570 (indent-according-to-mode)
571 (delete-horizontal-space t))
572 (indent-according-to-mode)))
574 (defun quoted-insert (arg)
575 "Read next input character and insert it.
576 This is useful for inserting control characters.
578 If the first character you type after this command is an octal digit,
579 you should type a sequence of octal digits which specify a character code.
580 Any nondigit terminates the sequence. If the terminator is a RET,
581 it is discarded; any other terminator is used itself as input.
582 The variable `read-quoted-char-radix' specifies the radix for this feature;
583 set it to 10 or 16 to use decimal or hex instead of octal.
585 In overwrite mode, this function inserts the character anyway, and
586 does not handle octal digits specially. This means that if you use
587 overwrite as your normal editing mode, you can use this function to
588 insert characters when necessary.
590 In binary overwrite mode, this function does overwrite, and octal
591 digits are interpreted as a character code. This is intended to be
592 useful for editing binary files."
594 (let* ((char (let (translation-table-for-input)
595 (if (or (not overwrite-mode)
596 (eq overwrite-mode 'overwrite-mode-binary))
599 ;; Assume character codes 0240 - 0377 stand for characters in some
600 ;; single-byte character set, and convert them to Emacs
602 (if (and enable-multibyte-characters
605 (setq char (unibyte-char-to-multibyte char)))
607 (if (eq overwrite-mode 'overwrite-mode-binary)
610 (insert-and-inherit char)
611 (setq arg (1- arg)))))
613 (defun forward-to-indentation (&optional arg)
614 "Move forward ARG lines and position at first nonblank character."
616 (forward-line (or arg 1))
617 (skip-chars-forward " \t"))
619 (defun backward-to-indentation (&optional arg)
620 "Move backward ARG lines and position at first nonblank character."
622 (forward-line (- (or arg 1)))
623 (skip-chars-forward " \t"))
625 (defun back-to-indentation ()
626 "Move point to the first non-whitespace character on this line."
628 (beginning-of-line 1)
629 (skip-syntax-forward " " (line-end-position))
630 ;; Move back over chars that have whitespace syntax but have the p flag.
631 (backward-prefix-chars))
633 (defun fixup-whitespace ()
634 "Fixup white space between objects around point.
635 Leave one space or none, according to the context."
638 (delete-horizontal-space)
639 (if (or (looking-at "^\\|\\s)")
640 (save-excursion (forward-char -1)
641 (looking-at "$\\|\\s(\\|\\s'")))
645 (defun delete-horizontal-space (&optional backward-only)
646 "Delete all spaces and tabs around point.
647 If BACKWARD-ONLY is non-nil, only delete spaces before point."
649 (let ((orig-pos (point)))
654 (skip-chars-forward " \t")
655 (constrain-to-field nil orig-pos t)))
657 (skip-chars-backward " \t")
658 (constrain-to-field nil orig-pos)))))
660 (defun just-one-space (&optional n)
661 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
663 (let ((orig-pos (point)))
664 (skip-chars-backward " \t")
665 (constrain-to-field nil orig-pos)
666 (dotimes (i (or n 1))
667 (if (= (following-char) ?\ )
673 (skip-chars-forward " \t")
674 (constrain-to-field nil orig-pos t)))))
676 (defun beginning-of-buffer (&optional arg)
677 "Move point to the beginning of the buffer; leave mark at previous position.
678 With \\[universal-argument] prefix, do not set mark at previous position.
679 With numeric arg N, put point N/10 of the way from the beginning.
681 If the buffer is narrowed, this command uses the beginning and size
682 of the accessible part of the buffer.
684 Don't use this command in Lisp programs!
685 \(goto-char (point-min)) is faster and avoids clobbering the mark."
688 (and transient-mark-mode mark-active)
690 (let ((size (- (point-max) (point-min))))
691 (goto-char (if (and arg (not (consp arg)))
694 ;; Avoid overflow for large buffer sizes!
695 (* (prefix-numeric-value arg)
697 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
699 (if arg (forward-line 1)))
701 (defun end-of-buffer (&optional arg)
702 "Move point to the end of the buffer; leave mark at previous position.
703 With \\[universal-argument] prefix, do not set mark at previous position.
704 With numeric arg N, put point N/10 of the way from the end.
706 If the buffer is narrowed, this command uses the beginning and size
707 of the accessible part of the buffer.
709 Don't use this command in Lisp programs!
710 \(goto-char (point-max)) is faster and avoids clobbering the mark."
713 (and transient-mark-mode mark-active)
715 (let ((size (- (point-max) (point-min))))
716 (goto-char (if (and arg (not (consp arg)))
719 ;; Avoid overflow for large buffer sizes!
720 (* (prefix-numeric-value arg)
722 (/ (* size (prefix-numeric-value arg)) 10)))
724 ;; If we went to a place in the middle of the buffer,
725 ;; adjust it to the beginning of a line.
726 (cond (arg (forward-line 1))
727 ((> (point) (window-end nil t))
728 ;; If the end of the buffer is not already on the screen,
729 ;; then scroll specially to put it near, but not at, the bottom.
730 (overlay-recenter (point))
733 (defun mark-whole-buffer ()
734 "Put point at beginning and mark at end of buffer.
735 You probably should not use this function in Lisp programs;
736 it is usually a mistake for a Lisp function to use any subroutine
737 that uses or sets the mark."
740 (push-mark (point-max) nil t)
741 (goto-char (point-min)))
744 ;; Counting lines, one way or another.
746 (defun goto-line (arg &optional buffer)
747 "Goto line ARG, counting from line 1 at beginning of buffer.
748 Normally, move point in the current buffer.
749 With just \\[universal-argument] as argument, move point in the most recently
750 displayed other buffer, and switch to it. When called from Lisp code,
751 the optional argument BUFFER specifies a buffer to switch to.
753 If there's a number in the buffer at point, it is the default for ARG."
755 (if (and current-prefix-arg (not (consp current-prefix-arg)))
756 (list (prefix-numeric-value current-prefix-arg))
757 ;; Look for a default, a number in the buffer at point.
760 (skip-chars-backward "0-9")
761 (if (looking-at "[0-9]")
762 (buffer-substring-no-properties
764 (progn (skip-chars-forward "0-9")
766 ;; Decide if we're switching buffers.
768 (if (consp current-prefix-arg)
769 (other-buffer (current-buffer) t)))
772 (concat " in " (buffer-name buffer))
774 ;; Read the argument, offering that number (if any) as default.
775 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
783 ;; Switch to the desired buffer, one way or another.
785 (let ((window (get-buffer-window buffer)))
786 (if window (select-window window)
787 (switch-to-buffer-other-window buffer))))
788 ;; Move to the specified line number in that buffer.
792 (if (eq selective-display t)
793 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
794 (forward-line (1- arg)))))
796 (defun count-lines-region (start end)
797 "Print number of lines and characters in the region."
799 (message "Region has %d lines, %d characters"
800 (count-lines start end) (- end start)))
803 "Print the current buffer line number and narrowed line number of point."
805 (let ((start (point-min))
806 (n (line-number-at-pos)))
808 (message "Line %d" n)
812 (message "line %d (narrowed line %d)"
813 (+ n (line-number-at-pos start) -1) n))))))
815 (defun count-lines (start end)
816 "Return number of lines between START and END.
817 This is usually the number of newlines between them,
818 but can be one more if START is not equal to END
819 and the greater of them is not at the start of a line."
822 (narrow-to-region start end)
823 (goto-char (point-min))
824 (if (eq selective-display t)
827 (while (re-search-forward "[\n\C-m]" nil t 40)
828 (setq done (+ 40 done)))
829 (while (re-search-forward "[\n\C-m]" nil t 1)
830 (setq done (+ 1 done)))
831 (goto-char (point-max))
832 (if (and (/= start end)
836 (- (buffer-size) (forward-line (buffer-size)))))))
838 (defun line-number-at-pos (&optional pos)
839 "Return (narrowed) buffer line number at position POS.
840 If POS is nil, use current buffer location."
841 (let ((opoint (or pos (point))) start)
843 (goto-char (point-min))
847 (1+ (count-lines start (point))))))
849 (defun what-cursor-position (&optional detail)
850 "Print info on cursor position (on screen and within buffer).
851 Also describe the character after point, and give its character code
852 in octal, decimal and hex.
854 For a non-ASCII multibyte character, also give its encoding in the
855 buffer's selected coding system if the coding system encodes the
856 character safely. If the character is encoded into one byte, that
857 code is shown in hex. If the character is encoded into more than one
858 byte, just \"...\" is shown.
860 In addition, with prefix argument, show details about that character
861 in *Help* buffer. See also the command `describe-char'."
863 (let* ((char (following-char))
867 (total (buffer-size))
868 (percent (if (> total 50000)
869 ;; Avoid overflow from multiplying by 100!
870 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
871 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
872 (hscroll (if (= (window-hscroll) 0)
874 (format " Hscroll=%d" (window-hscroll))))
875 (col (current-column)))
877 (if (or (/= beg 1) (/= end (1+ total)))
878 (message "point=%d of %d (%d%%) <%d - %d> column %d %s"
879 pos total percent beg end col hscroll)
880 (message "point=%d of %d (%d%%) column %d %s"
881 pos total percent col hscroll))
882 (let ((coding buffer-file-coding-system)
883 encoded encoding-msg)
885 (eq (coding-system-type coding) t))
886 (setq coding default-buffer-file-coding-system))
887 (if (not (char-valid-p char))
889 (format "(0%o, %d, 0x%x, invalid)" char char char))
890 (setq encoded (and (>= char 128) (encode-coding-char char coding)))
893 (format "(0%o, %d, 0x%x, file %s)"
895 (if (> (length encoded) 1)
897 (encoded-string-description encoded coding)))
898 (format "(0%o, %d, 0x%x)" char char char))))
900 ;; We show the detailed information about CHAR.
901 (describe-char (point)))
902 (if (or (/= beg 1) (/= end (1+ total)))
903 (message "Char: %s %s point=%d of %d (%d%%) <%d - %d> column %d %s"
905 (single-key-description char)
906 (buffer-substring-no-properties (point) (1+ (point))))
907 encoding-msg pos total percent beg end col hscroll)
908 (message "Char: %s %s point=%d of %d (%d%%) column %d %s"
910 (single-key-description char)
911 (buffer-substring-no-properties (point) (1+ (point))))
912 encoding-msg pos total percent col hscroll))))))
914 (defvar read-expression-map
915 (let ((m (make-sparse-keymap)))
916 (define-key m "\M-\t" 'lisp-complete-symbol)
917 (set-keymap-parent m minibuffer-local-map)
919 "Minibuffer keymap used for reading Lisp expressions.")
921 (defvar read-expression-history nil)
923 (defcustom eval-expression-print-level 4
924 "Value for `print-level' while printing value in `eval-expression'.
925 A value of nil means no limit."
927 :type '(choice (const :tag "No Limit" nil) integer)
930 (defcustom eval-expression-print-length 12
931 "Value for `print-length' while printing value in `eval-expression'.
932 A value of nil means no limit."
934 :type '(choice (const :tag "No Limit" nil) integer)
937 (defcustom eval-expression-debug-on-error t
938 "If non-nil set `debug-on-error' to t in `eval-expression'.
939 If nil, don't change the value of `debug-on-error'."
944 (defun eval-expression-print-format (value)
945 "Format VALUE as a result of evaluated expression.
946 Return a formatted string which is displayed in the echo area
947 in addition to the value printed by prin1 in functions which
948 display the result of expression evaluation."
949 (if (and (integerp value)
950 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
951 (eq this-command last-command)
952 (if (boundp 'edebug-active) edebug-active)))
954 (if (or (if (boundp 'edebug-active) edebug-active)
955 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
956 (prin1-char value))))
958 (format " (0%o, 0x%x) = %s" value value char-string)
959 (format " (0%o, 0x%x)" value value)))))
961 ;; We define this, rather than making `eval' interactive,
962 ;; for the sake of completion of names like eval-region, eval-current-buffer.
963 (defun eval-expression (eval-expression-arg
964 &optional eval-expression-insert-value)
965 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
966 Value is also consed on to front of the variable `values'.
967 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
968 insert the result into the current buffer instead of printing it in
971 (list (read-from-minibuffer "Eval: "
972 nil read-expression-map t
973 'read-expression-history)
976 (if (null eval-expression-debug-on-error)
977 (setq values (cons (eval eval-expression-arg) values))
978 (let ((old-value (make-symbol "t")) new-value)
979 ;; Bind debug-on-error to something unique so that we can
980 ;; detect when evaled code changes it.
981 (let ((debug-on-error old-value))
982 (setq values (cons (eval eval-expression-arg) values))
983 (setq new-value debug-on-error))
984 ;; If evaled code has changed the value of debug-on-error,
985 ;; propagate that change to the global binding.
986 (unless (eq old-value new-value)
987 (setq debug-on-error new-value))))
989 (let ((print-length eval-expression-print-length)
990 (print-level eval-expression-print-level))
991 (if eval-expression-insert-value
993 (let ((standard-output (current-buffer)))
994 (eval-last-sexp-print-value (car values))))
996 (prin1 (car values) t)
997 (let ((str (eval-expression-print-format (car values))))
998 (if str (princ str t)))))))
1000 (defun edit-and-eval-command (prompt command)
1001 "Prompting with PROMPT, let user edit COMMAND and eval result.
1002 COMMAND is a Lisp expression. Let user edit that expression in
1003 the minibuffer, then read and evaluate the result."
1005 (let ((print-level nil)
1006 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1008 (read-from-minibuffer prompt
1009 (prin1-to-string command)
1010 read-expression-map t
1012 ;; If command was added to command-history as a string,
1013 ;; get rid of that. We want only evaluable expressions there.
1014 (if (stringp (car command-history))
1015 (setq command-history (cdr command-history)))))))
1017 ;; If command to be redone does not match front of history,
1018 ;; add it to the history.
1019 (or (equal command (car command-history))
1020 (setq command-history (cons command command-history)))
1023 (defun repeat-complex-command (arg)
1024 "Edit and re-evaluate last complex command, or ARGth from last.
1025 A complex command is one which used the minibuffer.
1026 The command is placed in the minibuffer as a Lisp form for editing.
1027 The result is executed, repeating the command as changed.
1028 If the command has been changed or is not the most recent previous command
1029 it is added to the front of the command history.
1030 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1031 to get different commands to edit and resubmit."
1033 (let ((elt (nth (1- arg) command-history))
1038 (let ((print-level nil)
1039 (minibuffer-history-position arg)
1040 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1042 (read-from-minibuffer
1043 "Redo: " (prin1-to-string elt) read-expression-map t
1044 (cons 'command-history arg))
1046 ;; If command was added to command-history as a
1047 ;; string, get rid of that. We want only
1048 ;; evaluable expressions there.
1049 (if (stringp (car command-history))
1050 (setq command-history (cdr command-history))))))
1052 ;; If command to be redone does not match front of history,
1053 ;; add it to the history.
1054 (or (equal newcmd (car command-history))
1055 (setq command-history (cons newcmd command-history)))
1058 (error "Argument %d is beyond length of command history" arg)
1059 (error "There are no previous complex commands to repeat")))))
1061 (defvar minibuffer-history nil
1062 "Default minibuffer history list.
1063 This is used for all minibuffer input
1064 except when an alternate history list is specified.")
1065 (defvar minibuffer-history-sexp-flag nil
1066 "Control whether history list elements are expressions or strings.
1067 If the value of this variable equals current minibuffer depth,
1068 they are expressions; otherwise they are strings.
1069 \(That convention is designed to do the right thing fora
1070 recursive uses of the minibuffer.)")
1071 (setq minibuffer-history-variable 'minibuffer-history)
1072 (setq minibuffer-history-position nil)
1073 (defvar minibuffer-history-search-history nil)
1075 (defvar minibuffer-text-before-history nil
1076 "Text that was in this minibuffer before any history commands.
1077 This is nil if there have not yet been any history commands
1078 in this use of the minibuffer.")
1080 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1082 (defun minibuffer-history-initialize ()
1083 (setq minibuffer-text-before-history nil))
1085 (defun minibuffer-avoid-prompt (new old)
1086 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1087 (constrain-to-field nil (point-max)))
1089 (defcustom minibuffer-history-case-insensitive-variables nil
1090 "*Minibuffer history variables for which matching should ignore case.
1091 If a history variable is a member of this list, then the
1092 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1093 commands ignore case when searching it, regardless of `case-fold-search'."
1094 :type '(repeat variable)
1097 (defun previous-matching-history-element (regexp n)
1098 "Find the previous history element that matches REGEXP.
1099 \(Previous history elements refer to earlier actions.)
1100 With prefix argument N, search for Nth previous match.
1101 If N is negative, find the next or Nth next match.
1102 Normally, history elements are matched case-insensitively if
1103 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1104 makes the search case-sensitive.
1105 See also `minibuffer-history-case-insensitive-variables'."
1107 (let* ((enable-recursive-minibuffers t)
1108 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1110 minibuffer-local-map
1112 'minibuffer-history-search-history
1113 (car minibuffer-history-search-history))))
1114 ;; Use the last regexp specified, by default, if input is empty.
1115 (list (if (string= regexp "")
1116 (if minibuffer-history-search-history
1117 (car minibuffer-history-search-history)
1118 (error "No previous history search regexp"))
1120 (prefix-numeric-value current-prefix-arg))))
1122 (if (and (zerop minibuffer-history-position)
1123 (null minibuffer-text-before-history))
1124 (setq minibuffer-text-before-history
1125 (minibuffer-contents-no-properties)))
1126 (let ((history (symbol-value minibuffer-history-variable))
1128 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1129 ;; On some systems, ignore case for file names.
1130 (if (memq minibuffer-history-variable
1131 minibuffer-history-case-insensitive-variables)
1133 ;; Respect the user's setting for case-fold-search:
1139 (pos minibuffer-history-position))
1142 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1143 (when (= pos prevpos)
1144 (error (if (= pos 1)
1145 "No later matching history item"
1146 "No earlier matching history item")))
1148 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1149 (let ((print-level nil))
1150 (prin1-to-string (nth (1- pos) history)))
1151 (nth (1- pos) history)))
1154 (and (string-match regexp match-string)
1156 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1157 (match-beginning 1))))
1159 (setq n (+ n (if (< n 0) 1 -1)))))
1160 (setq minibuffer-history-position pos)
1161 (goto-char (point-max))
1162 (delete-minibuffer-contents)
1163 (insert match-string)
1164 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1165 (if (memq (car (car command-history)) '(previous-matching-history-element
1166 next-matching-history-element))
1167 (setq command-history (cdr command-history))))
1169 (defun next-matching-history-element (regexp n)
1170 "Find the next history element that matches REGEXP.
1171 \(The next history element refers to a more recent action.)
1172 With prefix argument N, search for Nth next match.
1173 If N is negative, find the previous or Nth previous match.
1174 Normally, history elements are matched case-insensitively if
1175 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1176 makes the search case-sensitive."
1178 (let* ((enable-recursive-minibuffers t)
1179 (regexp (read-from-minibuffer "Next element matching (regexp): "
1181 minibuffer-local-map
1183 'minibuffer-history-search-history
1184 (car minibuffer-history-search-history))))
1185 ;; Use the last regexp specified, by default, if input is empty.
1186 (list (if (string= regexp "")
1187 (if minibuffer-history-search-history
1188 (car minibuffer-history-search-history)
1189 (error "No previous history search regexp"))
1191 (prefix-numeric-value current-prefix-arg))))
1192 (previous-matching-history-element regexp (- n)))
1194 (defvar minibuffer-temporary-goal-position nil)
1196 (defun next-history-element (n)
1197 "Insert the next element of the minibuffer history into the minibuffer."
1200 (let ((narg (- minibuffer-history-position n))
1201 (minimum (if minibuffer-default -1 0))
1202 elt minibuffer-returned-to-present)
1203 (if (and (zerop minibuffer-history-position)
1204 (null minibuffer-text-before-history))
1205 (setq minibuffer-text-before-history
1206 (minibuffer-contents-no-properties)))
1207 (if (< narg minimum)
1208 (if minibuffer-default
1209 (error "End of history; no next item")
1210 (error "End of history; no default available")))
1211 (if (> narg (length (symbol-value minibuffer-history-variable)))
1212 (error "Beginning of history; no preceding item"))
1213 (unless (memq last-command '(next-history-element
1214 previous-history-element))
1215 (let ((prompt-end (minibuffer-prompt-end)))
1216 (set (make-local-variable 'minibuffer-temporary-goal-position)
1217 (cond ((<= (point) prompt-end) prompt-end)
1220 (goto-char (point-max))
1221 (delete-minibuffer-contents)
1222 (setq minibuffer-history-position narg)
1224 (setq elt minibuffer-default))
1226 (setq elt (or minibuffer-text-before-history ""))
1227 (setq minibuffer-returned-to-present t)
1228 (setq minibuffer-text-before-history nil))
1229 (t (setq elt (nth (1- minibuffer-history-position)
1230 (symbol-value minibuffer-history-variable)))))
1232 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1233 (not minibuffer-returned-to-present))
1234 (let ((print-level nil))
1235 (prin1-to-string elt))
1237 (goto-char (or minibuffer-temporary-goal-position (point-max))))))
1239 (defun previous-history-element (n)
1240 "Inserts the previous element of the minibuffer history into the minibuffer."
1242 (next-history-element (- n)))
1244 (defun next-complete-history-element (n)
1245 "Get next history element which completes the minibuffer before the point.
1246 The contents of the minibuffer after the point are deleted, and replaced
1247 by the new completion."
1249 (let ((point-at-start (point)))
1250 (next-matching-history-element
1252 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1254 ;; next-matching-history-element always puts us at (point-min).
1255 ;; Move to the position we were at before changing the buffer contents.
1256 ;; This is still sensical, because the text before point has not changed.
1257 (goto-char point-at-start)))
1259 (defun previous-complete-history-element (n)
1261 Get previous history element which completes the minibuffer before the point.
1262 The contents of the minibuffer after the point are deleted, and replaced
1263 by the new completion."
1265 (next-complete-history-element (- n)))
1267 ;; For compatibility with the old subr of the same name.
1268 (defun minibuffer-prompt-width ()
1269 "Return the display width of the minibuffer prompt.
1270 Return 0 if current buffer is not a mini-buffer."
1271 ;; Return the width of everything before the field at the end of
1272 ;; the buffer; this should be 0 for normal buffers.
1273 (1- (minibuffer-prompt-end)))
1275 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1276 (defalias 'advertised-undo 'undo)
1278 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1279 "Table mapping redo records to the corresponding undo one.
1280 A redo record for undo-in-region maps to t.
1281 A redo record for ordinary undo maps to the following (earlier) undo.")
1283 (defvar undo-in-region nil
1284 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1286 (defvar undo-no-redo nil
1287 "If t, `undo' doesn't go through redo entries.")
1289 (defvar pending-undo-list nil
1290 "Within a run of consecutive undo commands, list remaining to be undone.
1291 If t, we undid all the way to the end of it.")
1293 (defun undo (&optional arg)
1294 "Undo some previous changes.
1295 Repeat this command to undo more changes.
1296 A numeric argument serves as a repeat count.
1298 In Transient Mark mode when the mark is active, only undo changes within
1299 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1300 as an argument limits undo to changes within the current region."
1302 ;; Make last-command indicate for the next command that this was an undo.
1303 ;; That way, another undo will undo more.
1304 ;; If we get to the end of the undo history and get an error,
1305 ;; another undo command will find the undo history empty
1306 ;; and will get another error. To begin undoing the undos,
1307 ;; you must type some other command.
1308 (let ((modified (buffer-modified-p))
1309 (recent-save (recent-auto-save-p)))
1310 ;; If we get an error in undo-start,
1311 ;; the next command should not be a "consecutive undo".
1312 ;; So set `this-command' to something other than `undo'.
1313 (setq this-command 'undo-start)
1315 (unless (and (eq last-command 'undo)
1316 (or (eq pending-undo-list t)
1317 ;; If something (a timer or filter?) changed the buffer
1318 ;; since the previous command, don't continue the undo seq.
1319 (let ((list buffer-undo-list))
1320 (while (eq (car list) nil)
1321 (setq list (cdr list)))
1322 ;; If the last undo record made was made by undo
1323 ;; it shows nothing else happened in between.
1324 (gethash list undo-equiv-table))))
1325 (setq undo-in-region
1326 (if transient-mark-mode mark-active (and arg (not (numberp arg)))))
1328 (undo-start (region-beginning) (region-end))
1330 ;; get rid of initial undo boundary
1332 ;; If we got this far, the next command should be a consecutive undo.
1333 (setq this-command 'undo)
1334 ;; Check to see whether we're hitting a redo record, and if
1335 ;; so, ask the user whether she wants to skip the redo/undo pair.
1336 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1337 (or (eq (selected-window) (minibuffer-window))
1338 (message (if undo-in-region
1339 (if equiv "Redo in region!" "Undo in region!")
1340 (if equiv "Redo!" "Undo!"))))
1341 (when (and (consp equiv) undo-no-redo)
1342 ;; The equiv entry might point to another redo record if we have done
1343 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1344 (while (let ((next (gethash equiv undo-equiv-table)))
1345 (if next (setq equiv next))))
1346 (setq pending-undo-list equiv)))
1348 (if (or transient-mark-mode (numberp arg))
1349 (prefix-numeric-value arg)
1351 ;; Record the fact that the just-generated undo records come from an
1352 ;; undo operation--that is, they are redo records.
1353 ;; In the ordinary case (not within a region), map the redo
1354 ;; record to the following undos.
1355 ;; I don't know how to do that in the undo-in-region case.
1356 (puthash buffer-undo-list
1357 (if undo-in-region t pending-undo-list)
1359 ;; Don't specify a position in the undo record for the undo command.
1360 ;; Instead, undoing this should move point to where the change is.
1361 (let ((tail buffer-undo-list)
1364 (when (integerp (car tail))
1365 (let ((pos (car tail)))
1367 (setcdr prev (cdr tail))
1368 (setq buffer-undo-list (cdr tail)))
1369 (setq tail (cdr tail))
1371 (if (eq pos (car tail))
1373 (setcdr prev (cdr tail))
1374 (setq buffer-undo-list (cdr tail)))
1376 (setq tail (cdr tail)))
1378 (setq prev tail tail (cdr tail))))
1379 ;; Record what the current undo list says,
1380 ;; so the next command can tell if the buffer was modified in between.
1381 (and modified (not (buffer-modified-p))
1382 (delete-auto-save-file-if-necessary recent-save))))
1384 (defun buffer-disable-undo (&optional buffer)
1385 "Make BUFFER stop keeping undo information.
1386 No argument or nil as argument means do this for the current buffer."
1388 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
1389 (setq buffer-undo-list t)))
1391 (defun undo-only (&optional arg)
1392 "Undo some previous changes.
1393 Repeat this command to undo more changes.
1394 A numeric argument serves as a repeat count.
1395 Contrary to `undo', this will not redo a previous undo."
1397 (let ((undo-no-redo t)) (undo arg)))
1399 (defvar undo-in-progress nil
1400 "Non-nil while performing an undo.
1401 Some change-hooks test this variable to do something different.")
1403 (defun undo-more (n)
1404 "Undo back N undo-boundaries beyond what was already undone recently.
1405 Call `undo-start' to get ready to undo recent changes,
1406 then call `undo-more' one or more times to undo them."
1407 (or (listp pending-undo-list)
1408 (error (concat "No further undo information"
1409 (and transient-mark-mode mark-active
1411 (let ((undo-in-progress t))
1412 (setq pending-undo-list (primitive-undo n pending-undo-list))
1413 (if (null pending-undo-list)
1414 (setq pending-undo-list t))))
1416 ;; Deep copy of a list
1417 (defun undo-copy-list (list)
1418 "Make a copy of undo list LIST."
1419 (mapcar 'undo-copy-list-1 list))
1421 (defun undo-copy-list-1 (elt)
1423 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1426 (defun undo-start (&optional beg end)
1427 "Set `pending-undo-list' to the front of the undo list.
1428 The next call to `undo-more' will undo the most recently made change.
1429 If BEG and END are specified, then only undo elements
1430 that apply to text between BEG and END are used; other undo elements
1431 are ignored. If BEG and END are nil, all undo elements are used."
1432 (if (eq buffer-undo-list t)
1433 (error "No undo information in this buffer"))
1434 (setq pending-undo-list
1435 (if (and beg end (not (= beg end)))
1436 (undo-make-selective-list (min beg end) (max beg end))
1439 (defvar undo-adjusted-markers)
1441 (defun undo-make-selective-list (start end)
1442 "Return a list of undo elements for the region START to END.
1443 The elements come from `buffer-undo-list', but we keep only
1444 the elements inside this region, and discard those outside this region.
1445 If we find an element that crosses an edge of this region,
1446 we stop and ignore all further elements."
1447 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1448 (undo-list (list nil))
1449 undo-adjusted-markers
1451 undo-elt undo-elt temp-undo-list delta)
1452 (while undo-list-copy
1453 (setq undo-elt (car undo-list-copy))
1455 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1456 ;; This is a "was unmodified" element.
1457 ;; Keep it if we have kept everything thus far.
1458 (not some-rejected))
1460 (undo-elt-in-region undo-elt start end)))))
1463 (setq end (+ end (cdr (undo-delta undo-elt))))
1464 ;; Don't put two nils together in the list
1465 (if (not (and (eq (car undo-list) nil)
1467 (setq undo-list (cons undo-elt undo-list))))
1468 (if (undo-elt-crosses-region undo-elt start end)
1469 (setq undo-list-copy nil)
1470 (setq some-rejected t)
1471 (setq temp-undo-list (cdr undo-list-copy))
1472 (setq delta (undo-delta undo-elt))
1474 (when (/= (cdr delta) 0)
1475 (let ((position (car delta))
1476 (offset (cdr delta)))
1478 ;; Loop down the earlier events adjusting their buffer
1479 ;; positions to reflect the fact that a change to the buffer
1480 ;; isn't being undone. We only need to process those element
1481 ;; types which undo-elt-in-region will return as being in
1482 ;; the region since only those types can ever get into the
1485 (while temp-undo-list
1486 (setq undo-elt (car temp-undo-list))
1487 (cond ((integerp undo-elt)
1488 (if (>= undo-elt position)
1489 (setcar temp-undo-list (- undo-elt offset))))
1490 ((atom undo-elt) nil)
1491 ((stringp (car undo-elt))
1492 ;; (TEXT . POSITION)
1493 (let ((text-pos (abs (cdr undo-elt)))
1494 (point-at-end (< (cdr undo-elt) 0 )))
1495 (if (>= text-pos position)
1496 (setcdr undo-elt (* (if point-at-end -1 1)
1497 (- text-pos offset))))))
1498 ((integerp (car undo-elt))
1500 (when (>= (car undo-elt) position)
1501 (setcar undo-elt (- (car undo-elt) offset))
1502 (setcdr undo-elt (- (cdr undo-elt) offset))))
1503 ((null (car undo-elt))
1504 ;; (nil PROPERTY VALUE BEG . END)
1505 (let ((tail (nthcdr 3 undo-elt)))
1506 (when (>= (car tail) position)
1507 (setcar tail (- (car tail) offset))
1508 (setcdr tail (- (cdr tail) offset))))))
1509 (setq temp-undo-list (cdr temp-undo-list))))))))
1510 (setq undo-list-copy (cdr undo-list-copy)))
1511 (nreverse undo-list)))
1513 (defun undo-elt-in-region (undo-elt start end)
1514 "Determine whether UNDO-ELT falls inside the region START ... END.
1515 If it crosses the edge, we return nil."
1516 (cond ((integerp undo-elt)
1517 (and (>= undo-elt start)
1523 ((stringp (car undo-elt))
1524 ;; (TEXT . POSITION)
1525 (and (>= (abs (cdr undo-elt)) start)
1526 (< (abs (cdr undo-elt)) end)))
1527 ((and (consp undo-elt) (markerp (car undo-elt)))
1528 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1529 ;; See if MARKER is inside the region.
1530 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1532 (setq alist-elt (cons (car undo-elt)
1533 (marker-position (car undo-elt))))
1534 (setq undo-adjusted-markers
1535 (cons alist-elt undo-adjusted-markers)))
1536 (and (cdr alist-elt)
1537 (>= (cdr alist-elt) start)
1538 (<= (cdr alist-elt) end))))
1539 ((null (car undo-elt))
1540 ;; (nil PROPERTY VALUE BEG . END)
1541 (let ((tail (nthcdr 3 undo-elt)))
1542 (and (>= (car tail) start)
1543 (<= (cdr tail) end))))
1544 ((integerp (car undo-elt))
1546 (and (>= (car undo-elt) start)
1547 (<= (cdr undo-elt) end)))))
1549 (defun undo-elt-crosses-region (undo-elt start end)
1550 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1551 This assumes we have already decided that UNDO-ELT
1552 is not *inside* the region START...END."
1553 (cond ((atom undo-elt) nil)
1554 ((null (car undo-elt))
1555 ;; (nil PROPERTY VALUE BEG . END)
1556 (let ((tail (nthcdr 3 undo-elt)))
1557 (not (or (< (car tail) end)
1558 (> (cdr tail) start)))))
1559 ((integerp (car undo-elt))
1561 (not (or (< (car undo-elt) end)
1562 (> (cdr undo-elt) start))))))
1564 ;; Return the first affected buffer position and the delta for an undo element
1565 ;; delta is defined as the change in subsequent buffer positions if we *did*
1567 (defun undo-delta (undo-elt)
1568 (if (consp undo-elt)
1569 (cond ((stringp (car undo-elt))
1570 ;; (TEXT . POSITION)
1571 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1572 ((integerp (car undo-elt))
1574 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1579 (defcustom undo-ask-before-discard t
1580 "If non-nil ask about discarding undo info for the current command.
1581 Normally, Emacs discards the undo info for the current command if
1582 it exceeds `undo-outer-limit'. But if you set this option
1583 non-nil, it asks in the echo area whether to discard the info.
1584 If you answer no, there a slight risk that Emacs might crash, so
1585 only do it if you really want to undo the command.
1587 This option is mainly intended for debugging. You have to be
1588 careful if you use it for other purposes. Garbage collection is
1589 inhibited while the question is asked, meaning that Emacs might
1590 leak memory. So you should make sure that you do not wait
1591 excessively long before answering the question."
1596 (defvar undo-extra-outer-limit nil
1597 "If non-nil, an extra level of size that's ok in an undo item.
1598 We don't ask the user about truncating the undo list until the
1599 current item gets bigger than this amount.
1601 This variable only matters if `undo-ask-before-discard' is non-nil.")
1602 (make-variable-buffer-local 'undo-extra-outer-limit)
1604 ;; When the first undo batch in an undo list is longer than
1605 ;; undo-outer-limit, this function gets called to warn the user that
1606 ;; the undo info for the current command was discarded. Garbage
1607 ;; collection is inhibited around the call, so it had better not do a
1609 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
1610 (defun undo-outer-limit-truncate (size)
1611 (if undo-ask-before-discard
1612 (when (or (null undo-extra-outer-limit)
1613 (> size undo-extra-outer-limit))
1614 ;; Don't ask the question again unless it gets even bigger.
1615 ;; This applies, in particular, if the user quits from the question.
1616 ;; Such a quit quits out of GC, but something else will call GC
1617 ;; again momentarily. It will call this function again,
1618 ;; but we don't want to ask the question again.
1619 (setq undo-extra-outer-limit (+ size 50000))
1620 (if (let (use-dialog-box track-mouse executing-kbd-macro )
1621 (yes-or-no-p (format "Buffer %s undo info is %d bytes long; discard it? "
1622 (buffer-name) size)))
1623 (progn (setq buffer-undo-list nil)
1624 (setq undo-extra-outer-limit nil)
1627 (display-warning '(undo discard-info)
1629 (format "Buffer %s undo info was %d bytes long.\n"
1631 "The undo info was discarded because it exceeded \
1634 This is normal if you executed a command that made a huge change
1635 to the buffer. In that case, to prevent similar problems in the
1636 future, set `undo-outer-limit' to a value that is large enough to
1637 cover the maximum size of normal changes you expect a single
1638 command to make, but not so large that it might exceed the
1639 maximum memory allotted to Emacs.
1641 If you did not execute any such command, the situation is
1642 probably due to a bug and you should report it.
1644 You can disable the popping up of this buffer by adding the entry
1645 \(undo discard-info) to the user option `warning-suppress-types'.\n")
1647 (setq buffer-undo-list nil)
1650 (defvar shell-command-history nil
1651 "History list for some commands that read shell commands.")
1653 (defvar shell-command-switch "-c"
1654 "Switch used to have the shell execute its command line argument.")
1656 (defvar shell-command-default-error-buffer nil
1657 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1658 This buffer is used when `shell-command' or `shell-command-on-region'
1659 is run interactively. A value of nil means that output to stderr and
1660 stdout will be intermixed in the output stream.")
1662 (defun shell-command (command &optional output-buffer error-buffer)
1663 "Execute string COMMAND in inferior shell; display output, if any.
1664 With prefix argument, insert the COMMAND's output at point.
1666 If COMMAND ends in ampersand, execute it asynchronously.
1667 The output appears in the buffer `*Async Shell Command*'.
1668 That buffer is in shell mode.
1670 Otherwise, COMMAND is executed synchronously. The output appears in
1671 the buffer `*Shell Command Output*'. If the output is short enough to
1672 display in the echo area (which is determined by the variables
1673 `resize-mini-windows' and `max-mini-window-height'), it is shown
1674 there, but it is nonetheless available in buffer `*Shell Command
1675 Output*' even though that buffer is not automatically displayed.
1677 To specify a coding system for converting non-ASCII characters
1678 in the shell command output, use \\[universal-coding-system-argument]
1679 before this command.
1681 Noninteractive callers can specify coding systems by binding
1682 `coding-system-for-read' and `coding-system-for-write'.
1684 The optional second argument OUTPUT-BUFFER, if non-nil,
1685 says to put the output in some other buffer.
1686 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1687 If OUTPUT-BUFFER is not a buffer and not nil,
1688 insert output in current buffer. (This cannot be done asynchronously.)
1689 In either case, the output is inserted after point (leaving mark after it).
1691 If the command terminates without error, but generates output,
1692 and you did not specify \"insert it in the current buffer\",
1693 the output can be displayed in the echo area or in its buffer.
1694 If the output is short enough to display in the echo area
1695 \(determined by the variable `max-mini-window-height' if
1696 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
1697 the buffer containing the output is displayed.
1699 If there is output and an error, and you did not specify \"insert it
1700 in the current buffer\", a message about the error goes at the end
1703 If there is no output, or if output is inserted in the current buffer,
1704 then `*Shell Command Output*' is deleted.
1706 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1707 or buffer name to which to direct the command's standard error output.
1708 If it is nil, error output is mingled with regular output.
1709 In an interactive call, the variable `shell-command-default-error-buffer'
1710 specifies the value of ERROR-BUFFER."
1712 (interactive (list (read-from-minibuffer "Shell command: "
1713 nil nil nil 'shell-command-history)
1715 shell-command-default-error-buffer))
1716 ;; Look for a handler in case default-directory is a remote file name.
1718 (find-file-name-handler (directory-file-name default-directory)
1721 (funcall handler 'shell-command command output-buffer error-buffer)
1722 (if (and output-buffer
1723 (not (or (bufferp output-buffer) (stringp output-buffer))))
1724 ;; Output goes in current buffer.
1728 (expand-file-name "scor"
1729 (or small-temporary-file-directory
1730 temporary-file-directory)))
1732 (barf-if-buffer-read-only)
1734 ;; We do not use -f for csh; we will not support broken use of
1735 ;; .cshrcs. Even the BSD csh manual says to use
1736 ;; "if ($?prompt) exit" before things which are not useful
1737 ;; non-interactively. Besides, if someone wants their other
1738 ;; aliases for shell commands then they can still have them.
1739 (call-process shell-file-name nil
1743 nil shell-command-switch command)
1744 (when (and error-file (file-exists-p error-file))
1745 (if (< 0 (nth 7 (file-attributes error-file)))
1746 (with-current-buffer (get-buffer-create error-buffer)
1747 (let ((pos-from-end (- (point-max) (point))))
1750 ;; Do no formatting while reading error file,
1751 ;; because that can run a shell command, and we
1752 ;; don't want that to cause an infinite recursion.
1753 (format-insert-file error-file nil)
1754 ;; Put point after the inserted errors.
1755 (goto-char (- (point-max) pos-from-end)))
1756 (display-buffer (current-buffer))))
1757 (delete-file error-file))
1758 ;; This is like exchange-point-and-mark, but doesn't
1759 ;; activate the mark. It is cleaner to avoid activation,
1760 ;; even though the command loop would deactivate the mark
1761 ;; because we inserted text.
1762 (goto-char (prog1 (mark t)
1763 (set-marker (mark-marker) (point)
1764 (current-buffer)))))
1765 ;; Output goes in a separate buffer.
1766 ;; Preserve the match data in case called from a program.
1768 (if (string-match "[ \t]*&[ \t]*\\'" command)
1769 ;; Command ending with ampersand means asynchronous.
1770 (let ((buffer (get-buffer-create
1771 (or output-buffer "*Async Shell Command*")))
1772 (directory default-directory)
1774 ;; Remove the ampersand.
1775 (setq command (substring command 0 (match-beginning 0)))
1776 ;; If will kill a process, query first.
1777 (setq proc (get-buffer-process buffer))
1779 (if (yes-or-no-p "A command is running. Kill it? ")
1781 (error "Shell command in progress")))
1782 (with-current-buffer buffer
1783 (setq buffer-read-only nil)
1785 (display-buffer buffer)
1786 (setq default-directory directory)
1787 (setq proc (start-process "Shell" buffer shell-file-name
1788 shell-command-switch command))
1789 (setq mode-line-process '(":%s"))
1790 (require 'shell) (shell-mode)
1791 (set-process-sentinel proc 'shell-command-sentinel)
1793 (shell-command-on-region (point) (point) command
1794 output-buffer nil error-buffer)))))))
1796 (defun display-message-or-buffer (message
1797 &optional buffer-name not-this-window frame)
1798 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1799 MESSAGE may be either a string or a buffer.
1801 A buffer is displayed using `display-buffer' if MESSAGE is too long for
1802 the maximum height of the echo area, as defined by `max-mini-window-height'
1803 if `resize-mini-windows' is non-nil.
1805 Returns either the string shown in the echo area, or when a pop-up
1806 buffer is used, the window used to display it.
1808 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1809 name of the buffer used to display it in the case where a pop-up buffer
1810 is used, defaulting to `*Message*'. In the case where MESSAGE is a
1811 string and it is displayed in the echo area, it is not specified whether
1812 the contents are inserted into the buffer anyway.
1814 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1815 and only used if a buffer is displayed."
1816 (cond ((and (stringp message) (not (string-match "\n" message)))
1817 ;; Trivial case where we can use the echo area
1818 (message "%s" message))
1819 ((and (stringp message)
1820 (= (string-match "\n" message) (1- (length message))))
1821 ;; Trivial case where we can just remove single trailing newline
1822 (message "%s" (substring message 0 (1- (length message)))))
1825 (with-current-buffer
1826 (if (bufferp message)
1828 (get-buffer-create (or buffer-name "*Message*")))
1830 (unless (bufferp message)
1835 (if (= (buffer-size) 0)
1837 (count-lines (point-min) (point-max)))))
1839 ((and (or (<= lines 1)
1841 (if resize-mini-windows
1842 (cond ((floatp max-mini-window-height)
1844 max-mini-window-height))
1845 ((integerp max-mini-window-height)
1846 max-mini-window-height)
1850 ;; Don't use the echo area if the output buffer is
1851 ;; already dispayed in the selected frame.
1852 (not (get-buffer-window (current-buffer))))
1854 (goto-char (point-max))
1857 (message "%s" (buffer-substring (point-min) (point))))
1860 (goto-char (point-min))
1861 (display-buffer (current-buffer)
1862 not-this-window frame))))))))
1865 ;; We have a sentinel to prevent insertion of a termination message
1866 ;; in the buffer itself.
1867 (defun shell-command-sentinel (process signal)
1868 (if (memq (process-status process) '(exit signal))
1870 (car (cdr (cdr (process-command process))))
1871 (substring signal 0 -1))))
1873 (defun shell-command-on-region (start end command
1874 &optional output-buffer replace
1875 error-buffer display-error-buffer)
1876 "Execute string COMMAND in inferior shell with region as input.
1877 Normally display output (if any) in temp buffer `*Shell Command Output*';
1878 Prefix arg means replace the region with it. Return the exit code of
1881 To specify a coding system for converting non-ASCII characters
1882 in the input and output to the shell command, use \\[universal-coding-system-argument]
1883 before this command. By default, the input (from the current buffer)
1884 is encoded in the same coding system that will be used to save the file,
1885 `buffer-file-coding-system'. If the output is going to replace the region,
1886 then it is decoded from that same coding system.
1888 The noninteractive arguments are START, END, COMMAND,
1889 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
1890 Noninteractive callers can specify coding systems by binding
1891 `coding-system-for-read' and `coding-system-for-write'.
1893 If the command generates output, the output may be displayed
1894 in the echo area or in a buffer.
1895 If the output is short enough to display in the echo area
1896 \(determined by the variable `max-mini-window-height' if
1897 `resize-mini-windows' is non-nil), it is shown there. Otherwise
1898 it is displayed in the buffer `*Shell Command Output*'. The output
1899 is available in that buffer in both cases.
1901 If there is output and an error, a message about the error
1902 appears at the end of the output.
1904 If there is no output, or if output is inserted in the current buffer,
1905 then `*Shell Command Output*' is deleted.
1907 If the optional fourth argument OUTPUT-BUFFER is non-nil,
1908 that says to put the output in some other buffer.
1909 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1910 If OUTPUT-BUFFER is not a buffer and not nil,
1911 insert output in the current buffer.
1912 In either case, the output is inserted after point (leaving mark after it).
1914 If REPLACE, the optional fifth argument, is non-nil, that means insert
1915 the output in place of text from START to END, putting point and mark
1918 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
1919 or buffer name to which to direct the command's standard error output.
1920 If it is nil, error output is mingled with regular output.
1921 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
1922 were any errors. (This is always t, interactively.)
1923 In an interactive call, the variable `shell-command-default-error-buffer'
1924 specifies the value of ERROR-BUFFER."
1925 (interactive (let (string)
1927 (error "The mark is not set now, so there is no region"))
1928 ;; Do this before calling region-beginning
1929 ;; and region-end, in case subprocess output
1930 ;; relocates them while we are in the minibuffer.
1931 (setq string (read-from-minibuffer "Shell command on region: "
1933 'shell-command-history))
1934 ;; call-interactively recognizes region-beginning and
1935 ;; region-end specially, leaving them in the history.
1936 (list (region-beginning) (region-end)
1940 shell-command-default-error-buffer
1945 (expand-file-name "scor"
1946 (or small-temporary-file-directory
1947 temporary-file-directory)))
1952 (not (or (bufferp output-buffer) (stringp output-buffer)))))
1953 ;; Replace specified region with output from command.
1954 (let ((swap (and replace (< start end))))
1955 ;; Don't muck with mark unless REPLACE says we should.
1957 (and replace (push-mark (point) 'nomsg))
1959 (call-process-region start end shell-file-name t
1963 nil shell-command-switch command))
1964 ;; It is rude to delete a buffer which the command is not using.
1965 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
1966 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
1967 ;; (kill-buffer shell-buffer)))
1968 ;; Don't muck with mark unless REPLACE says we should.
1969 (and replace swap (exchange-point-and-mark)))
1970 ;; No prefix argument: put the output in a temp buffer,
1971 ;; replacing its entire contents.
1972 (let ((buffer (get-buffer-create
1973 (or output-buffer "*Shell Command Output*"))))
1975 (if (eq buffer (current-buffer))
1976 ;; If the input is the same buffer as the output,
1977 ;; delete everything but the specified region,
1978 ;; then replace that region with the output.
1979 (progn (setq buffer-read-only nil)
1980 (delete-region (max start end) (point-max))
1981 (delete-region (point-min) (min start end))
1983 (call-process-region (point-min) (point-max)
1988 nil shell-command-switch
1990 ;; Clear the output buffer, then run the command with
1992 (let ((directory default-directory))
1995 (setq buffer-read-only nil)
1996 (if (not output-buffer)
1997 (setq default-directory directory))
2000 (call-process-region start end shell-file-name nil
2002 (list buffer error-file)
2004 nil shell-command-switch command)))
2005 ;; Report the output.
2006 (with-current-buffer buffer
2007 (setq mode-line-process
2008 (cond ((null exit-status)
2010 ((stringp exit-status)
2011 (format " - Signal [%s]" exit-status))
2012 ((not (equal 0 exit-status))
2013 (format " - Exit [%d]" exit-status)))))
2014 (if (with-current-buffer buffer (> (point-max) (point-min)))
2015 ;; There's some output, display it
2016 (display-message-or-buffer buffer)
2017 ;; No output; error?
2020 (< 0 (nth 7 (file-attributes error-file))))
2023 (cond ((null exit-status)
2024 (message "(Shell command failed with error)"))
2025 ((equal 0 exit-status)
2026 (message "(Shell command succeeded with %s)"
2028 ((stringp exit-status)
2029 (message "(Shell command killed by signal %s)"
2032 (message "(Shell command failed with code %d and %s)"
2033 exit-status output))))
2034 ;; Don't kill: there might be useful info in the undo-log.
2035 ;; (kill-buffer buffer)
2038 (when (and error-file (file-exists-p error-file))
2039 (if (< 0 (nth 7 (file-attributes error-file)))
2040 (with-current-buffer (get-buffer-create error-buffer)
2041 (let ((pos-from-end (- (point-max) (point))))
2044 ;; Do no formatting while reading error file,
2045 ;; because that can run a shell command, and we
2046 ;; don't want that to cause an infinite recursion.
2047 (format-insert-file error-file nil)
2048 ;; Put point after the inserted errors.
2049 (goto-char (- (point-max) pos-from-end)))
2050 (and display-error-buffer
2051 (display-buffer (current-buffer)))))
2052 (delete-file error-file))
2055 (defun shell-command-to-string (command)
2056 "Execute shell command COMMAND and return its output as a string."
2057 (with-output-to-string
2058 (with-current-buffer
2060 (call-process shell-file-name nil t nil shell-command-switch command))))
2062 (defun process-file (program &optional infile buffer display &rest args)
2063 "Process files synchronously in a separate process.
2064 Similar to `call-process', but may invoke a file handler based on
2065 `default-directory'. The current working directory of the
2066 subprocess is `default-directory'.
2068 File names in INFILE and BUFFER are handled normally, but file
2069 names in ARGS should be relative to `default-directory', as they
2070 are passed to the process verbatim. \(This is a difference to
2071 `call-process' which does not support file handlers for INFILE
2074 Some file handlers might not support all variants, for example
2075 they might behave as if DISPLAY was nil, regardless of the actual
2077 (let ((fh (find-file-name-handler default-directory 'process-file))
2080 (if fh (apply fh 'process-file program infile buffer display args)
2081 (when infile (setq lc (file-local-copy infile)))
2082 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
2083 (make-temp-file "emacs")))
2085 (apply 'call-process program
2087 (if stderr-file (list (car buffer) stderr-file) buffer)
2089 (when stderr-file (copy-file stderr-file (cadr buffer)))))
2090 (when stderr-file (delete-file stderr-file))
2091 (when lc (delete-file lc)))))
2095 (defvar universal-argument-map
2096 (let ((map (make-sparse-keymap)))
2097 (define-key map [t] 'universal-argument-other-key)
2098 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2099 (define-key map [switch-frame] nil)
2100 (define-key map [?\C-u] 'universal-argument-more)
2101 (define-key map [?-] 'universal-argument-minus)
2102 (define-key map [?0] 'digit-argument)
2103 (define-key map [?1] 'digit-argument)
2104 (define-key map [?2] 'digit-argument)
2105 (define-key map [?3] 'digit-argument)
2106 (define-key map [?4] 'digit-argument)
2107 (define-key map [?5] 'digit-argument)
2108 (define-key map [?6] 'digit-argument)
2109 (define-key map [?7] 'digit-argument)
2110 (define-key map [?8] 'digit-argument)
2111 (define-key map [?9] 'digit-argument)
2112 (define-key map [kp-0] 'digit-argument)
2113 (define-key map [kp-1] 'digit-argument)
2114 (define-key map [kp-2] 'digit-argument)
2115 (define-key map [kp-3] 'digit-argument)
2116 (define-key map [kp-4] 'digit-argument)
2117 (define-key map [kp-5] 'digit-argument)
2118 (define-key map [kp-6] 'digit-argument)
2119 (define-key map [kp-7] 'digit-argument)
2120 (define-key map [kp-8] 'digit-argument)
2121 (define-key map [kp-9] 'digit-argument)
2122 (define-key map [kp-subtract] 'universal-argument-minus)
2124 "Keymap used while processing \\[universal-argument].")
2126 (defvar universal-argument-num-events nil
2127 "Number of argument-specifying events read by `universal-argument'.
2128 `universal-argument-other-key' uses this to discard those events
2129 from (this-command-keys), and reread only the final command.")
2131 (defvar overriding-map-is-bound nil
2132 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2134 (defvar saved-overriding-map nil
2135 "The saved value of `overriding-terminal-local-map'.
2136 That variable gets restored to this value on exiting \"universal
2139 (defun ensure-overriding-map-is-bound ()
2140 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2141 (unless overriding-map-is-bound
2142 (setq saved-overriding-map overriding-terminal-local-map)
2143 (setq overriding-terminal-local-map universal-argument-map)
2144 (setq overriding-map-is-bound t)))
2146 (defun restore-overriding-map ()
2147 "Restore `overriding-terminal-local-map' to its saved value."
2148 (setq overriding-terminal-local-map saved-overriding-map)
2149 (setq overriding-map-is-bound nil))
2151 (defun universal-argument ()
2152 "Begin a numeric argument for the following command.
2153 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2154 \\[universal-argument] following the digits or minus sign ends the argument.
2155 \\[universal-argument] without digits or minus sign provides 4 as argument.
2156 Repeating \\[universal-argument] without digits or minus sign
2157 multiplies the argument by 4 each time.
2158 For some commands, just \\[universal-argument] by itself serves as a flag
2159 which is different in effect from any particular numeric argument.
2160 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2162 (setq prefix-arg (list 4))
2163 (setq universal-argument-num-events (length (this-command-keys)))
2164 (ensure-overriding-map-is-bound))
2166 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2167 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2168 (defun universal-argument-more (arg)
2171 (setq prefix-arg (list (* 4 (car arg))))
2173 (setq prefix-arg (list -4))
2174 (setq prefix-arg arg)
2175 (restore-overriding-map)))
2176 (setq universal-argument-num-events (length (this-command-keys))))
2178 (defun negative-argument (arg)
2179 "Begin a negative numeric argument for the next command.
2180 \\[universal-argument] following digits or minus sign ends the argument."
2182 (cond ((integerp arg)
2183 (setq prefix-arg (- arg)))
2185 (setq prefix-arg nil))
2187 (setq prefix-arg '-)))
2188 (setq universal-argument-num-events (length (this-command-keys)))
2189 (ensure-overriding-map-is-bound))
2191 (defun digit-argument (arg)
2192 "Part of the numeric argument for the next command.
2193 \\[universal-argument] following digits or minus sign ends the argument."
2195 (let* ((char (if (integerp last-command-char)
2197 (get last-command-char 'ascii-character)))
2198 (digit (- (logand char ?\177) ?0)))
2199 (cond ((integerp arg)
2200 (setq prefix-arg (+ (* arg 10)
2201 (if (< arg 0) (- digit) digit))))
2203 ;; Treat -0 as just -, so that -01 will work.
2204 (setq prefix-arg (if (zerop digit) '- (- digit))))
2206 (setq prefix-arg digit))))
2207 (setq universal-argument-num-events (length (this-command-keys)))
2208 (ensure-overriding-map-is-bound))
2210 ;; For backward compatibility, minus with no modifiers is an ordinary
2211 ;; command if digits have already been entered.
2212 (defun universal-argument-minus (arg)
2215 (universal-argument-other-key arg)
2216 (negative-argument arg)))
2218 ;; Anything else terminates the argument and is left in the queue to be
2219 ;; executed as a command.
2220 (defun universal-argument-other-key (arg)
2222 (setq prefix-arg arg)
2223 (let* ((key (this-command-keys))
2224 (keylist (listify-key-sequence key)))
2225 (setq unread-command-events
2226 (append (nthcdr universal-argument-num-events keylist)
2227 unread-command-events)))
2228 (reset-this-command-lengths)
2229 (restore-overriding-map))
2231 (defvar buffer-substring-filters nil
2232 "List of filter functions for `filter-buffer-substring'.
2233 Each function must accept a single argument, a string, and return
2234 a string. The buffer substring is passed to the first function
2235 in the list, and the return value of each function is passed to
2236 the next. The return value of the last function is used as the
2237 return value of `filter-buffer-substring'.
2239 If this variable is nil, no filtering is performed.")
2241 (defun filter-buffer-substring (beg end &optional delete)
2242 "Return the buffer substring between BEG and END, after filtering.
2243 The buffer substring is passed through each of the filter
2244 functions in `buffer-substring-filters', and the value from the
2245 last filter function is returned. If `buffer-substring-filters'
2246 is nil, the buffer substring is returned unaltered.
2248 If DELETE is non-nil, the text between BEG and END is deleted
2251 Point is temporarily set to BEG before calling
2252 `buffer-substring-filters', in case the functions need to know
2253 where the text came from.
2255 This function should be used instead of `buffer-substring' or
2256 `delete-and-extract-region' when you want to allow filtering to
2257 take place. For example, major or minor modes can use
2258 `buffer-substring-filters' to extract characters that are special
2259 to a buffer, and should not be copied into other buffers."
2262 (let ((string (if delete (delete-and-extract-region beg end)
2263 (buffer-substring beg end))))
2264 (dolist (filter buffer-substring-filters string)
2265 (setq string (funcall filter string))))))
2267 ;;;; Window system cut and paste hooks.
2269 (defvar interprogram-cut-function nil
2270 "Function to call to make a killed region available to other programs.
2272 Most window systems provide some sort of facility for cutting and
2273 pasting text between the windows of different programs.
2274 This variable holds a function that Emacs calls whenever text
2275 is put in the kill ring, to make the new kill available to other
2278 The function takes one or two arguments.
2279 The first argument, TEXT, is a string containing
2280 the text which should be made available.
2281 The second, optional, argument PUSH, has the same meaning as the
2282 similar argument to `x-set-cut-buffer', which see.")
2284 (make-variable-frame-local 'interprogram-cut-function)
2286 (defvar interprogram-paste-function nil
2287 "Function to call to get text cut from other programs.
2289 Most window systems provide some sort of facility for cutting and
2290 pasting text between the windows of different programs.
2291 This variable holds a function that Emacs calls to obtain
2292 text that other programs have provided for pasting.
2294 The function should be called with no arguments. If the function
2295 returns nil, then no other program has provided such text, and the top
2296 of the Emacs kill ring should be used. If the function returns a
2297 string, then the caller of the function \(usually `current-kill')
2298 should put this string in the kill ring as the latest kill.
2300 Note that the function should return a string only if a program other
2301 than Emacs has provided a string for pasting; if Emacs provided the
2302 most recent string, the function should return nil. If it is
2303 difficult to tell whether Emacs or some other program provided the
2304 current string, it is probably good enough to return nil if the string
2305 is equal (according to `string=') to the last text Emacs provided.")
2307 (make-variable-frame-local 'interprogram-paste-function)
2311 ;;;; The kill ring data structure.
2313 (defvar kill-ring nil
2314 "List of killed text sequences.
2315 Since the kill ring is supposed to interact nicely with cut-and-paste
2316 facilities offered by window systems, use of this variable should
2317 interact nicely with `interprogram-cut-function' and
2318 `interprogram-paste-function'. The functions `kill-new',
2319 `kill-append', and `current-kill' are supposed to implement this
2320 interaction; you may want to use them instead of manipulating the kill
2323 (defcustom kill-ring-max 60
2324 "*Maximum length of kill ring before oldest elements are thrown away."
2328 (defvar kill-ring-yank-pointer nil
2329 "The tail of the kill ring whose car is the last thing yanked.")
2331 (defun kill-new (string &optional replace yank-handler)
2332 "Make STRING the latest kill in the kill ring.
2333 Set `kill-ring-yank-pointer' to point to it.
2334 If `interprogram-cut-function' is non-nil, apply it to STRING.
2335 Optional second argument REPLACE non-nil means that STRING will replace
2336 the front of the kill ring, rather than being added to the list.
2338 Optional third arguments YANK-HANDLER controls how the STRING is later
2339 inserted into a buffer; see `insert-for-yank' for details.
2340 When a yank handler is specified, STRING must be non-empty (the yank
2341 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2343 When the yank handler has a non-nil PARAM element, the original STRING
2344 argument is not used by `insert-for-yank'. However, since Lisp code
2345 may access and use elements from the kill-ring directly, the STRING
2346 argument should still be a \"useful\" string for such uses."
2347 (if (> (length string) 0)
2349 (put-text-property 0 (length string)
2350 'yank-handler yank-handler string))
2352 (signal 'args-out-of-range
2353 (list string "yank-handler specified for empty string"))))
2354 (if (fboundp 'menu-bar-update-yank-menu)
2355 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2356 (if (and replace kill-ring)
2357 (setcar kill-ring string)
2358 (setq kill-ring (cons string kill-ring))
2359 (if (> (length kill-ring) kill-ring-max)
2360 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2361 (setq kill-ring-yank-pointer kill-ring)
2362 (if interprogram-cut-function
2363 (funcall interprogram-cut-function string (not replace))))
2365 (defun kill-append (string before-p &optional yank-handler)
2366 "Append STRING to the end of the latest kill in the kill ring.
2367 If BEFORE-P is non-nil, prepend STRING to the kill.
2368 Optional third argument YANK-HANDLER, if non-nil, specifies the
2369 yank-handler text property to be set on the combined kill ring
2370 string. If the specified yank-handler arg differs from the
2371 yank-handler property of the latest kill string, this function
2372 adds the combined string to the kill ring as a new element,
2373 instead of replacing the last kill with it.
2374 If `interprogram-cut-function' is set, pass the resulting kill to it."
2375 (let* ((cur (car kill-ring)))
2376 (kill-new (if before-p (concat string cur) (concat cur string))
2377 (or (= (length cur) 0)
2378 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2381 (defun current-kill (n &optional do-not-move)
2382 "Rotate the yanking point by N places, and then return that kill.
2383 If N is zero, `interprogram-paste-function' is set, and calling it
2384 returns a string, then that string is added to the front of the
2385 kill ring and returned as the latest kill.
2386 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
2387 yanking point; just return the Nth kill forward."
2388 (let ((interprogram-paste (and (= n 0)
2389 interprogram-paste-function
2390 (funcall interprogram-paste-function))))
2391 (if interprogram-paste
2393 ;; Disable the interprogram cut function when we add the new
2394 ;; text to the kill ring, so Emacs doesn't try to own the
2395 ;; selection, with identical text.
2396 (let ((interprogram-cut-function nil))
2397 (kill-new interprogram-paste))
2399 (or kill-ring (error "Kill ring is empty"))
2400 (let ((ARGth-kill-element
2401 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2405 (setq kill-ring-yank-pointer ARGth-kill-element))
2406 (car ARGth-kill-element)))))
2410 ;;;; Commands for manipulating the kill ring.
2412 (defcustom kill-read-only-ok nil
2413 "*Non-nil means don't signal an error for killing read-only text."
2417 (put 'text-read-only 'error-conditions
2418 '(text-read-only buffer-read-only error))
2419 (put 'text-read-only 'error-message "Text is read-only")
2421 (defun kill-region (beg end &optional yank-handler)
2422 "Kill between point and mark.
2423 The text is deleted but saved in the kill ring.
2424 The command \\[yank] can retrieve it from there.
2425 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2427 If you want to append the killed region to the last killed text,
2428 use \\[append-next-kill] before \\[kill-region].
2430 If the buffer is read-only, Emacs will beep and refrain from deleting
2431 the text, but put the text in the kill ring anyway. This means that
2432 you can use the killing commands to copy text from a read-only buffer.
2434 This is the primitive for programs to kill text (as opposed to deleting it).
2435 Supply two arguments, character positions indicating the stretch of text
2437 Any command that calls this function is a \"kill command\".
2438 If the previous command was also a kill command,
2439 the text killed this time appends to the text killed last time
2440 to make one entry in the kill ring.
2442 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2443 specifies the yank-handler text property to be set on the killed
2444 text. See `insert-for-yank'."
2447 (let ((string (filter-buffer-substring beg end t)))
2448 (when string ;STRING is nil if BEG = END
2449 ;; Add that string to the kill ring, one way or another.
2450 (if (eq last-command 'kill-region)
2451 (kill-append string (< end beg) yank-handler)
2452 (kill-new string nil yank-handler)))
2453 (when (or string (eq last-command 'kill-region))
2454 (setq this-command 'kill-region))
2456 ((buffer-read-only text-read-only)
2457 ;; The code above failed because the buffer, or some of the characters
2458 ;; in the region, are read-only.
2459 ;; We should beep, in case the user just isn't aware of this.
2460 ;; However, there's no harm in putting
2461 ;; the region's text in the kill ring, anyway.
2462 (copy-region-as-kill beg end)
2463 ;; Set this-command now, so it will be set even if we get an error.
2464 (setq this-command 'kill-region)
2465 ;; This should barf, if appropriate, and give us the correct error.
2466 (if kill-read-only-ok
2467 (progn (message "Read only text copied to kill ring") nil)
2468 ;; Signal an error if the buffer is read-only.
2469 (barf-if-buffer-read-only)
2470 ;; If the buffer isn't read-only, the text is.
2471 (signal 'text-read-only (list (current-buffer)))))))
2473 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2474 ;; to get two copies of the text when the user accidentally types M-w and
2475 ;; then corrects it with the intended C-w.
2476 (defun copy-region-as-kill (beg end)
2477 "Save the region as if killed, but don't kill it.
2478 In Transient Mark mode, deactivate the mark.
2479 If `interprogram-cut-function' is non-nil, also save the text for a window
2480 system cut and paste."
2482 (if (eq last-command 'kill-region)
2483 (kill-append (filter-buffer-substring beg end) (< end beg))
2484 (kill-new (filter-buffer-substring beg end)))
2485 (if transient-mark-mode
2486 (setq deactivate-mark t))
2489 (defun kill-ring-save (beg end)
2490 "Save the region as if killed, but don't kill it.
2491 In Transient Mark mode, deactivate the mark.
2492 If `interprogram-cut-function' is non-nil, also save the text for a window
2493 system cut and paste.
2495 If you want to append the killed line to the last killed text,
2496 use \\[append-next-kill] before \\[kill-ring-save].
2498 This command is similar to `copy-region-as-kill', except that it gives
2499 visual feedback indicating the extent of the region being copied."
2501 (copy-region-as-kill beg end)
2502 ;; This use of interactive-p is correct
2503 ;; because the code it controls just gives the user visual feedback.
2505 (let ((other-end (if (= (point) beg) end beg))
2507 ;; Inhibit quitting so we can make a quit here
2508 ;; look like a C-g typed as a command.
2510 (if (pos-visible-in-window-p other-end (selected-window))
2511 (unless (and transient-mark-mode
2512 (face-background 'region))
2513 ;; Swap point and mark.
2514 (set-marker (mark-marker) (point) (current-buffer))
2515 (goto-char other-end)
2516 (sit-for blink-matching-delay)
2518 (set-marker (mark-marker) other-end (current-buffer))
2520 ;; If user quit, deactivate the mark
2521 ;; as C-g would as a command.
2522 (and quit-flag mark-active
2524 (let* ((killed-text (current-kill 0))
2525 (message-len (min (length killed-text) 40)))
2527 ;; Don't say "killed"; that is misleading.
2528 (message "Saved text until \"%s\""
2529 (substring killed-text (- message-len)))
2530 (message "Saved text from \"%s\""
2531 (substring killed-text 0 message-len))))))))
2533 (defun append-next-kill (&optional interactive)
2534 "Cause following command, if it kills, to append to previous kill.
2535 The argument is used for internal purposes; do not supply one."
2537 ;; We don't use (interactive-p), since that breaks kbd macros.
2540 (setq this-command 'kill-region)
2541 (message "If the next command is a kill, it will append"))
2542 (setq last-command 'kill-region)))
2546 ;; This is actually used in subr.el but defcustom does not work there.
2547 (defcustom yank-excluded-properties
2548 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2549 yank-handler follow-link)
2550 "*Text properties to discard when yanking.
2551 The value should be a list of text properties to discard or t,
2552 which means to discard all text properties."
2553 :type '(choice (const :tag "All" t) (repeat symbol))
2557 (defvar yank-window-start nil)
2558 (defvar yank-undo-function nil
2559 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2560 Function is called with two parameters, START and END corresponding to
2561 the value of the mark and point; it is guaranteed that START <= END.
2562 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2564 (defun yank-pop (&optional arg)
2565 "Replace just-yanked stretch of killed text with a different stretch.
2566 This command is allowed only immediately after a `yank' or a `yank-pop'.
2567 At such a time, the region contains a stretch of reinserted
2568 previously-killed text. `yank-pop' deletes that text and inserts in its
2569 place a different stretch of killed text.
2571 With no argument, the previous kill is inserted.
2572 With argument N, insert the Nth previous kill.
2573 If N is negative, this is a more recent kill.
2575 The sequence of kills wraps around, so that after the oldest one
2576 comes the newest one.
2578 When this command inserts killed text into the buffer, it honors
2579 `yank-excluded-properties' and `yank-handler' as described in the
2580 doc string for `insert-for-yank-1', which see."
2582 (if (not (eq last-command 'yank))
2583 (error "Previous command was not a yank"))
2584 (setq this-command 'yank)
2585 (unless arg (setq arg 1))
2586 (let ((inhibit-read-only t)
2587 (before (< (point) (mark t))))
2589 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2590 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2591 (setq yank-undo-function nil)
2592 (set-marker (mark-marker) (point) (current-buffer))
2593 (insert-for-yank (current-kill arg))
2594 ;; Set the window start back where it was in the yank command,
2596 (set-window-start (selected-window) yank-window-start t)
2598 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2599 ;; It is cleaner to avoid activation, even though the command
2600 ;; loop would deactivate the mark because we inserted text.
2601 (goto-char (prog1 (mark t)
2602 (set-marker (mark-marker) (point) (current-buffer))))))
2605 (defun yank (&optional arg)
2606 "Reinsert the last stretch of killed text.
2607 More precisely, reinsert the stretch of killed text most recently
2608 killed OR yanked. Put point at end, and set mark at beginning.
2609 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2610 With argument N, reinsert the Nth most recently killed stretch of killed
2613 When this command inserts killed text into the buffer, it honors
2614 `yank-excluded-properties' and `yank-handler' as described in the
2615 doc string for `insert-for-yank-1', which see.
2617 See also the command \\[yank-pop]."
2619 (setq yank-window-start (window-start))
2620 ;; If we don't get all the way thru, make last-command indicate that
2621 ;; for the following command.
2622 (setq this-command t)
2624 (insert-for-yank (current-kill (cond
2629 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2630 ;; It is cleaner to avoid activation, even though the command
2631 ;; loop would deactivate the mark because we inserted text.
2632 (goto-char (prog1 (mark t)
2633 (set-marker (mark-marker) (point) (current-buffer)))))
2634 ;; If we do get all the way thru, make this-command indicate that.
2635 (if (eq this-command t)
2636 (setq this-command 'yank))
2639 (defun rotate-yank-pointer (arg)
2640 "Rotate the yanking point in the kill ring.
2641 With argument, rotate that many kills forward (or backward, if negative)."
2645 ;; Some kill commands.
2647 ;; Internal subroutine of delete-char
2648 (defun kill-forward-chars (arg)
2649 (if (listp arg) (setq arg (car arg)))
2650 (if (eq arg '-) (setq arg -1))
2651 (kill-region (point) (forward-point arg)))
2653 ;; Internal subroutine of backward-delete-char
2654 (defun kill-backward-chars (arg)
2655 (if (listp arg) (setq arg (car arg)))
2656 (if (eq arg '-) (setq arg -1))
2657 (kill-region (point) (forward-point (- arg))))
2659 (defcustom backward-delete-char-untabify-method 'untabify
2660 "*The method for untabifying when deleting backward.
2661 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2662 `hungry' -- delete all whitespace, both tabs and spaces;
2663 `all' -- delete all whitespace, including tabs, spaces and newlines;
2664 nil -- just delete one character."
2665 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2669 (defun backward-delete-char-untabify (arg &optional killp)
2670 "Delete characters backward, changing tabs into spaces.
2671 The exact behavior depends on `backward-delete-char-untabify-method'.
2672 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2673 Interactively, ARG is the prefix arg (default 1)
2674 and KILLP is t if a prefix arg was specified."
2675 (interactive "*p\nP")
2676 (when (eq backward-delete-char-untabify-method 'untabify)
2679 (while (and (> count 0) (not (bobp)))
2680 (if (= (preceding-char) ?\t)
2681 (let ((col (current-column)))
2683 (setq col (- col (current-column)))
2684 (insert-char ?\ col)
2687 (setq count (1- count))))))
2688 (delete-backward-char
2689 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2690 ((eq backward-delete-char-untabify-method 'all)
2693 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2695 (+ arg (if (zerop wh) 0 (1- wh))))
2699 (defun zap-to-char (arg char)
2700 "Kill up to and including ARG'th occurrence of CHAR.
2701 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2702 Goes backward if ARG is negative; error if CHAR not found."
2703 (interactive "p\ncZap to char: ")
2704 (kill-region (point) (progn
2705 (search-forward (char-to-string char) nil nil arg)
2706 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2709 ;; kill-line and its subroutines.
2711 (defcustom kill-whole-line nil
2712 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2716 (defun kill-line (&optional arg)
2717 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2718 With prefix argument, kill that many lines from point.
2719 Negative arguments kill lines backward.
2720 With zero argument, kills the text before point on the current line.
2722 When calling from a program, nil means \"no arg\",
2723 a number counts as a prefix arg.
2725 To kill a whole line, when point is not at the beginning, type \
2726 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2728 If `kill-whole-line' is non-nil, then this command kills the whole line
2729 including its terminating newline, when used at the beginning of a line
2730 with no argument. As a consequence, you can always kill a whole line
2731 by typing \\[beginning-of-line] \\[kill-line].
2733 If you want to append the killed line to the last killed text,
2734 use \\[append-next-kill] before \\[kill-line].
2736 If the buffer is read-only, Emacs will beep and refrain from deleting
2737 the line, but put the line in the kill ring anyway. This means that
2738 you can use this command to copy text from a read-only buffer.
2739 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2742 (kill-region (point)
2743 ;; It is better to move point to the other end of the kill
2744 ;; before killing. That way, in a read-only buffer, point
2745 ;; moves across the text that is copied to the kill ring.
2746 ;; The choice has no effect on undo now that undo records
2747 ;; the value of point from before the command was run.
2750 (forward-visible-line (prefix-numeric-value arg))
2752 (signal 'end-of-buffer nil))
2755 (end-of-visible-line) (point))))
2756 (if (or (save-excursion
2757 ;; If trailing whitespace is visible,
2758 ;; don't treat it as nothing.
2759 (unless show-trailing-whitespace
2760 (skip-chars-forward " \t" end))
2762 (and kill-whole-line (bolp)))
2763 (forward-visible-line 1)
2767 (defun kill-whole-line (&optional arg)
2769 With prefix arg, kill that many lines starting from the current line.
2770 If arg is negative, kill backward. Also kill the preceding newline.
2771 \(This is meant to make \\[repeat] work well with negative arguments.\)
2772 If arg is zero, kill current line but exclude the trailing newline."
2774 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2775 (signal 'end-of-buffer nil))
2776 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2777 (signal 'beginning-of-buffer nil))
2778 (unless (eq last-command 'kill-region)
2780 (setq last-command 'kill-region))
2782 ;; We need to kill in two steps, because the previous command
2783 ;; could have been a kill command, in which case the text
2784 ;; before point needs to be prepended to the current kill
2785 ;; ring entry and the text after point appended. Also, we
2786 ;; need to use save-excursion to avoid copying the same text
2787 ;; twice to the kill ring in read-only buffers.
2789 (kill-region (point) (progn (forward-visible-line 0) (point))))
2790 (kill-region (point) (progn (end-of-visible-line) (point))))
2793 (kill-region (point) (progn (end-of-visible-line) (point))))
2794 (kill-region (point)
2795 (progn (forward-visible-line (1+ arg))
2796 (unless (bobp) (backward-char))
2800 (kill-region (point) (progn (forward-visible-line 0) (point))))
2801 (kill-region (point)
2802 (progn (forward-visible-line arg) (point))))))
2804 (defun forward-visible-line (arg)
2805 "Move forward by ARG lines, ignoring currently invisible newlines only.
2806 If ARG is negative, move backward -ARG lines.
2807 If ARG is zero, move to the beginning of the current line."
2812 (or (zerop (forward-line 1))
2813 (signal 'end-of-buffer nil))
2814 ;; If the newline we just skipped is invisible,
2817 (get-char-property (1- (point)) 'invisible)))
2818 (if (if (eq buffer-invisibility-spec t)
2820 (or (memq prop buffer-invisibility-spec)
2821 (assq prop buffer-invisibility-spec)))
2822 (setq arg (1+ arg))))
2823 (setq arg (1- arg)))
2824 ;; If invisible text follows, and it is a number of complete lines,
2826 (let ((opoint (point)))
2827 (while (and (not (eobp))
2829 (get-char-property (point) 'invisible)))
2830 (if (eq buffer-invisibility-spec t)
2832 (or (memq prop buffer-invisibility-spec)
2833 (assq prop buffer-invisibility-spec)))))
2835 (if (get-text-property (point) 'invisible)
2836 (or (next-single-property-change (point) 'invisible)
2838 (next-overlay-change (point)))))
2840 (goto-char opoint))))
2842 (while (or first (<= arg 0))
2845 (or (zerop (forward-line -1))
2846 (signal 'beginning-of-buffer nil)))
2847 ;; If the newline we just moved to is invisible,
2851 (get-char-property (1- (point)) 'invisible)))
2852 (unless (if (eq buffer-invisibility-spec t)
2854 (or (memq prop buffer-invisibility-spec)
2855 (assq prop buffer-invisibility-spec)))
2856 (setq arg (1+ arg)))))
2858 ;; If invisible text follows, and it is a number of complete lines,
2860 (let ((opoint (point)))
2861 (while (and (not (bobp))
2863 (get-char-property (1- (point)) 'invisible)))
2864 (if (eq buffer-invisibility-spec t)
2866 (or (memq prop buffer-invisibility-spec)
2867 (assq prop buffer-invisibility-spec)))))
2869 (if (get-text-property (1- (point)) 'invisible)
2870 (or (previous-single-property-change (point) 'invisible)
2872 (previous-overlay-change (point)))))
2874 (goto-char opoint)))))
2875 ((beginning-of-buffer end-of-buffer)
2878 (defun end-of-visible-line ()
2879 "Move to end of current visible line."
2881 ;; If the following character is currently invisible,
2882 ;; skip all characters with that same `invisible' property value,
2883 ;; then find the next newline.
2884 (while (and (not (eobp))
2886 (skip-chars-forward "^\n")
2888 (get-char-property (point) 'invisible)))
2889 (if (eq buffer-invisibility-spec t)
2891 (or (memq prop buffer-invisibility-spec)
2892 (assq prop buffer-invisibility-spec))))))
2893 (skip-chars-forward "^\n")
2894 (if (get-text-property (point) 'invisible)
2895 (goto-char (next-single-property-change (point) 'invisible))
2896 (goto-char (next-overlay-change (point))))
2899 (defun insert-buffer (buffer)
2900 "Insert after point the contents of BUFFER.
2901 Puts mark after the inserted text.
2902 BUFFER may be a buffer or a buffer name.
2904 This function is meant for the user to run interactively.
2905 Don't call it from programs: use `insert-buffer-substring' instead!"
2909 (barf-if-buffer-read-only)
2910 (read-buffer "Insert buffer: "
2911 (if (eq (selected-window) (next-window (selected-window)))
2912 (other-buffer (current-buffer))
2913 (window-buffer (next-window (selected-window))))
2917 (insert-buffer-substring (get-buffer buffer))
2921 (defun append-to-buffer (buffer start end)
2922 "Append to specified buffer the text of the region.
2923 It is inserted into that buffer before its point.
2925 When calling from a program, give three arguments:
2926 BUFFER (or buffer name), START and END.
2927 START and END specify the portion of the current buffer to be copied."
2929 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
2930 (region-beginning) (region-end)))
2931 (let ((oldbuf (current-buffer)))
2933 (let* ((append-to (get-buffer-create buffer))
2934 (windows (get-buffer-window-list append-to t t))
2936 (set-buffer append-to)
2937 (setq point (point))
2938 (barf-if-buffer-read-only)
2939 (insert-buffer-substring oldbuf start end)
2940 (dolist (window windows)
2941 (when (= (window-point window) point)
2942 (set-window-point window (point))))))))
2944 (defun prepend-to-buffer (buffer start end)
2945 "Prepend to specified buffer the text of the region.
2946 It is inserted into that buffer after its point.
2948 When calling from a program, give three arguments:
2949 BUFFER (or buffer name), START and END.
2950 START and END specify the portion of the current buffer to be copied."
2951 (interactive "BPrepend to buffer: \nr")
2952 (let ((oldbuf (current-buffer)))
2954 (set-buffer (get-buffer-create buffer))
2955 (barf-if-buffer-read-only)
2957 (insert-buffer-substring oldbuf start end)))))
2959 (defun copy-to-buffer (buffer start end)
2960 "Copy to specified buffer the text of the region.
2961 It is inserted into that buffer, replacing existing text there.
2963 When calling from a program, give three arguments:
2964 BUFFER (or buffer name), START and END.
2965 START and END specify the portion of the current buffer to be copied."
2966 (interactive "BCopy to buffer: \nr")
2967 (let ((oldbuf (current-buffer)))
2969 (set-buffer (get-buffer-create buffer))
2970 (barf-if-buffer-read-only)
2973 (insert-buffer-substring oldbuf start end)))))
2975 (put 'mark-inactive 'error-conditions '(mark-inactive error))
2976 (put 'mark-inactive 'error-message "The mark is not active now")
2978 (defvar activate-mark-hook nil
2979 "Hook run when the mark becomes active.
2980 It is also run at the end of a command, if the mark is active and
2981 it is possible that the region may have changed")
2983 (defvar deactivate-mark-hook nil
2984 "Hook run when the mark becomes inactive.")
2986 (defun mark (&optional force)
2987 "Return this buffer's mark value as integer; error if mark inactive.
2988 If optional argument FORCE is non-nil, access the mark value
2989 even if the mark is not currently active, and return nil
2990 if there is no mark at all.
2992 If you are using this in an editing command, you are most likely making
2993 a mistake; see the documentation of `set-mark'."
2994 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
2995 (marker-position (mark-marker))
2996 (signal 'mark-inactive nil)))
2998 ;; Many places set mark-active directly, and several of them failed to also
2999 ;; run deactivate-mark-hook. This shorthand should simplify.
3000 (defsubst deactivate-mark ()
3001 "Deactivate the mark by setting `mark-active' to nil.
3002 \(That makes a difference only in Transient Mark mode.)
3003 Also runs the hook `deactivate-mark-hook'."
3005 ((eq transient-mark-mode 'lambda)
3006 (setq transient-mark-mode nil))
3007 (transient-mark-mode
3008 (setq mark-active nil)
3009 (run-hooks 'deactivate-mark-hook))))
3011 (defun set-mark (pos)
3012 "Set this buffer's mark to POS. Don't use this function!
3013 That is to say, don't use this function unless you want
3014 the user to see that the mark has moved, and you want the previous
3015 mark position to be lost.
3017 Normally, when a new mark is set, the old one should go on the stack.
3018 This is why most applications should use `push-mark', not `set-mark'.
3020 Novice Emacs Lisp programmers often try to use the mark for the wrong
3021 purposes. The mark saves a location for the user's convenience.
3022 Most editing commands should not alter the mark.
3023 To remember a location for internal use in the Lisp program,
3024 store it in a Lisp variable. Example:
3026 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3030 (setq mark-active t)
3031 (run-hooks 'activate-mark-hook)
3032 (set-marker (mark-marker) pos (current-buffer)))
3033 ;; Normally we never clear mark-active except in Transient Mark mode.
3034 ;; But when we actually clear out the mark value too,
3035 ;; we must clear mark-active in any mode.
3036 (setq mark-active nil)
3037 (run-hooks 'deactivate-mark-hook)
3038 (set-marker (mark-marker) nil)))
3040 (defvar mark-ring nil
3041 "The list of former marks of the current buffer, most recent first.")
3042 (make-variable-buffer-local 'mark-ring)
3043 (put 'mark-ring 'permanent-local t)
3045 (defcustom mark-ring-max 16
3046 "*Maximum size of mark ring. Start discarding off end if gets this big."
3048 :group 'editing-basics)
3050 (defvar global-mark-ring nil
3051 "The list of saved global marks, most recent first.")
3053 (defcustom global-mark-ring-max 16
3054 "*Maximum size of global mark ring. \
3055 Start discarding off end if gets this big."
3057 :group 'editing-basics)
3059 (defun pop-to-mark-command ()
3060 "Jump to mark, and pop a new position for mark off the ring
3061 \(does not affect global mark ring\)."
3064 (error "No mark set in this buffer")
3065 (goto-char (mark t))
3068 (defun push-mark-command (arg &optional nomsg)
3069 "Set mark at where point is.
3070 If no prefix arg and mark is already set there, just activate it.
3071 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3073 (let ((mark (marker-position (mark-marker))))
3074 (if (or arg (null mark) (/= mark (point)))
3075 (push-mark nil nomsg t)
3076 (setq mark-active t)
3077 (run-hooks 'activate-mark-hook)
3079 (message "Mark activated")))))
3081 (defun set-mark-command (arg)
3082 "Set mark at where point is, or jump to mark.
3083 With no prefix argument, set mark, and push old mark position on local
3084 mark ring; also push mark on global mark ring if last mark was set in
3085 another buffer. Immediately repeating the command activates
3086 `transient-mark-mode' temporarily.
3088 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
3089 jump to mark, and pop a new position
3090 for mark off the local mark ring \(this does not affect the global
3091 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
3092 mark ring \(see `pop-global-mark'\).
3094 Repeating the \\[set-mark-command] command without the prefix jumps to
3095 the next position off the local (or global) mark ring.
3097 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
3098 \\[universal-argument] \\[set-mark-command], unconditionally
3099 set mark where point is.
3101 Novice Emacs Lisp programmers often try to use the mark for the wrong
3102 purposes. See the documentation of `set-mark' for more information."
3104 (if (eq transient-mark-mode 'lambda)
3105 (setq transient-mark-mode nil))
3107 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3108 (push-mark-command nil))
3109 ((not (eq this-command 'set-mark-command))
3111 (pop-to-mark-command)
3112 (push-mark-command t)))
3113 ((eq last-command 'pop-to-mark-command)
3114 (setq this-command 'pop-to-mark-command)
3115 (pop-to-mark-command))
3116 ((and (eq last-command 'pop-global-mark) (not arg))
3117 (setq this-command 'pop-global-mark)
3120 (setq this-command 'pop-to-mark-command)
3121 (pop-to-mark-command))
3122 ((and (eq last-command 'set-mark-command)
3123 mark-active (null transient-mark-mode))
3124 (setq transient-mark-mode 'lambda)
3125 (message "Transient-mark-mode temporarily enabled"))
3127 (push-mark-command nil))))
3129 (defun push-mark (&optional location nomsg activate)
3130 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3131 If the last global mark pushed was not in the current buffer,
3132 also push LOCATION on the global mark ring.
3133 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3134 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
3136 Novice Emacs Lisp programmers often try to use the mark for the wrong
3137 purposes. See the documentation of `set-mark' for more information.
3139 In Transient Mark mode, this does not activate the mark."
3140 (unless (null (mark t))
3141 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3142 (when (> (length mark-ring) mark-ring-max)
3143 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3144 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3145 (set-marker (mark-marker) (or location (point)) (current-buffer))
3146 ;; Now push the mark on the global mark ring.
3147 (if (and global-mark-ring
3148 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3149 ;; The last global mark pushed was in this same buffer.
3150 ;; Don't push another one.
3152 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3153 (when (> (length global-mark-ring) global-mark-ring-max)
3154 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3155 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3156 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3157 (message "Mark set"))
3158 (if (or activate (not transient-mark-mode))
3159 (set-mark (mark t)))
3163 "Pop off mark ring into the buffer's actual mark.
3164 Does not set point. Does nothing if mark ring is empty."
3166 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3167 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3168 (move-marker (car mark-ring) nil)
3169 (if (null (mark t)) (ding))
3170 (setq mark-ring (cdr mark-ring)))
3173 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3174 (defun exchange-point-and-mark (&optional arg)
3175 "Put the mark where point is now, and point where the mark is now.
3176 This command works even when the mark is not active,
3177 and it reactivates the mark.
3178 With prefix arg, `transient-mark-mode' is enabled temporarily."
3182 (if (null transient-mark-mode)
3183 (setq transient-mark-mode 'lambda))
3186 (let ((omark (mark t)))
3188 (error "No mark set in this buffer"))
3193 (define-minor-mode transient-mark-mode
3194 "Toggle Transient Mark mode.
3195 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
3197 In Transient Mark mode, when the mark is active, the region is highlighted.
3198 Changing the buffer \"deactivates\" the mark.
3199 So do certain other operations that set the mark
3200 but whose main purpose is something else--for example,
3201 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3203 You can also deactivate the mark by typing \\[keyboard-quit] or
3204 \\[keyboard-escape-quit].
3206 Many commands change their behavior when Transient Mark mode is in effect
3207 and the mark is active, by acting on the region instead of their usual
3208 default part of the buffer's text. Examples of such commands include
3209 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3210 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3211 Invoke \\[apropos-documentation] and type \"transient\" or
3212 \"mark.*active\" at the prompt, to see the documentation of
3213 commands which are sensitive to the Transient Mark mode."
3214 :global t :group 'editing-basics :require nil)
3216 (defvar widen-automatically t
3217 "Non-nil means it is ok for commands to call `widen' when they want to.
3218 Some commands will do this in order to go to positions outside
3219 the current accessible part of the buffer.
3221 If `widen-automatically' is nil, these commands will do something else
3222 as a fallback, and won't change the buffer bounds.")
3224 (defun pop-global-mark ()
3225 "Pop off global mark ring and jump to the top location."
3227 ;; Pop entries which refer to non-existent buffers.
3228 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3229 (setq global-mark-ring (cdr global-mark-ring)))
3230 (or global-mark-ring
3231 (error "No global mark set"))
3232 (let* ((marker (car global-mark-ring))
3233 (buffer (marker-buffer marker))
3234 (position (marker-position marker)))
3235 (setq global-mark-ring (nconc (cdr global-mark-ring)
3236 (list (car global-mark-ring))))
3238 (or (and (>= position (point-min))
3239 (<= position (point-max)))
3240 (if widen-automatically
3241 (error "Global mark position is outside accessible part of buffer")
3243 (goto-char position)
3244 (switch-to-buffer buffer)))
3246 (defcustom next-line-add-newlines nil
3247 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3250 :group 'editing-basics)
3252 (defun next-line (&optional arg try-vscroll)
3253 "Move cursor vertically down ARG lines.
3254 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3255 If there is no character in the target line exactly under the current column,
3256 the cursor is positioned after the character in that line which spans this
3257 column, or at the end of the line if it is not long enough.
3258 If there is no line in the buffer after this one, behavior depends on the
3259 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3260 to create a line, and moves the cursor to that line. Otherwise it moves the
3261 cursor to the end of the buffer.
3263 The command \\[set-goal-column] can be used to create
3264 a semipermanent goal column for this command.
3265 Then instead of trying to move exactly vertically (or as close as possible),
3266 this command moves to the specified goal column (or as close as possible).
3267 The goal column is stored in the variable `goal-column', which is nil
3268 when there is no goal column.
3270 If you are thinking of using this in a Lisp program, consider
3271 using `forward-line' instead. It is usually easier to use
3272 and more reliable (no dependence on goal column, etc.)."
3273 (interactive "p\np")
3274 (or arg (setq arg 1))
3275 (if (and next-line-add-newlines (= arg 1))
3276 (if (save-excursion (end-of-line) (eobp))
3277 ;; When adding a newline, don't expand an abbrev.
3278 (let ((abbrev-mode nil))
3281 (line-move arg nil nil try-vscroll))
3284 (line-move arg nil nil try-vscroll)
3285 ((beginning-of-buffer end-of-buffer) (ding)))
3286 (line-move arg nil nil try-vscroll)))
3289 (defun previous-line (&optional arg try-vscroll)
3290 "Move cursor vertically up ARG lines.
3291 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3292 If there is no character in the target line exactly over the current column,
3293 the cursor is positioned after the character in that line which spans this
3294 column, or at the end of the line if it is not long enough.
3296 The command \\[set-goal-column] can be used to create
3297 a semipermanent goal column for this command.
3298 Then instead of trying to move exactly vertically (or as close as possible),
3299 this command moves to the specified goal column (or as close as possible).
3300 The goal column is stored in the variable `goal-column', which is nil
3301 when there is no goal column.
3303 If you are thinking of using this in a Lisp program, consider using
3304 `forward-line' with a negative argument instead. It is usually easier
3305 to use and more reliable (no dependence on goal column, etc.)."
3306 (interactive "p\np")
3307 (or arg (setq arg 1))
3310 (line-move (- arg) nil nil try-vscroll)
3311 ((beginning-of-buffer end-of-buffer) (ding)))
3312 (line-move (- arg) nil nil try-vscroll))
3315 (defcustom track-eol nil
3316 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
3317 This means moving to the end of each line moved onto.
3318 The beginning of a blank line does not count as the end of a line."
3320 :group 'editing-basics)
3322 (defcustom goal-column nil
3323 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3324 :type '(choice integer
3325 (const :tag "None" nil))
3326 :group 'editing-basics)
3327 (make-variable-buffer-local 'goal-column)
3329 (defvar temporary-goal-column 0
3330 "Current goal column for vertical motion.
3331 It is the column where point was
3332 at the start of current run of vertical motion commands.
3333 When the `track-eol' feature is doing its job, the value is 9999.")
3335 (defcustom line-move-ignore-invisible t
3336 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3337 Outline mode sets this."
3339 :group 'editing-basics)
3341 (defun line-move-invisible-p (pos)
3342 "Return non-nil if the character after POS is currently invisible."
3344 (get-char-property pos 'invisible)))
3345 (if (eq buffer-invisibility-spec t)
3347 (or (memq prop buffer-invisibility-spec)
3348 (assq prop buffer-invisibility-spec)))))
3350 ;; This is like line-move-1 except that it also performs
3351 ;; vertical scrolling of tall images if appropriate.
3352 ;; That is not really a clean thing to do, since it mixes
3353 ;; scrolling with cursor motion. But so far we don't have
3354 ;; a cleaner solution to the problem of making C-n do something
3355 ;; useful given a tall image.
3356 (defun line-move (arg &optional noerror to-end try-vscroll)
3357 (if (and auto-window-vscroll try-vscroll
3358 ;; But don't vscroll in a keyboard macro.
3359 (not defining-kbd-macro)
3360 (not executing-kbd-macro))
3361 (let ((forward (> arg 0))
3362 (part (nth 2 (pos-visible-in-window-p (point) nil t))))
3363 (if (and (consp part)
3364 (> (if forward (cdr part) (car part)) 0))
3365 (set-window-vscroll nil
3367 (+ (window-vscroll nil t)
3369 (* (frame-char-height) arg)))
3371 (- (window-vscroll nil t)
3373 (* (frame-char-height) (- arg))))))
3375 (set-window-vscroll nil 0)
3376 (when (line-move-1 arg noerror to-end)
3378 ;; Update display before calling pos-visible-in-window-p,
3379 ;; because it depends on window-start being up-to-date.
3381 ;; If the current line is partly hidden at the bottom,
3382 ;; scroll it partially up so as to unhide the bottom.
3383 (if (and (setq part (nth 2 (pos-visible-in-window-p
3384 (line-beginning-position) nil t)))
3386 (set-window-vscroll nil (cdr part) t)))
3388 (line-move-1 arg noerror to-end)))
3390 ;; This is the guts of next-line and previous-line.
3391 ;; Arg says how many lines to move.
3392 ;; The value is t if we can move the specified number of lines.
3393 (defun line-move-1 (arg &optional noerror to-end)
3394 ;; Don't run any point-motion hooks, and disregard intangibility,
3395 ;; for intermediate positions.
3396 (let ((inhibit-point-motion-hooks t)
3398 (forward (> arg 0)))
3401 (if (not (memq last-command '(next-line previous-line)))
3402 (setq temporary-goal-column
3403 (if (and track-eol (eolp)
3404 ;; Don't count beg of empty line as end of line
3405 ;; unless we just did explicit end-of-line.
3406 (or (not (bolp)) (eq last-command 'end-of-line)))
3410 (if (and (not (integerp selective-display))
3411 (not line-move-ignore-invisible))
3412 ;; Use just newline characters.
3413 ;; Set ARG to 0 if we move as many lines as requested.
3415 (progn (if (> arg 1) (forward-line (1- arg)))
3416 ;; This way of moving forward ARG lines
3417 ;; verifies that we have a newline after the last one.
3418 ;; It doesn't get confused by intangible text.
3420 (if (zerop (forward-line 1))
3422 (and (zerop (forward-line arg))
3426 (signal (if (< arg 0)
3427 'beginning-of-buffer
3430 ;; Move by arg lines, but ignore invisible ones.
3432 (while (and (> arg 0) (not done))
3433 ;; If the following character is currently invisible,
3434 ;; skip all characters with that same `invisible' property value.
3435 (while (and (not (eobp)) (line-move-invisible-p (point)))
3436 (goto-char (next-char-property-change (point))))
3439 ;; If there's no invisibility here, move over the newline.
3440 (let ((pos-before (point))
3444 (signal 'end-of-buffer nil)
3446 (when (and (not done)
3447 (not (integerp selective-display))
3448 (not (line-move-invisible-p (point))))
3449 (unless (overlays-in (max (1- pos-before) (point-min))
3450 (min (1+ (point)) (point-max)))
3451 ;; We avoid vertical-motion when possible
3452 ;; because that has to fontify.
3454 (setq line-done t)))
3455 (and (not done) (not line-done)
3456 ;; Otherwise move a more sophisticated way.
3457 (zerop (vertical-motion 1))
3459 (signal 'end-of-buffer nil)
3462 (setq arg (1- arg))))
3463 ;; The logic of this is the same as the loop above,
3464 ;; it just goes in the other direction.
3465 (while (and (< arg 0) (not done))
3467 (let ((pos-before (point))
3471 (signal 'beginning-of-buffer nil)
3473 (when (and (not done)
3474 (not (integerp selective-display))
3475 (not (line-move-invisible-p (1- (point)))))
3476 (unless (overlays-in (max (1- (point)) (point-min))
3477 (min (1+ pos-before) (point-max)))
3479 (setq line-done t)))
3480 (and (not done) (not line-done)
3481 (zerop (vertical-motion -1))
3483 (signal 'beginning-of-buffer nil)
3487 (while (and ;; Don't move over previous invis lines
3488 ;; if our target is the middle of this line.
3489 (or (zerop (or goal-column temporary-goal-column))
3491 (not (bobp)) (line-move-invisible-p (1- (point))))
3492 (goto-char (previous-char-property-change (point))))))))
3493 ;; This is the value the function returns.
3497 ;; If we did not move down as far as desired,
3498 ;; at least go to end of line.
3501 ;; If we did not move down as far as desired,
3502 ;; at least go to end of line.
3503 (beginning-of-line))
3505 (line-move-finish (or goal-column temporary-goal-column)
3506 opoint forward))))))
3508 (defun line-move-finish (column opoint forward)
3511 ;; Set REPEAT to t to repeat the whole thing.
3515 (line-beg (save-excursion (beginning-of-line) (point)))
3517 ;; Compute the end of the line
3518 ;; ignoring effectively invisible newlines.
3521 (while (and (not (eobp)) (line-move-invisible-p (point)))
3522 (goto-char (next-char-property-change (point)))
3526 ;; Move to the desired column.
3527 (line-move-to-column column)
3530 ;; Process intangibility within a line.
3531 ;; Move to the chosen destination position from above,
3532 ;; with intangibility processing enabled.
3534 (goto-char (point-min))
3535 (let ((inhibit-point-motion-hooks nil))
3538 ;; If intangibility moves us to a different (later) place
3539 ;; in the same line, use that as the destination.
3540 (if (<= (point) line-end)
3542 ;; If that position is "too late",
3543 ;; try the previous allowable position.
3547 ;; If going forward, don't accept the previous
3548 ;; allowable position if it is before the target line.
3549 (< line-beg (point))
3550 ;; If going backward, don't accept the previous
3551 ;; allowable position if it is still after the target line.
3552 (<= (point) line-end))
3554 ;; As a last resort, use the end of the line.
3555 (setq new line-end))))
3557 ;; Now move to the updated destination, processing fields
3558 ;; as well as intangibility.
3560 (let ((inhibit-point-motion-hooks nil))
3562 (constrain-to-field new opoint nil t
3563 'inhibit-line-move-field-capture)))
3565 ;; If all this moved us to a different line,
3566 ;; retry everything within that new line.
3567 (when (or (< (point) line-beg) (> (point) line-end))
3568 ;; Repeat the intangibility and field processing.
3569 (setq repeat t))))))
3571 (defun line-move-to-column (col)
3572 "Try to find column COL, considering invisibility.
3573 This function works only in certain cases,
3574 because what we really need is for `move-to-column'
3575 and `current-column' to be able to ignore invisible text."
3578 (move-to-column col))
3580 (when (and line-move-ignore-invisible
3581 (not (bolp)) (line-move-invisible-p (1- (point))))
3582 (let ((normal-location (point))
3583 (normal-column (current-column)))
3584 ;; If the following character is currently invisible,
3585 ;; skip all characters with that same `invisible' property value.
3586 (while (and (not (eobp))
3587 (line-move-invisible-p (point)))
3588 (goto-char (next-char-property-change (point))))
3589 ;; Have we advanced to a larger column position?
3590 (if (> (current-column) normal-column)
3591 ;; We have made some progress towards the desired column.
3592 ;; See if we can make any further progress.
3593 (line-move-to-column (+ (current-column) (- col normal-column)))
3594 ;; Otherwise, go to the place we originally found
3595 ;; and move back over invisible text.
3596 ;; that will get us to the same place on the screen
3597 ;; but with a more reasonable buffer position.
3598 (goto-char normal-location)
3599 (let ((line-beg (save-excursion (beginning-of-line) (point))))
3600 (while (and (not (bolp)) (line-move-invisible-p (1- (point))))
3601 (goto-char (previous-char-property-change (point) line-beg))))))))
3603 (defun move-end-of-line (arg)
3604 "Move point to end of current line.
3605 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3606 If point reaches the beginning or end of buffer, it stops there.
3607 To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3609 This command does not move point across a field boundary unless doing so
3610 would move beyond there to a different line; if ARG is nil or 1, and
3611 point starts at a field boundary, point does not move. To ignore field
3612 boundaries bind `inhibit-field-text-motion' to t."
3614 (or arg (setq arg 1))
3619 (let ((goal-column 0))
3620 (and (line-move arg t)
3623 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3624 (goto-char (previous-char-property-change (point))))
3628 (if (and (> (point) newpos)
3629 (eq (preceding-char) ?\n))
3631 (if (and (> (point) newpos) (not (eobp))
3632 (not (eq (following-char) ?\n)))
3633 ;; If we skipped something intangible
3634 ;; and now we're not really at eol,
3639 (defun move-beginning-of-line (arg)
3640 "Move point to beginning of current display line.
3641 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3642 If point reaches the beginning or end of buffer, it stops there.
3643 To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3645 This command does not move point across a field boundary unless doing so
3646 would move beyond there to a different line; if ARG is nil or 1, and
3647 point starts at a field boundary, point does not move. To ignore field
3648 boundaries bind `inhibit-field-text-motion' to t."
3650 (or arg (setq arg 1))
3652 (line-move (1- arg) t))
3653 (beginning-of-line 1)
3654 (let ((orig (point)))
3656 (if (/= orig (point))
3657 (goto-char (constrain-to-field (point) orig (/= arg 1) t nil)))))
3660 ;;; Many people have said they rarely use this feature, and often type
3661 ;;; it by accident. Maybe it shouldn't even be on a key.
3662 (put 'set-goal-column 'disabled t)
3664 (defun set-goal-column (arg)
3665 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3666 Those commands will move to this position in the line moved to
3667 rather than trying to keep the same horizontal position.
3668 With a non-nil argument, clears out the goal column
3669 so that \\[next-line] and \\[previous-line] resume vertical motion.
3670 The goal column is stored in the variable `goal-column'."
3674 (setq goal-column nil)
3675 (message "No goal column"))
3676 (setq goal-column (current-column))
3677 (message (substitute-command-keys
3678 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3683 (defun scroll-other-window-down (lines)
3684 "Scroll the \"other window\" down.
3685 For more details, see the documentation for `scroll-other-window'."
3687 (scroll-other-window
3688 ;; Just invert the argument's meaning.
3689 ;; We can do that without knowing which window it will be.
3690 (if (eq lines '-) nil
3692 (- (prefix-numeric-value lines))))))
3694 (defun beginning-of-buffer-other-window (arg)
3695 "Move point to the beginning of the buffer in the other window.
3696 Leave mark at previous position.
3697 With arg N, put point N/10 of the way from the true beginning."
3699 (let ((orig-window (selected-window))
3700 (window (other-window-for-scrolling)))
3701 ;; We use unwind-protect rather than save-window-excursion
3702 ;; because the latter would preserve the things we want to change.
3705 (select-window window)
3706 ;; Set point and mark in that window's buffer.
3708 (beginning-of-buffer arg))
3709 ;; Set point accordingly.
3711 (select-window orig-window))))
3713 (defun end-of-buffer-other-window (arg)
3714 "Move point to the end of the buffer in the other window.
3715 Leave mark at previous position.
3716 With arg N, put point N/10 of the way from the true end."
3718 ;; See beginning-of-buffer-other-window for comments.
3719 (let ((orig-window (selected-window))
3720 (window (other-window-for-scrolling)))
3723 (select-window window)
3725 (end-of-buffer arg))
3727 (select-window orig-window))))
3729 (defun transpose-chars (arg)
3730 "Interchange characters around point, moving forward one character.
3731 With prefix arg ARG, effect is to take character before point
3732 and drag it forward past ARG other characters (backward if ARG negative).
3733 If no argument and at end of line, the previous two chars are exchanged."
3735 (and (null arg) (eolp) (forward-char -1))
3736 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3738 (defun transpose-words (arg)
3739 "Interchange words around point, leaving point at end of them.
3740 With prefix arg ARG, effect is to take word before or around point
3741 and drag it forward past ARG other words (backward if ARG negative).
3742 If ARG is zero, the words around or after point and around or after mark
3744 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3746 (transpose-subr 'forward-word arg))
3748 (defun transpose-sexps (arg)
3749 "Like \\[transpose-words] but applies to sexps.
3750 Does not work on a sexp that point is in the middle of
3751 if it is a list or string."
3755 ;; Here we should try to simulate the behavior of
3756 ;; (cons (progn (forward-sexp x) (point))
3757 ;; (progn (forward-sexp (- x)) (point)))
3758 ;; Except that we don't want to rely on the second forward-sexp
3759 ;; putting us back to where we want to be, since forward-sexp-function
3760 ;; might do funny things like infix-precedence.
3762 (looking-at "\\sw\\|\\s_")
3764 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3765 ;; Jumping over a symbol. We might be inside it, mind you.
3766 (progn (funcall (if (> arg 0)
3767 'skip-syntax-backward 'skip-syntax-forward)
3769 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3770 ;; Otherwise, we're between sexps. Take a step back before jumping
3771 ;; to make sure we'll obey the same precedence no matter which direction
3773 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3774 (cons (save-excursion (forward-sexp arg) (point))
3775 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3776 (not (zerop (funcall (if (> arg 0)
3777 'skip-syntax-forward
3778 'skip-syntax-backward)
3783 (defun transpose-lines (arg)
3784 "Exchange current line and previous line, leaving point after both.
3785 With argument ARG, takes previous line and moves it past ARG lines.
3786 With argument 0, interchanges line point is in with line mark is in."
3788 (transpose-subr (function
3792 ;; Move forward over ARG lines,
3793 ;; but create newlines if necessary.
3794 (setq arg (forward-line arg))
3795 (if (/= (preceding-char) ?\n)
3796 (setq arg (1+ arg)))
3799 (forward-line arg))))
3802 (defun transpose-subr (mover arg &optional special)
3803 (let ((aux (if special mover
3805 (cons (progn (funcall mover x) (point))
3806 (progn (funcall mover (- x)) (point))))))
3811 (setq pos1 (funcall aux 1))
3813 (setq pos2 (funcall aux 1))
3814 (transpose-subr-1 pos1 pos2))
3815 (exchange-point-and-mark))
3817 (setq pos1 (funcall aux -1))
3818 (setq pos2 (funcall aux arg))
3819 (transpose-subr-1 pos1 pos2)
3820 (goto-char (car pos2)))
3822 (setq pos1 (funcall aux -1))
3823 (goto-char (car pos1))
3824 (setq pos2 (funcall aux arg))
3825 (transpose-subr-1 pos1 pos2)))))
3827 (defun transpose-subr-1 (pos1 pos2)
3828 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3829 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3830 (when (> (car pos1) (car pos2))
3832 (setq pos1 pos2 pos2 swap)))
3833 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3834 (atomic-change-group
3836 ;; FIXME: We first delete the two pieces of text, so markers that
3837 ;; used to point to after the text end up pointing to before it :-(
3838 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3839 (goto-char (car pos2))
3840 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3841 (goto-char (car pos1))
3844 (defun backward-word (&optional arg)
3845 "Move backward until encountering the beginning of a word.
3846 With argument, do this that many times."
3848 (forward-word (- (or arg 1))))
3850 (defun mark-word (&optional arg allow-extend)
3851 "Set mark ARG words away from point.
3852 The place mark goes is the same place \\[forward-word] would
3853 move to with the same argument.
3854 Interactively, if this command is repeated
3855 or (in Transient Mark mode) if the mark is active,
3856 it marks the next ARG words after the ones already marked."
3857 (interactive "P\np")
3858 (cond ((and allow-extend
3859 (or (and (eq last-command this-command) (mark t))
3860 (and transient-mark-mode mark-active)))
3861 (setq arg (if arg (prefix-numeric-value arg)
3862 (if (< (mark) (point)) -1 1)))
3871 (forward-word (prefix-numeric-value arg))
3875 (defun kill-word (arg)
3876 "Kill characters forward until encountering the end of a word.
3877 With argument, do this that many times."
3879 (kill-region (point) (progn (forward-word arg) (point))))
3881 (defun backward-kill-word (arg)
3882 "Kill characters backward until encountering the end of a word.
3883 With argument, do this that many times."
3885 (kill-word (- arg)))
3887 (defun current-word (&optional strict really-word)
3888 "Return the symbol or word that point is on (or a nearby one) as a string.
3889 The return value includes no text properties.
3890 If optional arg STRICT is non-nil, return nil unless point is within
3891 or adjacent to a symbol or word. In all cases the value can be nil
3892 if there is no word nearby.
3893 The function, belying its name, normally finds a symbol.
3894 If optional arg REALLY-WORD is non-nil, it finds just a word."
3896 (let* ((oldpoint (point)) (start (point)) (end (point))
3897 (syntaxes (if really-word "w" "w_"))
3898 (not-syntaxes (concat "^" syntaxes)))
3899 (skip-syntax-backward syntaxes) (setq start (point))
3900 (goto-char oldpoint)
3901 (skip-syntax-forward syntaxes) (setq end (point))
3902 (when (and (eq start oldpoint) (eq end oldpoint)
3903 ;; Point is neither within nor adjacent to a word.
3905 ;; Look for preceding word in same line.
3906 (skip-syntax-backward not-syntaxes
3907 (save-excursion (beginning-of-line)
3910 ;; No preceding word in same line.
3911 ;; Look for following word in same line.
3913 (skip-syntax-forward not-syntaxes
3914 (save-excursion (end-of-line)
3916 (setq start (point))
3917 (skip-syntax-forward syntaxes)
3920 (skip-syntax-backward syntaxes)
3921 (setq start (point))))
3922 ;; If we found something nonempty, return it as a string.
3923 (unless (= start end)
3924 (buffer-substring-no-properties start end)))))
3926 (defcustom fill-prefix nil
3927 "*String for filling to insert at front of new line, or nil for none."
3928 :type '(choice (const :tag "None" nil)
3931 (make-variable-buffer-local 'fill-prefix)
3933 (defcustom auto-fill-inhibit-regexp nil
3934 "*Regexp to match lines which should not be auto-filled."
3935 :type '(choice (const :tag "None" nil)
3939 (defvar comment-line-break-function 'comment-indent-new-line
3940 "*Mode-specific function which line breaks and continues a comment.
3942 This function is only called during auto-filling of a comment section.
3943 The function should take a single optional argument, which is a flag
3944 indicating whether it should use soft newlines.")
3946 ;; This function is used as the auto-fill-function of a buffer
3947 ;; when Auto-Fill mode is enabled.
3948 ;; It returns t if it really did any work.
3949 ;; (Actually some major modes use a different auto-fill function,
3950 ;; but this one is the default one.)
3951 (defun do-auto-fill ()
3952 (let (fc justify give-up
3953 (fill-prefix fill-prefix))
3954 (if (or (not (setq justify (current-justification)))
3955 (null (setq fc (current-fill-column)))
3956 (and (eq justify 'left)
3957 (<= (current-column) fc))
3958 (and auto-fill-inhibit-regexp
3959 (save-excursion (beginning-of-line)
3960 (looking-at auto-fill-inhibit-regexp))))
3961 nil ;; Auto-filling not required
3962 (if (memq justify '(full center right))
3963 (save-excursion (unjustify-current-line)))
3965 ;; Choose a fill-prefix automatically.
3966 (when (and adaptive-fill-mode
3967 (or (null fill-prefix) (string= fill-prefix "")))
3969 (fill-context-prefix
3970 (save-excursion (backward-paragraph 1) (point))
3971 (save-excursion (forward-paragraph 1) (point)))))
3972 (and prefix (not (equal prefix ""))
3973 ;; Use auto-indentation rather than a guessed empty prefix.
3974 (not (and fill-indent-according-to-mode
3975 (string-match "\\`[ \t]*\\'" prefix)))
3976 (setq fill-prefix prefix))))
3978 (while (and (not give-up) (> (current-column) fc))
3979 ;; Determine where to split the line.
3984 (setq after-prefix (point))
3986 (looking-at (regexp-quote fill-prefix))
3987 (setq after-prefix (match-end 0)))
3988 (move-to-column (1+ fc))
3989 (fill-move-to-break-point after-prefix)
3992 ;; See whether the place we found is any good.
3994 (goto-char fill-point)
3996 ;; There is no use breaking at end of line.
3997 (save-excursion (skip-chars-forward " ") (eolp))
3998 ;; It is futile to split at the end of the prefix
3999 ;; since we would just insert the prefix again.
4000 (and after-prefix (<= (point) after-prefix))
4001 ;; Don't split right after a comment starter
4002 ;; since we would just make another comment starter.
4003 (and comment-start-skip
4004 (let ((limit (point)))
4006 (and (re-search-forward comment-start-skip
4008 (eq (point) limit))))))
4009 ;; No good place to break => stop trying.
4011 ;; Ok, we have a useful place to break the line. Do it.
4012 (let ((prev-column (current-column)))
4013 ;; If point is at the fill-point, do not `save-excursion'.
4014 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4015 ;; point will end up before it rather than after it.
4017 (skip-chars-backward " \t")
4018 (= (point) fill-point))
4019 (funcall comment-line-break-function t)
4021 (goto-char fill-point)
4022 (funcall comment-line-break-function t)))
4023 ;; Now do justification, if required
4024 (if (not (eq justify 'left))
4027 (justify-current-line justify nil t)))
4028 ;; If making the new line didn't reduce the hpos of
4029 ;; the end of the line, then give up now;
4030 ;; trying again will not help.
4031 (if (>= (current-column) prev-column)
4032 (setq give-up t))))))
4033 ;; Justify last line.
4034 (justify-current-line justify t t)
4037 (defvar normal-auto-fill-function 'do-auto-fill
4038 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4039 Some major modes set this.")
4041 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
4042 ;; FIXME: turn into a proper minor mode.
4043 ;; Add a global minor mode version of it.
4044 (defun auto-fill-mode (&optional arg)
4045 "Toggle Auto Fill mode.
4046 With arg, turn Auto Fill mode on if and only if arg is positive.
4047 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4048 automatically breaks the line at a previous space.
4050 The value of `normal-auto-fill-function' specifies the function to use
4051 for `auto-fill-function' when turning Auto Fill mode on."
4053 (prog1 (setq auto-fill-function
4055 (not auto-fill-function)
4056 (> (prefix-numeric-value arg) 0))
4057 normal-auto-fill-function
4059 (force-mode-line-update)))
4061 ;; This holds a document string used to document auto-fill-mode.
4062 (defun auto-fill-function ()
4063 "Automatically break line at a previous space, in insertion of text."
4066 (defun turn-on-auto-fill ()
4067 "Unconditionally turn on Auto Fill mode."
4070 (defun turn-off-auto-fill ()
4071 "Unconditionally turn off Auto Fill mode."
4072 (auto-fill-mode -1))
4074 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
4076 (defun set-fill-column (arg)
4077 "Set `fill-column' to specified argument.
4078 Use \\[universal-argument] followed by a number to specify a column.
4079 Just \\[universal-argument] as argument means to use the current column."
4082 (setq arg (current-column)))
4083 (if (not (integerp arg))
4084 ;; Disallow missing argument; it's probably a typo for C-x C-f.
4085 (error "Set-fill-column requires an explicit argument")
4086 (message "Fill column set to %d (was %d)" arg fill-column)
4087 (setq fill-column arg)))
4089 (defun set-selective-display (arg)
4090 "Set `selective-display' to ARG; clear it if no arg.
4091 When the value of `selective-display' is a number > 0,
4092 lines whose indentation is >= that value are not displayed.
4093 The variable `selective-display' has a separate value for each buffer."
4095 (if (eq selective-display t)
4096 (error "selective-display already in use for marked lines"))
4099 (narrow-to-region (point-min) (point))
4100 (goto-char (window-start))
4101 (vertical-motion (window-height)))))
4102 (setq selective-display
4103 (and arg (prefix-numeric-value arg)))
4104 (recenter current-vpos))
4105 (set-window-start (selected-window) (window-start (selected-window)))
4106 (princ "selective-display set to " t)
4107 (prin1 selective-display t)
4110 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
4111 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
4113 (defun toggle-truncate-lines (arg)
4114 "Toggle whether to fold or truncate long lines on the screen.
4115 With arg, truncate long lines iff arg is positive.
4116 Note that in side-by-side windows, truncation is always enabled."
4118 (setq truncate-lines
4120 (not truncate-lines)
4121 (> (prefix-numeric-value arg) 0)))
4122 (force-mode-line-update)
4123 (unless truncate-lines
4124 (let ((buffer (current-buffer)))
4125 (walk-windows (lambda (window)
4126 (if (eq buffer (window-buffer window))
4127 (set-window-hscroll window 0)))
4129 (message "Truncate long lines %s"
4130 (if truncate-lines "enabled" "disabled")))
4132 (defvar overwrite-mode-textual " Ovwrt"
4133 "The string displayed in the mode line when in overwrite mode.")
4134 (defvar overwrite-mode-binary " Bin Ovwrt"
4135 "The string displayed in the mode line when in binary overwrite mode.")
4137 (defun overwrite-mode (arg)
4138 "Toggle overwrite mode.
4139 With arg, turn overwrite mode on iff arg is positive.
4140 In overwrite mode, printing characters typed in replace existing text
4141 on a one-for-one basis, rather than pushing it to the right. At the
4142 end of a line, such characters extend the line. Before a tab,
4143 such characters insert until the tab is filled in.
4144 \\[quoted-insert] still inserts characters in overwrite mode; this
4145 is supposed to make it easier to insert characters when necessary."
4147 (setq overwrite-mode
4148 (if (if (null arg) (not overwrite-mode)
4149 (> (prefix-numeric-value arg) 0))
4150 'overwrite-mode-textual))
4151 (force-mode-line-update))
4153 (defun binary-overwrite-mode (arg)
4154 "Toggle binary overwrite mode.
4155 With arg, turn binary overwrite mode on iff arg is positive.
4156 In binary overwrite mode, printing characters typed in replace
4157 existing text. Newlines are not treated specially, so typing at the
4158 end of a line joins the line to the next, with the typed character
4159 between them. Typing before a tab character simply replaces the tab
4160 with the character typed.
4161 \\[quoted-insert] replaces the text at the cursor, just as ordinary
4162 typing characters do.
4164 Note that binary overwrite mode is not its own minor mode; it is a
4165 specialization of overwrite-mode, entered by setting the
4166 `overwrite-mode' variable to `overwrite-mode-binary'."
4168 (setq overwrite-mode
4170 (not (eq overwrite-mode 'overwrite-mode-binary))
4171 (> (prefix-numeric-value arg) 0))
4172 'overwrite-mode-binary))
4173 (force-mode-line-update))
4175 (define-minor-mode line-number-mode
4176 "Toggle Line Number mode.
4177 With arg, turn Line Number mode on iff arg is positive.
4178 When Line Number mode is enabled, the line number appears
4181 Line numbers do not appear for very large buffers and buffers
4182 with very long lines; see variables `line-number-display-limit'
4183 and `line-number-display-limit-width'."
4184 :init-value t :global t :group 'editing-basics :require nil)
4186 (define-minor-mode column-number-mode
4187 "Toggle Column Number mode.
4188 With arg, turn Column Number mode on iff arg is positive.
4189 When Column Number mode is enabled, the column number appears
4191 :global t :group 'editing-basics :require nil)
4193 (define-minor-mode size-indication-mode
4194 "Toggle Size Indication mode.
4195 With arg, turn Size Indication mode on iff arg is positive. When
4196 Size Indication mode is enabled, the size of the accessible part
4197 of the buffer appears in the mode line."
4198 :global t :group 'editing-basics :require nil)
4200 (defgroup paren-blinking nil
4201 "Blinking matching of parens and expressions."
4202 :prefix "blink-matching-"
4203 :group 'paren-matching)
4205 (defcustom blink-matching-paren t
4206 "*Non-nil means show matching open-paren when close-paren is inserted."
4208 :group 'paren-blinking)
4210 (defcustom blink-matching-paren-on-screen t
4211 "*Non-nil means show matching open-paren when it is on screen.
4212 If nil, means don't show it (but the open-paren can still be shown
4213 when it is off screen)."
4215 :group 'paren-blinking)
4217 (defcustom blink-matching-paren-distance (* 25 1024)
4218 "*If non-nil, is maximum distance to search for matching open-paren."
4220 :group 'paren-blinking)
4222 (defcustom blink-matching-delay 1
4223 "*Time in seconds to delay after showing a matching paren."
4225 :group 'paren-blinking)
4227 (defcustom blink-matching-paren-dont-ignore-comments nil
4228 "*Non-nil means `blink-matching-paren' will not ignore comments."
4230 :group 'paren-blinking)
4232 (defun blink-matching-open ()
4233 "Move cursor momentarily to the beginning of the sexp before point."
4235 (and (> (point) (1+ (point-min)))
4236 blink-matching-paren
4237 ;; Verify an even number of quoting characters precede the close.
4238 (= 1 (logand 1 (- (point)
4241 (skip-syntax-backward "/\\")
4243 (let* ((oldpos (point))
4249 (if blink-matching-paren-distance
4250 (narrow-to-region (max (point-min)
4251 (- (point) blink-matching-paren-distance))
4254 (let ((parse-sexp-ignore-comments
4255 (and parse-sexp-ignore-comments
4256 (not blink-matching-paren-dont-ignore-comments))))
4257 (setq blinkpos (scan-sexps oldpos -1)))
4261 (not (eq (syntax-class (syntax-after blinkpos)) 8))
4262 (setq matching-paren
4263 (let ((syntax (syntax-after blinkpos)))
4265 (eq (syntax-class syntax) 4)
4268 (or (null matching-paren)
4269 (/= (char-after (1- oldpos))
4271 (if mismatch (setq blinkpos nil))
4273 ;; Don't log messages about paren matching.
4274 (let (message-log-max)
4275 (goto-char blinkpos)
4276 (if (pos-visible-in-window-p)
4277 (and blink-matching-paren-on-screen
4278 (sit-for blink-matching-delay))
4279 (goto-char blinkpos)
4282 ;; Show what precedes the open in its line, if anything.
4284 (skip-chars-backward " \t")
4286 (buffer-substring (progn (beginning-of-line) (point))
4288 ;; Show what follows the open in its line, if anything.
4291 (skip-chars-forward " \t")
4293 (buffer-substring blinkpos
4294 (progn (end-of-line) (point)))
4295 ;; Otherwise show the previous nonblank line,
4298 (skip-chars-backward "\n \t")
4301 (buffer-substring (progn
4302 (skip-chars-backward "\n \t")
4305 (progn (end-of-line)
4306 (skip-chars-backward " \t")
4308 ;; Replace the newline and other whitespace with `...'.
4310 (buffer-substring blinkpos (1+ blinkpos)))
4311 ;; There is nothing to show except the char itself.
4312 (buffer-substring blinkpos (1+ blinkpos))))))))
4314 (message "Mismatched parentheses"))
4315 ((not blink-matching-paren-distance)
4316 (message "Unmatched parenthesis"))))))))
4318 ;Turned off because it makes dbx bomb out.
4319 (setq blink-paren-function 'blink-matching-open)
4321 ;; This executes C-g typed while Emacs is waiting for a command.
4322 ;; Quitting out of a program does not go through here;
4323 ;; that happens in the QUIT macro at the C code level.
4324 (defun keyboard-quit ()
4325 "Signal a `quit' condition.
4326 During execution of Lisp code, this character causes a quit directly.
4327 At top-level, as an editor command, this simply beeps."
4330 (if (fboundp 'kmacro-keyboard-quit)
4331 (kmacro-keyboard-quit))
4332 (setq defining-kbd-macro nil)
4335 (defvar buffer-quit-function nil
4336 "Function to call to \"quit\" the current buffer, or nil if none.
4337 \\[keyboard-escape-quit] calls this function when its more local actions
4338 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4340 (defun keyboard-escape-quit ()
4341 "Exit the current \"mode\" (in a generalized sense of the word).
4342 This command can exit an interactive command such as `query-replace',
4343 can clear out a prefix argument or a region,
4344 can get out of the minibuffer or other recursive edit,
4345 cancel the use of the current buffer (for special-purpose buffers),
4346 or go back to just one window (by deleting all but the selected window)."
4348 (cond ((eq last-command 'mode-exited) nil)
4349 ((> (minibuffer-depth) 0)
4350 (abort-recursive-edit))
4353 ((and transient-mark-mode mark-active)
4355 ((> (recursion-depth) 0)
4356 (exit-recursive-edit))
4357 (buffer-quit-function
4358 (funcall buffer-quit-function))
4359 ((not (one-window-p t))
4360 (delete-other-windows))
4361 ((string-match "^ \\*" (buffer-name (current-buffer)))
4364 (defun play-sound-file (file &optional volume device)
4365 "Play sound stored in FILE.
4366 VOLUME and DEVICE correspond to the keywords of the sound
4367 specification for `play-sound'."
4368 (interactive "fPlay sound file: ")
4369 (let ((sound (list :file file)))
4371 (plist-put sound :volume volume))
4373 (plist-put sound :device device))
4375 (play-sound sound)))
4378 (defcustom read-mail-command 'rmail
4379 "*Your preference for a mail reading package.
4380 This is used by some keybindings which support reading mail.
4381 See also `mail-user-agent' concerning sending mail."
4382 :type '(choice (function-item rmail)
4383 (function-item gnus)
4384 (function-item mh-rmail)
4385 (function :tag "Other"))
4389 (defcustom mail-user-agent 'sendmail-user-agent
4390 "*Your preference for a mail composition package.
4391 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
4392 outgoing email message. This variable lets you specify which
4393 mail-sending package you prefer.
4395 Valid values include:
4397 `sendmail-user-agent' -- use the default Emacs Mail package.
4398 See Info node `(emacs)Sending Mail'.
4399 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
4400 See Info node `(mh-e)'.
4401 `message-user-agent' -- use the Gnus Message package.
4402 See Info node `(message)'.
4403 `gnus-user-agent' -- like `message-user-agent', but with Gnus
4404 paraphernalia, particularly the Gcc: header for
4407 Additional valid symbols may be available; check with the author of
4408 your package for details. The function should return non-nil if it
4411 See also `read-mail-command' concerning reading mail."
4412 :type '(radio (function-item :tag "Default Emacs mail"
4414 sendmail-user-agent)
4415 (function-item :tag "Emacs interface to MH"
4418 (function-item :tag "Gnus Message package"
4421 (function-item :tag "Gnus Message with full Gnus features"
4424 (function :tag "Other"))
4427 (define-mail-user-agent 'sendmail-user-agent
4428 'sendmail-user-agent-compose
4429 'mail-send-and-exit)
4431 (defun rfc822-goto-eoh ()
4432 ;; Go to header delimiter line in a mail message, following RFC822 rules
4433 (goto-char (point-min))
4434 (when (re-search-forward
4435 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
4436 (goto-char (match-beginning 0))))
4438 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
4439 switch-function yank-action
4442 (let ((special-display-buffer-names nil)
4443 (special-display-regexps nil)
4444 (same-window-buffer-names nil)
4445 (same-window-regexps nil))
4446 (funcall switch-function "*mail*")))
4447 (let ((cc (cdr (assoc-string "cc" other-headers t)))
4448 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
4449 (body (cdr (assoc-string "body" other-headers t))))
4450 (or (mail continue to subject in-reply-to cc yank-action send-actions)
4452 (error "Message aborted"))
4455 (while other-headers
4456 (unless (member-ignore-case (car (car other-headers))
4457 '("in-reply-to" "cc" "body"))
4458 (insert (car (car other-headers)) ": "
4459 (cdr (car other-headers)) "\n"))
4460 (setq other-headers (cdr other-headers)))
4466 (define-mail-user-agent 'mh-e-user-agent
4467 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
4468 'mh-before-send-letter-hook)
4470 (defun compose-mail (&optional to subject other-headers continue
4471 switch-function yank-action send-actions)
4472 "Start composing a mail message to send.
4473 This uses the user's chosen mail composition package
4474 as selected with the variable `mail-user-agent'.
4475 The optional arguments TO and SUBJECT specify recipients
4476 and the initial Subject field, respectively.
4478 OTHER-HEADERS is an alist specifying additional
4479 header fields. Elements look like (HEADER . VALUE) where both
4480 HEADER and VALUE are strings.
4482 CONTINUE, if non-nil, says to continue editing a message already
4485 SWITCH-FUNCTION, if non-nil, is a function to use to
4486 switch to and display the buffer used for mail composition.
4488 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
4489 to insert the raw text of the message being replied to.
4490 It has the form (FUNCTION . ARGS). The user agent will apply
4491 FUNCTION to ARGS, to insert the raw text of the original message.
4492 \(The user agent will also run `mail-citation-hook', *after* the
4493 original text has been inserted in this way.)
4495 SEND-ACTIONS is a list of actions to call when the message is sent.
4496 Each action has the form (FUNCTION . ARGS)."
4498 (list nil nil nil current-prefix-arg))
4499 (let ((function (get mail-user-agent 'composefunc)))
4500 (funcall function to subject other-headers continue
4501 switch-function yank-action send-actions)))
4503 (defun compose-mail-other-window (&optional to subject other-headers continue
4504 yank-action send-actions)
4505 "Like \\[compose-mail], but edit the outgoing message in another window."
4507 (list nil nil nil current-prefix-arg))
4508 (compose-mail to subject other-headers continue
4509 'switch-to-buffer-other-window yank-action send-actions))
4512 (defun compose-mail-other-frame (&optional to subject other-headers continue
4513 yank-action send-actions)
4514 "Like \\[compose-mail], but edit the outgoing message in another frame."
4516 (list nil nil nil current-prefix-arg))
4517 (compose-mail to subject other-headers continue
4518 'switch-to-buffer-other-frame yank-action send-actions))
4520 (defvar set-variable-value-history nil
4521 "History of values entered with `set-variable'.")
4523 (defun set-variable (variable value &optional make-local)
4524 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4525 VARIABLE should be a user option variable name, a Lisp variable
4526 meant to be customized by users. You should enter VALUE in Lisp syntax,
4527 so if you want VALUE to be a string, you must surround it with doublequotes.
4528 VALUE is used literally, not evaluated.
4530 If VARIABLE has a `variable-interactive' property, that is used as if
4531 it were the arg to `interactive' (which see) to interactively read VALUE.
4533 If VARIABLE has been defined with `defcustom', then the type information
4534 in the definition is used to check that VALUE is valid.
4536 With a prefix argument, set VARIABLE to VALUE buffer-locally."
4538 (let* ((default-var (variable-at-point))
4539 (var (if (symbolp default-var)
4540 (read-variable (format "Set variable (default %s): " default-var)
4542 (read-variable "Set variable: ")))
4543 (minibuffer-help-form '(describe-variable var))
4544 (prop (get var 'variable-interactive))
4545 (obsolete (car (get var 'byte-obsolete-variable)))
4546 (prompt (format "Set %s %s to value: " var
4547 (cond ((local-variable-p var)
4549 ((or current-prefix-arg
4550 (local-variable-if-set-p var))
4555 (message (concat "`%S' is obsolete; "
4556 (if (symbolp obsolete) "use `%S' instead" "%s"))
4560 ;; Use VAR's `variable-interactive' property
4561 ;; as an interactive spec for prompting.
4562 (call-interactively `(lambda (arg)
4566 (read-string prompt nil
4567 'set-variable-value-history))))))
4568 (list var val current-prefix-arg)))
4570 (and (custom-variable-p variable)
4571 (not (get variable 'custom-type))
4572 (custom-load-symbol variable))
4573 (let ((type (get variable 'custom-type)))
4575 ;; Match with custom type.
4577 (setq type (widget-convert type))
4578 (unless (widget-apply type :match value)
4579 (error "Value `%S' does not match type %S of %S"
4580 value (car type) variable))))
4583 (make-local-variable variable))
4585 (set variable value)
4587 ;; Force a thorough redisplay for the case that the variable
4588 ;; has an effect on the display, like `tab-width' has.
4589 (force-mode-line-update))
4591 ;; Define the major mode for lists of completions.
4593 (defvar completion-list-mode-map nil
4594 "Local map for completion list buffers.")
4595 (or completion-list-mode-map
4596 (let ((map (make-sparse-keymap)))
4597 (define-key map [mouse-2] 'mouse-choose-completion)
4598 (define-key map [follow-link] 'mouse-face)
4599 (define-key map [down-mouse-2] nil)
4600 (define-key map "\C-m" 'choose-completion)
4601 (define-key map "\e\e\e" 'delete-completion-window)
4602 (define-key map [left] 'previous-completion)
4603 (define-key map [right] 'next-completion)
4604 (setq completion-list-mode-map map)))
4606 ;; Completion mode is suitable only for specially formatted data.
4607 (put 'completion-list-mode 'mode-class 'special)
4609 (defvar completion-reference-buffer nil
4610 "Record the buffer that was current when the completion list was requested.
4611 This is a local variable in the completion list buffer.
4612 Initial value is nil to avoid some compiler warnings.")
4614 (defvar completion-no-auto-exit nil
4615 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4616 This also applies to other functions such as `choose-completion'
4617 and `mouse-choose-completion'.")
4619 (defvar completion-base-size nil
4620 "Number of chars at beginning of minibuffer not involved in completion.
4621 This is a local variable in the completion list buffer
4622 but it talks about the buffer in `completion-reference-buffer'.
4623 If this is nil, it means to compare text to determine which part
4624 of the tail end of the buffer's text is involved in completion.")
4626 (defun delete-completion-window ()
4627 "Delete the completion list window.
4628 Go to the window from which completion was requested."
4630 (let ((buf completion-reference-buffer))
4631 (if (one-window-p t)
4632 (if (window-dedicated-p (selected-window))
4633 (delete-frame (selected-frame)))
4634 (delete-window (selected-window))
4635 (if (get-buffer-window buf)
4636 (select-window (get-buffer-window buf))))))
4638 (defun previous-completion (n)
4639 "Move to the previous item in the completion list."
4641 (next-completion (- n)))
4643 (defun next-completion (n)
4644 "Move to the next item in the completion list.
4645 With prefix argument N, move N items (negative N means move backward)."
4647 (let ((beg (point-min)) (end (point-max)))
4648 (while (and (> n 0) (not (eobp)))
4649 ;; If in a completion, move to the end of it.
4650 (when (get-text-property (point) 'mouse-face)
4651 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4652 ;; Move to start of next one.
4653 (unless (get-text-property (point) 'mouse-face)
4654 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4656 (while (and (< n 0) (not (bobp)))
4657 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4658 ;; If in a completion, move to the start of it.
4659 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
4660 (goto-char (previous-single-property-change
4661 (point) 'mouse-face nil beg)))
4662 ;; Move to end of the previous completion.
4663 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4664 (goto-char (previous-single-property-change
4665 (point) 'mouse-face nil beg)))
4666 ;; Move to the start of that one.
4667 (goto-char (previous-single-property-change
4668 (point) 'mouse-face nil beg))
4671 (defun choose-completion ()
4672 "Choose the completion that point is in or next to."
4674 (let (beg end completion (buffer completion-reference-buffer)
4675 (base-size completion-base-size))
4676 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4677 (setq end (point) beg (1+ (point))))
4678 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
4679 (setq end (1- (point)) beg (point)))
4681 (error "No completion here"))
4682 (setq beg (previous-single-property-change beg 'mouse-face))
4683 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
4684 (setq completion (buffer-substring beg end))
4685 (let ((owindow (selected-window)))
4686 (if (and (one-window-p t 'selected-frame)
4687 (window-dedicated-p (selected-window)))
4688 ;; This is a special buffer's frame
4689 (iconify-frame (selected-frame))
4690 (or (window-dedicated-p (selected-window))
4692 (select-window owindow))
4693 (choose-completion-string completion buffer base-size)))
4695 ;; Delete the longest partial match for STRING
4696 ;; that can be found before POINT.
4697 (defun choose-completion-delete-max-match (string)
4698 (let ((opoint (point))
4700 ;; Try moving back by the length of the string.
4701 (goto-char (max (- (point) (length string))
4702 (minibuffer-prompt-end)))
4703 ;; See how far back we were actually able to move. That is the
4704 ;; upper bound on how much we can match and delete.
4705 (setq len (- opoint (point)))
4706 (if completion-ignore-case
4707 (setq string (downcase string)))
4708 (while (and (> len 0)
4709 (let ((tail (buffer-substring (point) opoint)))
4710 (if completion-ignore-case
4711 (setq tail (downcase tail)))
4712 (not (string= tail (substring string 0 len)))))
4717 (defvar choose-completion-string-functions nil
4718 "Functions that may override the normal insertion of a completion choice.
4719 These functions are called in order with four arguments:
4720 CHOICE - the string to insert in the buffer,
4721 BUFFER - the buffer in which the choice should be inserted,
4722 MINI-P - non-nil iff BUFFER is a minibuffer, and
4723 BASE-SIZE - the number of characters in BUFFER before
4724 the string being completed.
4726 If a function in the list returns non-nil, that function is supposed
4727 to have inserted the CHOICE in the BUFFER, and possibly exited
4728 the minibuffer; no further functions will be called.
4730 If all functions in the list return nil, that means to use
4731 the default method of inserting the completion in BUFFER.")
4733 (defun choose-completion-string (choice &optional buffer base-size)
4734 "Switch to BUFFER and insert the completion choice CHOICE.
4735 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
4736 to keep. If it is nil, we call `choose-completion-delete-max-match'
4737 to decide what to delete."
4739 ;; If BUFFER is the minibuffer, exit the minibuffer
4740 ;; unless it is reading a file name and CHOICE is a directory,
4741 ;; or completion-no-auto-exit is non-nil.
4743 (let* ((buffer (or buffer completion-reference-buffer))
4744 (mini-p (minibufferp buffer)))
4745 ;; If BUFFER is a minibuffer, barf unless it's the currently
4746 ;; active minibuffer.
4748 (or (not (active-minibuffer-window))
4750 (window-buffer (active-minibuffer-window))))))
4751 (error "Minibuffer is not active for completion")
4752 ;; Set buffer so buffer-local choose-completion-string-functions works.
4754 (unless (run-hook-with-args-until-success
4755 'choose-completion-string-functions
4756 choice buffer mini-p base-size)
4757 ;; Insert the completion into the buffer where it was requested.
4759 (delete-region (+ base-size (if mini-p
4760 (minibuffer-prompt-end)
4763 (choose-completion-delete-max-match choice))
4765 (remove-text-properties (- (point) (length choice)) (point)
4767 ;; Update point in the window that BUFFER is showing in.
4768 (let ((window (get-buffer-window buffer t)))
4769 (set-window-point window (point)))
4770 ;; If completing for the minibuffer, exit it with this choice.
4771 (and (not completion-no-auto-exit)
4772 (equal buffer (window-buffer (minibuffer-window)))
4773 minibuffer-completion-table
4774 ;; If this is reading a file name, and the file name chosen
4775 ;; is a directory, don't exit the minibuffer.
4776 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4777 (file-directory-p (field-string (point-max))))
4778 (let ((mini (active-minibuffer-window)))
4779 (select-window mini)
4780 (when minibuffer-auto-raise
4781 (raise-frame (window-frame mini))))
4782 (exit-minibuffer)))))))
4784 (defun completion-list-mode ()
4785 "Major mode for buffers showing lists of possible completions.
4786 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4787 to select the completion near point.
4788 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4791 (kill-all-local-variables)
4792 (use-local-map completion-list-mode-map)
4793 (setq mode-name "Completion List")
4794 (setq major-mode 'completion-list-mode)
4795 (make-local-variable 'completion-base-size)
4796 (setq completion-base-size nil)
4797 (run-mode-hooks 'completion-list-mode-hook))
4799 (defun completion-list-mode-finish ()
4800 "Finish setup of the completions buffer.
4801 Called from `temp-buffer-show-hook'."
4802 (when (eq major-mode 'completion-list-mode)
4803 (toggle-read-only 1)))
4805 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4807 (defvar completion-setup-hook nil
4808 "Normal hook run at the end of setting up a completion list buffer.
4809 When this hook is run, the current buffer is the one in which the
4810 command to display the completion list buffer was run.
4811 The completion list buffer is available as the value of `standard-output'.")
4813 ;; This function goes in completion-setup-hook, so that it is called
4814 ;; after the text of the completion list buffer is written.
4815 (defface completions-first-difference
4816 '((t (:inherit bold)))
4817 "Face put on the first uncommon character in completions in *Completions* buffer."
4820 (defface completions-common-part
4821 '((t (:inherit default)))
4822 "Face put on the common prefix substring in completions in *Completions* buffer.
4823 The idea of `completions-common-part' is that you can use it to
4824 make the common parts less visible than normal, so that the rest
4825 of the differing parts is, by contrast, slightly highlighted."
4828 ;; This is for packages that need to bind it to a non-default regexp
4829 ;; in order to make the first-differing character highlight work
4831 (defvar completion-root-regexp "^/"
4832 "Regexp to use in `completion-setup-function' to find the root directory.")
4834 (defun completion-setup-function ()
4835 (let ((mainbuf (current-buffer))
4836 (mbuf-contents (minibuffer-contents)))
4837 ;; When reading a file name in the minibuffer,
4838 ;; set default-directory in the minibuffer
4839 ;; so it will get copied into the completion list buffer.
4840 (if minibuffer-completing-file-name
4841 (with-current-buffer mainbuf
4842 (setq default-directory (file-name-directory mbuf-contents))))
4843 ;; If partial-completion-mode is on, point might not be after the
4844 ;; last character in the minibuffer.
4845 ;; FIXME: This still doesn't work if the text to be completed
4846 ;; starts with a `-'.
4847 (when (and partial-completion-mode (not (eobp)))
4849 (substring mbuf-contents 0 (- (point) (point-max)))))
4850 (with-current-buffer standard-output
4851 (completion-list-mode)
4852 (make-local-variable 'completion-reference-buffer)
4853 (setq completion-reference-buffer mainbuf)
4854 (if minibuffer-completing-file-name
4855 ;; For file name completion,
4856 ;; use the number of chars before the start of the
4857 ;; last file name component.
4858 (setq completion-base-size
4859 (with-current-buffer mainbuf
4861 (goto-char (point-max))
4862 (skip-chars-backward completion-root-regexp)
4863 (- (point) (minibuffer-prompt-end)))))
4864 ;; Otherwise, in minibuffer, the whole input is being completed.
4865 (if (minibufferp mainbuf)
4866 (if (and (symbolp minibuffer-completion-table)
4867 (get minibuffer-completion-table 'completion-base-size-function))
4868 (setq completion-base-size
4869 (funcall (get minibuffer-completion-table 'completion-base-size-function)))
4870 (setq completion-base-size 0))))
4871 ;; Put faces on first uncommon characters and common parts.
4872 (when completion-base-size
4873 (let* ((common-string-length
4874 (- (length mbuf-contents) completion-base-size))
4875 (element-start (next-single-property-change
4880 (+ (or element-start nil) common-string-length)))
4882 (while (and element-start (< element-common-end maxp))
4883 (when (and (get-char-property element-start 'mouse-face)
4884 (get-char-property element-common-end 'mouse-face))
4885 (put-text-property element-start element-common-end
4886 'font-lock-face 'completions-common-part)
4887 (put-text-property element-common-end (1+ element-common-end)
4888 'font-lock-face 'completions-first-difference))
4889 (setq element-start (next-single-property-change
4893 (setq element-common-end (+ element-start common-string-length))))))
4894 ;; Insert help string.
4895 (goto-char (point-min))
4896 (if (display-mouse-p)
4897 (insert (substitute-command-keys
4898 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4899 (insert (substitute-command-keys
4900 "In this buffer, type \\[choose-completion] to \
4901 select the completion near point.\n\n")))))
4903 (add-hook 'completion-setup-hook 'completion-setup-function)
4905 (define-key minibuffer-local-completion-map [prior]
4906 'switch-to-completions)
4907 (define-key minibuffer-local-must-match-map [prior]
4908 'switch-to-completions)
4909 (define-key minibuffer-local-completion-map "\M-v"
4910 'switch-to-completions)
4911 (define-key minibuffer-local-must-match-map "\M-v"
4912 'switch-to-completions)
4914 (defun switch-to-completions ()
4915 "Select the completion list window."
4917 ;; Make sure we have a completions window.
4918 (or (get-buffer-window "*Completions*")
4919 (minibuffer-completion-help))
4920 (let ((window (get-buffer-window "*Completions*")))
4922 (select-window window)
4923 (goto-char (point-min))
4924 (search-forward "\n\n")
4927 ;; Support keyboard commands to turn on various modifiers.
4929 ;; These functions -- which are not commands -- each add one modifier
4930 ;; to the following event.
4932 (defun event-apply-alt-modifier (ignore-prompt)
4933 "\\<function-key-map>Add the Alt modifier to the following event.
4934 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
4935 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4936 (defun event-apply-super-modifier (ignore-prompt)
4937 "\\<function-key-map>Add the Super modifier to the following event.
4938 For example, type \\[event-apply-super-modifier] & to enter Super-&."
4939 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4940 (defun event-apply-hyper-modifier (ignore-prompt)
4941 "\\<function-key-map>Add the Hyper modifier to the following event.
4942 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
4943 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4944 (defun event-apply-shift-modifier (ignore-prompt)
4945 "\\<function-key-map>Add the Shift modifier to the following event.
4946 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
4947 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4948 (defun event-apply-control-modifier (ignore-prompt)
4949 "\\<function-key-map>Add the Ctrl modifier to the following event.
4950 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
4951 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4952 (defun event-apply-meta-modifier (ignore-prompt)
4953 "\\<function-key-map>Add the Meta modifier to the following event.
4954 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
4955 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4957 (defun event-apply-modifier (event symbol lshiftby prefix)
4958 "Apply a modifier flag to event EVENT.
4959 SYMBOL is the name of this modifier, as a symbol.
4960 LSHIFTBY is the numeric value of this modifier, in keyboard events.
4961 PREFIX is the string that represents this modifier in an event type symbol."
4963 (cond ((eq symbol 'control)
4964 (if (and (<= (downcase event) ?z)
4965 (>= (downcase event) ?a))
4966 (- (downcase event) ?a -1)
4967 (if (and (<= (downcase event) ?Z)
4968 (>= (downcase event) ?A))
4969 (- (downcase event) ?A -1)
4970 (logior (lsh 1 lshiftby) event))))
4972 (if (and (<= (downcase event) ?z)
4973 (>= (downcase event) ?a))
4975 (logior (lsh 1 lshiftby) event)))
4977 (logior (lsh 1 lshiftby) event)))
4978 (if (memq symbol (event-modifiers event))
4980 (let ((event-type (if (symbolp event) event (car event))))
4981 (setq event-type (intern (concat prefix (symbol-name event-type))))
4984 (cons event-type (cdr event)))))))
4986 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4987 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4988 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4989 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4990 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4991 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
4993 ;;;; Keypad support.
4995 ;;; Make the keypad keys act like ordinary typing keys. If people add
4996 ;;; bindings for the function key symbols, then those bindings will
4997 ;;; override these, so this shouldn't interfere with any existing
5000 ;; Also tell read-char how to handle these keys.
5002 (lambda (keypad-normal)
5003 (let ((keypad (nth 0 keypad-normal))
5004 (normal (nth 1 keypad-normal)))
5005 (put keypad 'ascii-character normal)
5006 (define-key function-key-map (vector keypad) (vector normal))))
5007 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
5008 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
5021 ;;;; forking a twin copy of a buffer.
5024 (defvar clone-buffer-hook nil
5025 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5027 (defun clone-process (process &optional newname)
5028 "Create a twin copy of PROCESS.
5029 If NEWNAME is nil, it defaults to PROCESS' name;
5030 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5031 If PROCESS is associated with a buffer, the new process will be associated
5032 with the current buffer instead.
5033 Returns nil if PROCESS has already terminated."
5034 (setq newname (or newname (process-name process)))
5035 (if (string-match "<[0-9]+>\\'" newname)
5036 (setq newname (substring newname 0 (match-beginning 0))))
5037 (when (memq (process-status process) '(run stop open))
5038 (let* ((process-connection-type (process-tty-name process))
5040 (if (memq (process-status process) '(open))
5041 (let ((args (process-contact process t)))
5042 (setq args (plist-put args :name newname))
5043 (setq args (plist-put args :buffer
5044 (if (process-buffer process)
5046 (apply 'make-network-process args))
5047 (apply 'start-process newname
5048 (if (process-buffer process) (current-buffer))
5049 (process-command process)))))
5050 (set-process-query-on-exit-flag
5051 new-process (process-query-on-exit-flag process))
5052 (set-process-inherit-coding-system-flag
5053 new-process (process-inherit-coding-system-flag process))
5054 (set-process-filter new-process (process-filter process))
5055 (set-process-sentinel new-process (process-sentinel process))
5056 (set-process-plist new-process (copy-sequence (process-plist process)))
5059 ;; things to maybe add (currently partly covered by `funcall mode'):
5062 (defun clone-buffer (&optional newname display-flag)
5063 "Create and return a twin copy of the current buffer.
5064 Unlike an indirect buffer, the new buffer can be edited
5065 independently of the old one (if it is not read-only).
5066 NEWNAME is the name of the new buffer. It may be modified by
5067 adding or incrementing <N> at the end as necessary to create a
5068 unique buffer name. If nil, it defaults to the name of the
5069 current buffer, with the proper suffix. If DISPLAY-FLAG is
5070 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
5071 clone a file-visiting buffer, or a buffer whose major mode symbol
5072 has a non-nil `no-clone' property, results in an error.
5074 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
5075 current buffer with appropriate suffix. However, if a prefix
5076 argument is given, then the command prompts for NEWNAME in the
5079 This runs the normal hook `clone-buffer-hook' in the new buffer
5080 after it has been set up properly in other respects."
5083 (if buffer-file-name
5084 (error "Cannot clone a file-visiting buffer"))
5085 (if (get major-mode 'no-clone)
5086 (error "Cannot clone a buffer in %s mode" mode-name))
5087 (list (if current-prefix-arg (read-string "Name: "))
5089 (if buffer-file-name
5090 (error "Cannot clone a file-visiting buffer"))
5091 (if (get major-mode 'no-clone)
5092 (error "Cannot clone a buffer in %s mode" mode-name))
5093 (setq newname (or newname (buffer-name)))
5094 (if (string-match "<[0-9]+>\\'" newname)
5095 (setq newname (substring newname 0 (match-beginning 0))))
5096 (let ((buf (current-buffer))
5100 (mk (if mark-active (mark t)))
5101 (modified (buffer-modified-p))
5103 (lvars (buffer-local-variables))
5104 (process (get-buffer-process (current-buffer)))
5105 (new (generate-new-buffer (or newname (buffer-name)))))
5108 (with-current-buffer new
5109 (insert-buffer-substring buf)))
5110 (with-current-buffer new
5111 (narrow-to-region ptmin ptmax)
5113 (if mk (set-mark mk))
5114 (set-buffer-modified-p modified)
5116 ;; Clone the old buffer's process, if any.
5117 (when process (clone-process process))
5119 ;; Now set up the major mode.
5122 ;; Set up other local variables.
5124 (condition-case () ;in case var is read-only
5127 (set (make-local-variable (car v)) (cdr v)))
5131 ;; Run any hooks (typically set up by the major mode
5132 ;; for cloning to work properly).
5133 (run-hooks 'clone-buffer-hook))
5134 (if display-flag (pop-to-buffer new))
5138 (defun clone-indirect-buffer (newname display-flag &optional norecord)
5139 "Create an indirect buffer that is a twin copy of the current buffer.
5141 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
5142 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
5143 or if not called with a prefix arg, NEWNAME defaults to the current
5144 buffer's name. The name is modified by adding a `<N>' suffix to it
5145 or by incrementing the N in an existing suffix.
5147 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
5148 This is always done when called interactively.
5150 Optional last arg NORECORD non-nil means do not put this buffer at the
5151 front of the list of recently selected ones."
5154 (if (get major-mode 'no-clone-indirect)
5155 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5156 (list (if current-prefix-arg
5157 (read-string "BName of indirect buffer: "))
5159 (if (get major-mode 'no-clone-indirect)
5160 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5161 (setq newname (or newname (buffer-name)))
5162 (if (string-match "<[0-9]+>\\'" newname)
5163 (setq newname (substring newname 0 (match-beginning 0))))
5164 (let* ((name (generate-new-buffer-name newname))
5165 (buffer (make-indirect-buffer (current-buffer) name t)))
5167 (pop-to-buffer buffer norecord))
5171 (defun clone-indirect-buffer-other-window (buffer &optional norecord)
5172 "Create an indirect buffer that is a twin copy of BUFFER.
5173 Select the new buffer in another window.
5174 Optional second arg NORECORD non-nil means do not put this buffer at
5175 the front of the list of recently selected ones."
5176 (interactive "bClone buffer in other window: ")
5177 (let ((pop-up-windows t))
5179 (clone-indirect-buffer nil t norecord)))
5182 ;;; Handling of Backspace and Delete keys.
5184 (defcustom normal-erase-is-backspace
5185 (and (not noninteractive)
5186 (or (memq system-type '(ms-dos windows-nt))
5187 (eq initial-window-system 'mac)
5188 (and (memq initial-window-system '(x))
5189 (fboundp 'x-backspace-delete-keys-p)
5190 (x-backspace-delete-keys-p))
5191 ;; If the terminal Emacs is running on has erase char
5192 ;; set to ^H, use the Backspace key for deleting
5193 ;; backward and, and the Delete key for deleting forward.
5194 (and (null initial-window-system)
5195 (eq tty-erase-char ?\^H))))
5196 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
5198 On window systems, the default value of this option is chosen
5199 according to the keyboard used. If the keyboard has both a Backspace
5200 key and a Delete key, and both are mapped to their usual meanings, the
5201 option's default value is set to t, so that Backspace can be used to
5202 delete backward, and Delete can be used to delete forward.
5204 If not running under a window system, customizing this option accomplishes
5205 a similar effect by mapping C-h, which is usually generated by the
5206 Backspace key, to DEL, and by mapping DEL to C-d via
5207 `keyboard-translate'. The former functionality of C-h is available on
5208 the F1 key. You should probably not use this setting if you don't
5209 have both Backspace, Delete and F1 keys.
5211 Setting this variable with setq doesn't take effect. Programmatically,
5212 call `normal-erase-is-backspace-mode' (which see) instead."
5214 :group 'editing-basics
5216 :set (lambda (symbol value)
5217 ;; The fboundp is because of a problem with :set when
5218 ;; dumping Emacs. It doesn't really matter.
5219 (if (fboundp 'normal-erase-is-backspace-mode)
5220 (normal-erase-is-backspace-mode (or value 0))
5221 (set-default symbol value))))
5224 (defun normal-erase-is-backspace-mode (&optional arg)
5225 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5227 With numeric arg, turn the mode on if and only if ARG is positive.
5229 On window systems, when this mode is on, Delete is mapped to C-d and
5230 Backspace is mapped to DEL; when this mode is off, both Delete and
5231 Backspace are mapped to DEL. (The remapping goes via
5232 `function-key-map', so binding Delete or Backspace in the global or
5233 local keymap will override that.)
5235 In addition, on window systems, the bindings of C-Delete, M-Delete,
5236 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5237 the global keymap in accordance with the functionality of Delete and
5238 Backspace. For example, if Delete is remapped to C-d, which deletes
5239 forward, C-Delete is bound to `kill-word', but if Delete is remapped
5240 to DEL, which deletes backward, C-Delete is bound to
5241 `backward-kill-word'.
5243 If not running on a window system, a similar effect is accomplished by
5244 remapping C-h (normally produced by the Backspace key) and DEL via
5245 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5246 to C-d; if it's off, the keys are not remapped.
5248 When not running on a window system, and this mode is turned on, the
5249 former functionality of C-h is available on the F1 key. You should
5250 probably not turn on this mode on a text-only terminal if you don't
5251 have both Backspace, Delete and F1 keys.
5253 See also `normal-erase-is-backspace'."
5255 (setq normal-erase-is-backspace
5257 (> (prefix-numeric-value arg) 0)
5258 (not normal-erase-is-backspace)))
5260 (cond ((or (memq window-system '(x w32 mac pc))
5261 (memq system-type '(ms-dos windows-nt)))
5263 `(([C-delete] [C-backspace])
5264 ([M-delete] [M-backspace])
5265 ([C-M-delete] [C-M-backspace])
5267 [C-delete] [C-backspace])))
5268 (old-state (lookup-key function-key-map [delete])))
5270 (if normal-erase-is-backspace
5272 (define-key function-key-map [delete] [?\C-d])
5273 (define-key function-key-map [kp-delete] [?\C-d])
5274 (define-key function-key-map [backspace] [?\C-?]))
5275 (define-key function-key-map [delete] [?\C-?])
5276 (define-key function-key-map [kp-delete] [?\C-?])
5277 (define-key function-key-map [backspace] [?\C-?]))
5279 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5280 (unless (equal old-state (lookup-key function-key-map [delete]))
5281 (dolist (binding bindings)
5282 (let ((map global-map))
5283 (when (keymapp (car binding))
5284 (setq map (car binding) binding (cdr binding)))
5285 (let* ((key1 (nth 0 binding))
5286 (key2 (nth 1 binding))
5287 (binding1 (lookup-key map key1))
5288 (binding2 (lookup-key map key2)))
5289 (define-key map key1 binding2)
5290 (define-key map key2 binding1)))))))
5292 (if normal-erase-is-backspace
5294 (keyboard-translate ?\C-h ?\C-?)
5295 (keyboard-translate ?\C-? ?\C-d))
5296 (keyboard-translate ?\C-h ?\C-h)
5297 (keyboard-translate ?\C-? ?\C-?))))
5299 (run-hooks 'normal-erase-is-backspace-hook)
5301 (message "Delete key deletes %s"
5302 (if normal-erase-is-backspace "forward" "backward"))))
5304 (defvar vis-mode-saved-buffer-invisibility-spec nil
5305 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
5307 (define-minor-mode visible-mode
5308 "Toggle Visible mode.
5309 With argument ARG turn Visible mode on iff ARG is positive.
5311 Enabling Visible mode makes all invisible text temporarily visible.
5312 Disabling Visible mode turns off that effect. Visible mode
5313 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
5315 :group 'editing-basics
5316 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
5317 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
5318 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
5320 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
5321 buffer-invisibility-spec)
5322 (setq buffer-invisibility-spec nil)))
5324 ;; Minibuffer prompt stuff.
5326 ;(defun minibuffer-prompt-modification (start end)
5327 ; (error "You cannot modify the prompt"))
5330 ;(defun minibuffer-prompt-insertion (start end)
5331 ; (let ((inhibit-modification-hooks t))
5332 ; (delete-region start end)
5333 ; ;; Discard undo information for the text insertion itself
5334 ; ;; and for the text deletion.above.
5335 ; (when (consp buffer-undo-list)
5336 ; (setq buffer-undo-list (cddr buffer-undo-list)))
5337 ; (message "You cannot modify the prompt")))
5340 ;(setq minibuffer-prompt-properties
5341 ; (list 'modification-hooks '(minibuffer-prompt-modification)
5342 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
5347 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
5348 ;;; simple.el ends here