Fix brainos.
[emacs.git] / lisp / simple.el
blobd0dcbbfc42ccc9a1e352aaf696a1c9c1b9ff59f9
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.
7 ;; Maintainer: FSF
8 ;; Keywords: internal
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)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
27 ;;; Commentary:
29 ;; A grab-bag of basic Emacs commands not specifically related to some
30 ;; major mode or to file-handling.
32 ;;; Code:
34 (eval-when-compile
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."
42 :type 'number
43 :group 'display
44 :version "22.1")
46 (defgroup killing nil
47 "Killing and yanking commands."
48 :group 'editing)
50 (defgroup paren-matching nil
51 "Highlight (un)matching of parens and expressions."
52 :group 'matching)
54 (defun next-buffer ()
55 "Switch to the next buffer in cyclic order."
56 (interactive)
57 (let ((buffer (current-buffer)))
58 (switch-to-buffer (other-buffer buffer))
59 (bury-buffer buffer)))
61 (defun prev-buffer ()
62 "Switch to the previous buffer in cyclic order."
63 (interactive)
64 (let ((list (nreverse (buffer-list)))
65 found)
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))))
70 (setq found 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."
78 :group 'compilation
79 :version "22.1")
81 (defface next-error
82 '((t (:inherit region)))
83 "Face used to highlight next error locus."
84 :group 'next-error
85 :version "22.1")
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))
97 :group 'next-error
98 :version "22.1")
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))
110 :group 'next-error
111 :version "22.1")
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
133 to navigate in it.")
135 (make-variable-buffer-local 'next-error-function)
137 (defsubst next-error-buffer-p (buffer
138 &optional avoid-current
139 extra-test-inclusive
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
166 extra-test-inclusive
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
182 (delete-dups
183 (delq nil (mapcar (lambda (w)
184 (if (next-error-buffer-p
185 (window-buffer w)
186 avoid-current
187 extra-test-inclusive extra-test-exclusive)
188 (window-buffer w)))
189 (window-list))))))
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)
200 (current-buffer))
201 ;; 4. Look for any acceptable buffer.
202 (let ((buffers (buffer-list)))
203 (while (and buffers
204 (not (next-error-buffer-p
205 (car buffers) avoid-current
206 extra-test-inclusive extra-test-exclusive)))
207 (setq buffers (cdr buffers)))
208 (car buffers))
209 ;; 5. Use the current buffer as a last resort if it qualifies,
210 ;; even despite AVOID-CURRENT.
211 (and avoid-current
212 (next-error-buffer-p (current-buffer) nil
213 extra-test-inclusive extra-test-exclusive)
214 (progn
215 (message "This is the only next-error capable buffer")
216 (current-buffer)))
217 ;; 6. Give up.
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."
249 (interactive "P")
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."
266 (interactive "p")
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."
274 (interactive "p")
275 (next-error n t))
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."
283 (interactive "p")
284 (let ((next-error-highlight next-error-highlight-no-select))
285 (next-error n))
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."
294 (interactive "p")
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
304 location."
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))
316 (condition-case nil
317 (let ((compilation-context-lines nil))
318 (setq compilation-current-error (point))
319 (next-error-no-select 0))
320 (error t))))
325 (defun fundamental-mode ()
326 "Major mode not specialized for anything in particular.
327 Other major modes are defined by comparison with this one."
328 (interactive)
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."
342 (interactive "*P")
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))
349 (bolp)
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))
361 (or (eobp)
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)
372 (- (point) 2))))
373 (was-page-start (and (bolp)
374 (looking-at page-delimiter)))
375 (beforepos (point)))
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)))
384 (unwind-protect
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.
398 (or flag
399 (save-excursion
400 (goto-char beforepos)
401 (beginning-of-line)
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.
408 (or was-page-start
409 (move-to-left-margin nil t)))
410 nil)
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)))))
420 (defun open-line (n)
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."
425 (interactive "*p")
426 (let* ((do-fill-prefix (and fill-prefix (bolp)))
427 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
428 (loc (point))
429 ;; Don't expand an abbrev before point.
430 (abbrev-mode nil))
431 (newline n)
432 (goto-char loc)
433 (while (> n 0)
434 (cond ((bolp)
435 (if do-left-margin (indent-to (current-left-margin)))
436 (if do-fill-prefix (insert-and-inherit fill-prefix))))
437 (forward-line 1)
438 (setq n (1- n)))
439 (goto-char loc)
440 (end-of-line)))
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."
448 (interactive "*P")
449 (skip-chars-forward " \t")
450 (let* ((col (current-column))
451 (pos (point))
452 ;; What prefix should we check for (nil means don't).
453 (prefix (cond ((stringp arg) arg)
454 (arg nil)
455 (t fill-prefix)))
456 ;; Does this line start with it?
457 (have-prfx (and prefix
458 (save-excursion
459 (beginning-of-line)
460 (looking-at (regexp-quote prefix))))))
461 (newline 1)
462 (if have-prfx (insert-and-inherit prefix))
463 (indent-to col 0)
464 (goto-char pos)))
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."
470 (interactive "*P")
471 (beginning-of-line)
472 (if arg (forward-line 1))
473 (if (eq (preceding-char) ?\n)
474 (progn
475 (delete-region (point) (1- (point)))
476 ;; If the second line started with the fill prefix,
477 ;; delete the prefix.
478 (if (and fill-prefix
479 (<= (+ (point) (length fill-prefix)) (point-max))
480 (string= fill-prefix
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."
492 (interactive "*")
493 (let (thisblank singleblank)
494 (save-excursion
495 (beginning-of-line)
496 (setq thisblank (looking-at "[ \t]*$"))
497 ;; Set singleblank if there is just one blank line here.
498 (setq singleblank
499 (and thisblank
500 (not (looking-at "[ \t]*\n[ \t]*$"))
501 (or (bobp)
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.
505 (if thisblank
506 (progn
507 (beginning-of-line)
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))
512 (point-min)))))
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))
516 (save-excursion
517 (end-of-line)
518 (forward-line 1)
519 (delete-region (point)
520 (if (re-search-forward "[^ \t\n]" nil t)
521 (progn (beginning-of-line) (point))
522 (point-max)))))
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."
533 (interactive "*")
534 (save-match-data
535 (save-excursion
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.
540 (save-match-data
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'."
551 (interactive "*")
552 (delete-horizontal-space t)
553 (newline)
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'."
563 (interactive "*")
564 (let ((pos (point)))
565 ;; Be careful to insert the newline before indenting the line.
566 ;; Otherwise, the indentation might be wrong.
567 (newline)
568 (save-excursion
569 (goto-char pos)
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."
593 (interactive "*p")
594 (let* ((char (let (translation-table-for-input)
595 (if (or (not overwrite-mode)
596 (eq overwrite-mode 'overwrite-mode-binary))
597 (read-quoted-char)
598 (read-char)))))
599 ;; Assume character codes 0240 - 0377 stand for characters in some
600 ;; single-byte character set, and convert them to Emacs
601 ;; characters.
602 (if (and enable-multibyte-characters
603 (>= char ?\240)
604 (<= char ?\377))
605 (setq char (unibyte-char-to-multibyte char)))
606 (if (> arg 0)
607 (if (eq overwrite-mode 'overwrite-mode-binary)
608 (delete-char arg)))
609 (while (> arg 0)
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."
615 (interactive "p")
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."
621 (interactive "p")
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."
627 (interactive)
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."
636 (interactive "*")
637 (save-excursion
638 (delete-horizontal-space)
639 (if (or (looking-at "^\\|\\s)")
640 (save-excursion (forward-char -1)
641 (looking-at "$\\|\\s(\\|\\s'")))
643 (insert ?\ ))))
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."
648 (interactive "*")
649 (let ((orig-pos (point)))
650 (delete-region
651 (if backward-only
652 orig-pos
653 (progn
654 (skip-chars-forward " \t")
655 (constrain-to-field nil orig-pos t)))
656 (progn
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)."
662 (interactive "*p")
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) ?\ )
668 (forward-char 1)
669 (insert ?\ )))
670 (delete-region
671 (point)
672 (progn
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."
686 (interactive "P")
687 (or (consp arg)
688 (and transient-mark-mode mark-active)
689 (push-mark))
690 (let ((size (- (point-max) (point-min))))
691 (goto-char (if (and arg (not (consp arg)))
692 (+ (point-min)
693 (if (> size 10000)
694 ;; Avoid overflow for large buffer sizes!
695 (* (prefix-numeric-value arg)
696 (/ size 10))
697 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
698 (point-min))))
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."
711 (interactive "P")
712 (or (consp arg)
713 (and transient-mark-mode mark-active)
714 (push-mark))
715 (let ((size (- (point-max) (point-min))))
716 (goto-char (if (and arg (not (consp arg)))
717 (- (point-max)
718 (if (> size 10000)
719 ;; Avoid overflow for large buffer sizes!
720 (* (prefix-numeric-value arg)
721 (/ size 10))
722 (/ (* size (prefix-numeric-value arg)) 10)))
723 (point-max))))
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))
731 (recenter -3))))
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."
738 (interactive)
739 (push-mark (point))
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."
754 (interactive
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.
758 (let* ((default
759 (save-excursion
760 (skip-chars-backward "0-9")
761 (if (looking-at "[0-9]")
762 (buffer-substring-no-properties
763 (point)
764 (progn (skip-chars-forward "0-9")
765 (point))))))
766 ;; Decide if we're switching buffers.
767 (buffer
768 (if (consp current-prefix-arg)
769 (other-buffer (current-buffer) t)))
770 (buffer-prompt
771 (if buffer
772 (concat " in " (buffer-name buffer))
773 "")))
774 ;; Read the argument, offering that number (if any) as default.
775 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
776 "Goto line%s: ")
777 buffer-prompt
778 default)
779 nil nil t
780 'minibuffer-history
781 default)
782 buffer))))
783 ;; Switch to the desired buffer, one way or another.
784 (if buffer
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.
789 (save-restriction
790 (widen)
791 (goto-char 1)
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."
798 (interactive "r")
799 (message "Region has %d lines, %d characters"
800 (count-lines start end) (- end start)))
802 (defun what-line ()
803 "Print the current buffer line number and narrowed line number of point."
804 (interactive)
805 (let ((start (point-min))
806 (n (line-number-at-pos)))
807 (if (= start 1)
808 (message "Line %d" n)
809 (save-excursion
810 (save-restriction
811 (widen)
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."
820 (save-excursion
821 (save-restriction
822 (narrow-to-region start end)
823 (goto-char (point-min))
824 (if (eq selective-display t)
825 (save-match-data
826 (let ((done 0))
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)
833 (not (bolp)))
834 (1+ done)
835 done)))
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)
842 (save-excursion
843 (goto-char (point-min))
844 (setq start (point))
845 (goto-char opoint)
846 (forward-line 0)
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'."
862 (interactive "P")
863 (let* ((char (following-char))
864 (beg (point-min))
865 (end (point-max))
866 (pos (point))
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)))
876 (if (= pos end)
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)
884 (if (or (not coding)
885 (eq (coding-system-type coding) t))
886 (setq coding default-buffer-file-coding-system))
887 (if (not (char-valid-p char))
888 (setq encoding-msg
889 (format "(0%o, %d, 0x%x, invalid)" char char char))
890 (setq encoded (and (>= char 128) (encode-coding-char char coding)))
891 (setq encoding-msg
892 (if encoded
893 (format "(0%o, %d, 0x%x, file %s)"
894 char char char
895 (if (> (length encoded) 1)
896 "..."
897 (encoded-string-description encoded coding)))
898 (format "(0%o, %d, 0x%x)" char char char))))
899 (if detail
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"
904 (if (< char 256)
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"
909 (if (< char 256)
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."
926 :group 'lisp
927 :type '(choice (const :tag "No Limit" nil) integer)
928 :version "21.1")
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."
933 :group 'lisp
934 :type '(choice (const :tag "No Limit" nil) integer)
935 :version "21.1")
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'."
940 :group 'lisp
941 :type 'boolean
942 :version "21.1")
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)))
953 (let ((char-string
954 (if (or (if (boundp 'edebug-active) edebug-active)
955 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
956 (prin1-char value))))
957 (if char-string
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
969 the echo area."
970 (interactive
971 (list (read-from-minibuffer "Eval: "
972 nil read-expression-map t
973 'read-expression-history)
974 current-prefix-arg))
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
992 (with-no-warnings
993 (let ((standard-output (current-buffer)))
994 (eval-last-sexp-print-value (car values))))
995 (prog1
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."
1004 (let ((command
1005 (let ((print-level nil)
1006 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1007 (unwind-protect
1008 (read-from-minibuffer prompt
1009 (prin1-to-string command)
1010 read-expression-map t
1011 'command-history)
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)))
1021 (eval command)))
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."
1032 (interactive "p")
1033 (let ((elt (nth (1- arg) command-history))
1034 newcmd)
1035 (if elt
1036 (progn
1037 (setq newcmd
1038 (let ((print-level nil)
1039 (minibuffer-history-position arg)
1040 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1041 (unwind-protect
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)))
1056 (eval newcmd))
1057 (if 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)
1095 :group 'minibuffer)
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'."
1106 (interactive
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"))
1119 regexp)
1120 (prefix-numeric-value current-prefix-arg))))
1121 (unless (zerop n)
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))
1127 (case-fold-search
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:
1134 case-fold-search)
1135 nil))
1136 prevpos
1137 match-string
1138 match-offset
1139 (pos minibuffer-history-position))
1140 (while (/= n 0)
1141 (setq prevpos pos)
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")))
1147 (setq match-string
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)))
1152 (setq match-offset
1153 (if (< n 0)
1154 (and (string-match regexp match-string)
1155 (match-end 0))
1156 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1157 (match-beginning 1))))
1158 (when match-offset
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."
1177 (interactive
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"))
1190 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."
1198 (interactive "p")
1199 (or (zerop n)
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)
1218 ((eobp) nil)
1219 (t (point))))))
1220 (goto-char (point-max))
1221 (delete-minibuffer-contents)
1222 (setq minibuffer-history-position narg)
1223 (cond ((= narg -1)
1224 (setq elt minibuffer-default))
1225 ((= narg 0)
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)))))
1231 (insert
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))
1236 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."
1241 (interactive "p")
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."
1248 (interactive "p")
1249 (let ((point-at-start (point)))
1250 (next-matching-history-element
1251 (concat
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."
1264 (interactive "p")
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."
1301 (interactive "*P")
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)))))
1327 (if undo-in-region
1328 (undo-start (region-beginning) (region-end))
1329 (undo-start))
1330 ;; get rid of initial undo boundary
1331 (undo-more 1))
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)))
1347 (undo-more
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)
1358 undo-equiv-table)
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)
1362 (prev nil))
1363 (while (car tail)
1364 (when (integerp (car tail))
1365 (let ((pos (car tail)))
1366 (if prev
1367 (setcdr prev (cdr tail))
1368 (setq buffer-undo-list (cdr tail)))
1369 (setq tail (cdr tail))
1370 (while (car tail)
1371 (if (eq pos (car tail))
1372 (if prev
1373 (setcdr prev (cdr tail))
1374 (setq buffer-undo-list (cdr tail)))
1375 (setq prev tail))
1376 (setq tail (cdr tail)))
1377 (setq tail nil)))
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."
1387 (interactive)
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."
1396 (interactive "*p")
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
1410 " for region"))))
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)
1422 (if (consp elt)
1423 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1424 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))
1437 buffer-undo-list)))
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
1450 some-rejected
1451 undo-elt undo-elt temp-undo-list delta)
1452 (while undo-list-copy
1453 (setq undo-elt (car undo-list-copy))
1454 (let ((keep-this
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)))))
1461 (if keep-this
1462 (progn
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)
1466 (eq undo-elt 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
1483 ;; output
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))
1499 ;; (BEGIN . END)
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)
1518 (<= undo-elt end)))
1519 ((eq undo-elt nil)
1521 ((atom undo-elt)
1522 nil)
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)))
1531 (unless alist-elt
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))
1545 ;; (BEGIN . END)
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))
1560 ;; (BEGIN . END)
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*
1566 ;; the undo.
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))
1573 ;; (BEGIN . END)
1574 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1576 '(0 . 0)))
1577 '(0 . 0)))
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."
1592 :type 'boolean
1593 :group 'undo
1594 :version "22.1")
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
1608 ;; lot of consing.
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)
1626 nil))
1627 (display-warning '(undo discard-info)
1628 (concat
1629 (format "Buffer %s undo info was %d bytes long.\n"
1630 (buffer-name) size)
1631 "The undo info was discarded because it exceeded \
1632 `undo-outer-limit'.
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")
1646 :warning)
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
1701 of the output.
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)
1714 current-prefix-arg
1715 shell-command-default-error-buffer))
1716 ;; Look for a handler in case default-directory is a remote file name.
1717 (let ((handler
1718 (find-file-name-handler (directory-file-name default-directory)
1719 'shell-command)))
1720 (if handler
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.
1725 (let ((error-file
1726 (if error-buffer
1727 (make-temp-file
1728 (expand-file-name "scor"
1729 (or small-temporary-file-directory
1730 temporary-file-directory)))
1731 nil)))
1732 (barf-if-buffer-read-only)
1733 (push-mark nil t)
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
1740 (if error-file
1741 (list t error-file)
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))))
1748 (or (bobp)
1749 (insert "\f\n"))
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.
1767 (save-match-data
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)
1773 proc)
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))
1778 (if proc
1779 (if (yes-or-no-p "A command is running. Kill it? ")
1780 (kill-process proc)
1781 (error "Shell command in progress")))
1782 (with-current-buffer buffer
1783 (setq buffer-read-only nil)
1784 (erase-buffer)
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)))))
1824 ;; General case
1825 (with-current-buffer
1826 (if (bufferp message)
1827 message
1828 (get-buffer-create (or buffer-name "*Message*")))
1830 (unless (bufferp message)
1831 (erase-buffer)
1832 (insert message))
1834 (let ((lines
1835 (if (= (buffer-size) 0)
1837 (count-lines (point-min) (point-max)))))
1838 (cond ((= lines 0))
1839 ((and (or (<= lines 1)
1840 (<= lines
1841 (if resize-mini-windows
1842 (cond ((floatp max-mini-window-height)
1843 (* (frame-height)
1844 max-mini-window-height))
1845 ((integerp max-mini-window-height)
1846 max-mini-window-height)
1849 1)))
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))))
1853 ;; Echo area
1854 (goto-char (point-max))
1855 (when (bolp)
1856 (backward-char 1))
1857 (message "%s" (buffer-substring (point-min) (point))))
1859 ;; Buffer
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))
1869 (message "%s: %s."
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
1879 COMMAND.
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
1916 around it.
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)
1926 (unless (mark)
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: "
1932 nil nil nil
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)
1937 string
1938 current-prefix-arg
1939 current-prefix-arg
1940 shell-command-default-error-buffer
1941 t)))
1942 (let ((error-file
1943 (if error-buffer
1944 (make-temp-file
1945 (expand-file-name "scor"
1946 (or small-temporary-file-directory
1947 temporary-file-directory)))
1948 nil))
1949 exit-status)
1950 (if (or replace
1951 (and output-buffer
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.
1956 (goto-char start)
1957 (and replace (push-mark (point) 'nomsg))
1958 (setq exit-status
1959 (call-process-region start end shell-file-name t
1960 (if error-file
1961 (list t error-file)
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*"))))
1974 (unwind-protect
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))
1982 (setq exit-status
1983 (call-process-region (point-min) (point-max)
1984 shell-file-name t
1985 (if error-file
1986 (list t error-file)
1988 nil shell-command-switch
1989 command)))
1990 ;; Clear the output buffer, then run the command with
1991 ;; output there.
1992 (let ((directory default-directory))
1993 (save-excursion
1994 (set-buffer buffer)
1995 (setq buffer-read-only nil)
1996 (if (not output-buffer)
1997 (setq default-directory directory))
1998 (erase-buffer)))
1999 (setq exit-status
2000 (call-process-region start end shell-file-name nil
2001 (if error-file
2002 (list buffer error-file)
2003 buffer)
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)
2009 " - Error")
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?
2018 (let ((output
2019 (if (and error-file
2020 (< 0 (nth 7 (file-attributes error-file))))
2021 "some error output"
2022 "no output")))
2023 (cond ((null exit-status)
2024 (message "(Shell command failed with error)"))
2025 ((equal 0 exit-status)
2026 (message "(Shell command succeeded with %s)"
2027 output))
2028 ((stringp exit-status)
2029 (message "(Shell command killed by signal %s)"
2030 exit-status))
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)
2036 ))))
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))))
2042 (or (bobp)
2043 (insert "\f\n"))
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))
2053 exit-status))
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
2059 standard-output
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
2072 and BUFFER.\)
2074 Some file handlers might not support all variants, for example
2075 they might behave as if DISPLAY was nil, regardless of the actual
2076 value passed."
2077 (let ((fh (find-file-name-handler default-directory 'process-file))
2078 lc stderr-file)
2079 (unwind-protect
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")))
2084 (prog1
2085 (apply 'call-process program
2086 (or lc infile)
2087 (if stderr-file (list (car buffer) stderr-file) buffer)
2088 display args)
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)
2123 map)
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
2137 argument mode\".")
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]."
2161 (interactive)
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)
2169 (interactive "P")
2170 (if (consp arg)
2171 (setq prefix-arg (list (* 4 (car arg))))
2172 (if (eq 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."
2181 (interactive "P")
2182 (cond ((integerp arg)
2183 (setq prefix-arg (- arg)))
2184 ((eq 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."
2194 (interactive "P")
2195 (let* ((char (if (integerp last-command-char)
2196 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))))
2202 ((eq arg '-)
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)
2213 (interactive "P")
2214 (if (integerp 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)
2221 (interactive "P")
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
2249 from the buffer.
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."
2260 (save-excursion
2261 (goto-char beg)
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
2276 programs.
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 (defvar interprogram-paste-function nil
2285 "Function to call to get text cut from other programs.
2287 Most window systems provide some sort of facility for cutting and
2288 pasting text between the windows of different programs.
2289 This variable holds a function that Emacs calls to obtain
2290 text that other programs have provided for pasting.
2292 The function should be called with no arguments. If the function
2293 returns nil, then no other program has provided such text, and the top
2294 of the Emacs kill ring should be used. If the function returns a
2295 string, then the caller of the function \(usually `current-kill')
2296 should put this string in the kill ring as the latest kill.
2298 Note that the function should return a string only if a program other
2299 than Emacs has provided a string for pasting; if Emacs provided the
2300 most recent string, the function should return nil. If it is
2301 difficult to tell whether Emacs or some other program provided the
2302 current string, it is probably good enough to return nil if the string
2303 is equal (according to `string=') to the last text Emacs provided.")
2307 ;;;; The kill ring data structure.
2309 (defvar kill-ring nil
2310 "List of killed text sequences.
2311 Since the kill ring is supposed to interact nicely with cut-and-paste
2312 facilities offered by window systems, use of this variable should
2313 interact nicely with `interprogram-cut-function' and
2314 `interprogram-paste-function'. The functions `kill-new',
2315 `kill-append', and `current-kill' are supposed to implement this
2316 interaction; you may want to use them instead of manipulating the kill
2317 ring directly.")
2319 (defcustom kill-ring-max 60
2320 "*Maximum length of kill ring before oldest elements are thrown away."
2321 :type 'integer
2322 :group 'killing)
2324 (defvar kill-ring-yank-pointer nil
2325 "The tail of the kill ring whose car is the last thing yanked.")
2327 (defun kill-new (string &optional replace yank-handler)
2328 "Make STRING the latest kill in the kill ring.
2329 Set `kill-ring-yank-pointer' to point to it.
2330 If `interprogram-cut-function' is non-nil, apply it to STRING.
2331 Optional second argument REPLACE non-nil means that STRING will replace
2332 the front of the kill ring, rather than being added to the list.
2334 Optional third arguments YANK-HANDLER controls how the STRING is later
2335 inserted into a buffer; see `insert-for-yank' for details.
2336 When a yank handler is specified, STRING must be non-empty (the yank
2337 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2339 When the yank handler has a non-nil PARAM element, the original STRING
2340 argument is not used by `insert-for-yank'. However, since Lisp code
2341 may access and use elements from the kill-ring directly, the STRING
2342 argument should still be a \"useful\" string for such uses."
2343 (if (> (length string) 0)
2344 (if yank-handler
2345 (put-text-property 0 (length string)
2346 'yank-handler yank-handler string))
2347 (if yank-handler
2348 (signal 'args-out-of-range
2349 (list string "yank-handler specified for empty string"))))
2350 (if (fboundp 'menu-bar-update-yank-menu)
2351 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2352 (if (and replace kill-ring)
2353 (setcar kill-ring string)
2354 (setq kill-ring (cons string kill-ring))
2355 (if (> (length kill-ring) kill-ring-max)
2356 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2357 (setq kill-ring-yank-pointer kill-ring)
2358 (if interprogram-cut-function
2359 (funcall interprogram-cut-function string (not replace))))
2361 (defun kill-append (string before-p &optional yank-handler)
2362 "Append STRING to the end of the latest kill in the kill ring.
2363 If BEFORE-P is non-nil, prepend STRING to the kill.
2364 Optional third argument YANK-HANDLER, if non-nil, specifies the
2365 yank-handler text property to be set on the combined kill ring
2366 string. If the specified yank-handler arg differs from the
2367 yank-handler property of the latest kill string, this function
2368 adds the combined string to the kill ring as a new element,
2369 instead of replacing the last kill with it.
2370 If `interprogram-cut-function' is set, pass the resulting kill to it."
2371 (let* ((cur (car kill-ring)))
2372 (kill-new (if before-p (concat string cur) (concat cur string))
2373 (or (= (length cur) 0)
2374 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2375 yank-handler)))
2377 (defun current-kill (n &optional do-not-move)
2378 "Rotate the yanking point by N places, and then return that kill.
2379 If N is zero, `interprogram-paste-function' is set, and calling it
2380 returns a string, then that string is added to the front of the
2381 kill ring and returned as the latest kill.
2382 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
2383 yanking point; just return the Nth kill forward."
2384 (let ((interprogram-paste (and (= n 0)
2385 interprogram-paste-function
2386 (funcall interprogram-paste-function))))
2387 (if interprogram-paste
2388 (progn
2389 ;; Disable the interprogram cut function when we add the new
2390 ;; text to the kill ring, so Emacs doesn't try to own the
2391 ;; selection, with identical text.
2392 (let ((interprogram-cut-function nil))
2393 (kill-new interprogram-paste))
2394 interprogram-paste)
2395 (or kill-ring (error "Kill ring is empty"))
2396 (let ((ARGth-kill-element
2397 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2398 (length kill-ring))
2399 kill-ring)))
2400 (or do-not-move
2401 (setq kill-ring-yank-pointer ARGth-kill-element))
2402 (car ARGth-kill-element)))))
2406 ;;;; Commands for manipulating the kill ring.
2408 (defcustom kill-read-only-ok nil
2409 "*Non-nil means don't signal an error for killing read-only text."
2410 :type 'boolean
2411 :group 'killing)
2413 (put 'text-read-only 'error-conditions
2414 '(text-read-only buffer-read-only error))
2415 (put 'text-read-only 'error-message "Text is read-only")
2417 (defun kill-region (beg end &optional yank-handler)
2418 "Kill between point and mark.
2419 The text is deleted but saved in the kill ring.
2420 The command \\[yank] can retrieve it from there.
2421 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2423 If you want to append the killed region to the last killed text,
2424 use \\[append-next-kill] before \\[kill-region].
2426 If the buffer is read-only, Emacs will beep and refrain from deleting
2427 the text, but put the text in the kill ring anyway. This means that
2428 you can use the killing commands to copy text from a read-only buffer.
2430 This is the primitive for programs to kill text (as opposed to deleting it).
2431 Supply two arguments, character positions indicating the stretch of text
2432 to be killed.
2433 Any command that calls this function is a \"kill command\".
2434 If the previous command was also a kill command,
2435 the text killed this time appends to the text killed last time
2436 to make one entry in the kill ring.
2438 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2439 specifies the yank-handler text property to be set on the killed
2440 text. See `insert-for-yank'."
2441 (interactive "r")
2442 (condition-case nil
2443 (let ((string (filter-buffer-substring beg end t)))
2444 (when string ;STRING is nil if BEG = END
2445 ;; Add that string to the kill ring, one way or another.
2446 (if (eq last-command 'kill-region)
2447 (kill-append string (< end beg) yank-handler)
2448 (kill-new string nil yank-handler)))
2449 (when (or string (eq last-command 'kill-region))
2450 (setq this-command 'kill-region))
2451 nil)
2452 ((buffer-read-only text-read-only)
2453 ;; The code above failed because the buffer, or some of the characters
2454 ;; in the region, are read-only.
2455 ;; We should beep, in case the user just isn't aware of this.
2456 ;; However, there's no harm in putting
2457 ;; the region's text in the kill ring, anyway.
2458 (copy-region-as-kill beg end)
2459 ;; Set this-command now, so it will be set even if we get an error.
2460 (setq this-command 'kill-region)
2461 ;; This should barf, if appropriate, and give us the correct error.
2462 (if kill-read-only-ok
2463 (progn (message "Read only text copied to kill ring") nil)
2464 ;; Signal an error if the buffer is read-only.
2465 (barf-if-buffer-read-only)
2466 ;; If the buffer isn't read-only, the text is.
2467 (signal 'text-read-only (list (current-buffer)))))))
2469 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2470 ;; to get two copies of the text when the user accidentally types M-w and
2471 ;; then corrects it with the intended C-w.
2472 (defun copy-region-as-kill (beg end)
2473 "Save the region as if killed, but don't kill it.
2474 In Transient Mark mode, deactivate the mark.
2475 If `interprogram-cut-function' is non-nil, also save the text for a window
2476 system cut and paste."
2477 (interactive "r")
2478 (if (eq last-command 'kill-region)
2479 (kill-append (filter-buffer-substring beg end) (< end beg))
2480 (kill-new (filter-buffer-substring beg end)))
2481 (if transient-mark-mode
2482 (setq deactivate-mark t))
2483 nil)
2485 (defun kill-ring-save (beg end)
2486 "Save the region as if killed, but don't kill it.
2487 In Transient Mark mode, deactivate the mark.
2488 If `interprogram-cut-function' is non-nil, also save the text for a window
2489 system cut and paste.
2491 If you want to append the killed line to the last killed text,
2492 use \\[append-next-kill] before \\[kill-ring-save].
2494 This command is similar to `copy-region-as-kill', except that it gives
2495 visual feedback indicating the extent of the region being copied."
2496 (interactive "r")
2497 (copy-region-as-kill beg end)
2498 ;; This use of interactive-p is correct
2499 ;; because the code it controls just gives the user visual feedback.
2500 (if (interactive-p)
2501 (let ((other-end (if (= (point) beg) end beg))
2502 (opoint (point))
2503 ;; Inhibit quitting so we can make a quit here
2504 ;; look like a C-g typed as a command.
2505 (inhibit-quit t))
2506 (if (pos-visible-in-window-p other-end (selected-window))
2507 (unless (and transient-mark-mode
2508 (face-background 'region))
2509 ;; Swap point and mark.
2510 (set-marker (mark-marker) (point) (current-buffer))
2511 (goto-char other-end)
2512 (sit-for blink-matching-delay)
2513 ;; Swap back.
2514 (set-marker (mark-marker) other-end (current-buffer))
2515 (goto-char opoint)
2516 ;; If user quit, deactivate the mark
2517 ;; as C-g would as a command.
2518 (and quit-flag mark-active
2519 (deactivate-mark)))
2520 (let* ((killed-text (current-kill 0))
2521 (message-len (min (length killed-text) 40)))
2522 (if (= (point) beg)
2523 ;; Don't say "killed"; that is misleading.
2524 (message "Saved text until \"%s\""
2525 (substring killed-text (- message-len)))
2526 (message "Saved text from \"%s\""
2527 (substring killed-text 0 message-len))))))))
2529 (defun append-next-kill (&optional interactive)
2530 "Cause following command, if it kills, to append to previous kill.
2531 The argument is used for internal purposes; do not supply one."
2532 (interactive "p")
2533 ;; We don't use (interactive-p), since that breaks kbd macros.
2534 (if interactive
2535 (progn
2536 (setq this-command 'kill-region)
2537 (message "If the next command is a kill, it will append"))
2538 (setq last-command 'kill-region)))
2540 ;; Yanking.
2542 ;; This is actually used in subr.el but defcustom does not work there.
2543 (defcustom yank-excluded-properties
2544 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2545 yank-handler follow-link)
2546 "*Text properties to discard when yanking.
2547 The value should be a list of text properties to discard or t,
2548 which means to discard all text properties."
2549 :type '(choice (const :tag "All" t) (repeat symbol))
2550 :group 'killing
2551 :version "22.1")
2553 (defvar yank-window-start nil)
2554 (defvar yank-undo-function nil
2555 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2556 Function is called with two parameters, START and END corresponding to
2557 the value of the mark and point; it is guaranteed that START <= END.
2558 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2560 (defun yank-pop (&optional arg)
2561 "Replace just-yanked stretch of killed text with a different stretch.
2562 This command is allowed only immediately after a `yank' or a `yank-pop'.
2563 At such a time, the region contains a stretch of reinserted
2564 previously-killed text. `yank-pop' deletes that text and inserts in its
2565 place a different stretch of killed text.
2567 With no argument, the previous kill is inserted.
2568 With argument N, insert the Nth previous kill.
2569 If N is negative, this is a more recent kill.
2571 The sequence of kills wraps around, so that after the oldest one
2572 comes the newest one.
2574 When this command inserts killed text into the buffer, it honors
2575 `yank-excluded-properties' and `yank-handler' as described in the
2576 doc string for `insert-for-yank-1', which see."
2577 (interactive "*p")
2578 (if (not (eq last-command 'yank))
2579 (error "Previous command was not a yank"))
2580 (setq this-command 'yank)
2581 (unless arg (setq arg 1))
2582 (let ((inhibit-read-only t)
2583 (before (< (point) (mark t))))
2584 (if before
2585 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2586 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2587 (setq yank-undo-function nil)
2588 (set-marker (mark-marker) (point) (current-buffer))
2589 (insert-for-yank (current-kill arg))
2590 ;; Set the window start back where it was in the yank command,
2591 ;; if possible.
2592 (set-window-start (selected-window) yank-window-start t)
2593 (if before
2594 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2595 ;; It is cleaner to avoid activation, even though the command
2596 ;; loop would deactivate the mark because we inserted text.
2597 (goto-char (prog1 (mark t)
2598 (set-marker (mark-marker) (point) (current-buffer))))))
2599 nil)
2601 (defun yank (&optional arg)
2602 "Reinsert the last stretch of killed text.
2603 More precisely, reinsert the stretch of killed text most recently
2604 killed OR yanked. Put point at end, and set mark at beginning.
2605 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2606 With argument N, reinsert the Nth most recently killed stretch of killed
2607 text.
2609 When this command inserts killed text into the buffer, it honors
2610 `yank-excluded-properties' and `yank-handler' as described in the
2611 doc string for `insert-for-yank-1', which see.
2613 See also the command \\[yank-pop]."
2614 (interactive "*P")
2615 (setq yank-window-start (window-start))
2616 ;; If we don't get all the way thru, make last-command indicate that
2617 ;; for the following command.
2618 (setq this-command t)
2619 (push-mark (point))
2620 (insert-for-yank (current-kill (cond
2621 ((listp arg) 0)
2622 ((eq arg '-) -2)
2623 (t (1- arg)))))
2624 (if (consp arg)
2625 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2626 ;; It is cleaner to avoid activation, even though the command
2627 ;; loop would deactivate the mark because we inserted text.
2628 (goto-char (prog1 (mark t)
2629 (set-marker (mark-marker) (point) (current-buffer)))))
2630 ;; If we do get all the way thru, make this-command indicate that.
2631 (if (eq this-command t)
2632 (setq this-command 'yank))
2633 nil)
2635 (defun rotate-yank-pointer (arg)
2636 "Rotate the yanking point in the kill ring.
2637 With argument, rotate that many kills forward (or backward, if negative)."
2638 (interactive "p")
2639 (current-kill arg))
2641 ;; Some kill commands.
2643 ;; Internal subroutine of delete-char
2644 (defun kill-forward-chars (arg)
2645 (if (listp arg) (setq arg (car arg)))
2646 (if (eq arg '-) (setq arg -1))
2647 (kill-region (point) (forward-point arg)))
2649 ;; Internal subroutine of backward-delete-char
2650 (defun kill-backward-chars (arg)
2651 (if (listp arg) (setq arg (car arg)))
2652 (if (eq arg '-) (setq arg -1))
2653 (kill-region (point) (forward-point (- arg))))
2655 (defcustom backward-delete-char-untabify-method 'untabify
2656 "*The method for untabifying when deleting backward.
2657 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2658 `hungry' -- delete all whitespace, both tabs and spaces;
2659 `all' -- delete all whitespace, including tabs, spaces and newlines;
2660 nil -- just delete one character."
2661 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2662 :version "20.3"
2663 :group 'killing)
2665 (defun backward-delete-char-untabify (arg &optional killp)
2666 "Delete characters backward, changing tabs into spaces.
2667 The exact behavior depends on `backward-delete-char-untabify-method'.
2668 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2669 Interactively, ARG is the prefix arg (default 1)
2670 and KILLP is t if a prefix arg was specified."
2671 (interactive "*p\nP")
2672 (when (eq backward-delete-char-untabify-method 'untabify)
2673 (let ((count arg))
2674 (save-excursion
2675 (while (and (> count 0) (not (bobp)))
2676 (if (= (preceding-char) ?\t)
2677 (let ((col (current-column)))
2678 (forward-char -1)
2679 (setq col (- col (current-column)))
2680 (insert-char ?\ col)
2681 (delete-char 1)))
2682 (forward-char -1)
2683 (setq count (1- count))))))
2684 (delete-backward-char
2685 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2686 ((eq backward-delete-char-untabify-method 'all)
2687 " \t\n\r"))))
2688 (if skip
2689 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2690 (point)))))
2691 (+ arg (if (zerop wh) 0 (1- wh))))
2692 arg))
2693 killp))
2695 (defun zap-to-char (arg char)
2696 "Kill up to and including ARG'th occurrence of CHAR.
2697 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2698 Goes backward if ARG is negative; error if CHAR not found."
2699 (interactive "p\ncZap to char: ")
2700 (kill-region (point) (progn
2701 (search-forward (char-to-string char) nil nil arg)
2702 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2703 (point))))
2705 ;; kill-line and its subroutines.
2707 (defcustom kill-whole-line nil
2708 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2709 :type 'boolean
2710 :group 'killing)
2712 (defun kill-line (&optional arg)
2713 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2714 With prefix argument, kill that many lines from point.
2715 Negative arguments kill lines backward.
2716 With zero argument, kills the text before point on the current line.
2718 When calling from a program, nil means \"no arg\",
2719 a number counts as a prefix arg.
2721 To kill a whole line, when point is not at the beginning, type \
2722 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2724 If `kill-whole-line' is non-nil, then this command kills the whole line
2725 including its terminating newline, when used at the beginning of a line
2726 with no argument. As a consequence, you can always kill a whole line
2727 by typing \\[beginning-of-line] \\[kill-line].
2729 If you want to append the killed line to the last killed text,
2730 use \\[append-next-kill] before \\[kill-line].
2732 If the buffer is read-only, Emacs will beep and refrain from deleting
2733 the line, but put the line in the kill ring anyway. This means that
2734 you can use this command to copy text from a read-only buffer.
2735 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2736 even beep.)"
2737 (interactive "P")
2738 (kill-region (point)
2739 ;; It is better to move point to the other end of the kill
2740 ;; before killing. That way, in a read-only buffer, point
2741 ;; moves across the text that is copied to the kill ring.
2742 ;; The choice has no effect on undo now that undo records
2743 ;; the value of point from before the command was run.
2744 (progn
2745 (if arg
2746 (forward-visible-line (prefix-numeric-value arg))
2747 (if (eobp)
2748 (signal 'end-of-buffer nil))
2749 (let ((end
2750 (save-excursion
2751 (end-of-visible-line) (point))))
2752 (if (or (save-excursion
2753 ;; If trailing whitespace is visible,
2754 ;; don't treat it as nothing.
2755 (unless show-trailing-whitespace
2756 (skip-chars-forward " \t" end))
2757 (= (point) end))
2758 (and kill-whole-line (bolp)))
2759 (forward-visible-line 1)
2760 (goto-char end))))
2761 (point))))
2763 (defun kill-whole-line (&optional arg)
2764 "Kill current line.
2765 With prefix arg, kill that many lines starting from the current line.
2766 If arg is negative, kill backward. Also kill the preceding newline.
2767 \(This is meant to make \\[repeat] work well with negative arguments.\)
2768 If arg is zero, kill current line but exclude the trailing newline."
2769 (interactive "p")
2770 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2771 (signal 'end-of-buffer nil))
2772 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2773 (signal 'beginning-of-buffer nil))
2774 (unless (eq last-command 'kill-region)
2775 (kill-new "")
2776 (setq last-command 'kill-region))
2777 (cond ((zerop arg)
2778 ;; We need to kill in two steps, because the previous command
2779 ;; could have been a kill command, in which case the text
2780 ;; before point needs to be prepended to the current kill
2781 ;; ring entry and the text after point appended. Also, we
2782 ;; need to use save-excursion to avoid copying the same text
2783 ;; twice to the kill ring in read-only buffers.
2784 (save-excursion
2785 (kill-region (point) (progn (forward-visible-line 0) (point))))
2786 (kill-region (point) (progn (end-of-visible-line) (point))))
2787 ((< arg 0)
2788 (save-excursion
2789 (kill-region (point) (progn (end-of-visible-line) (point))))
2790 (kill-region (point)
2791 (progn (forward-visible-line (1+ arg))
2792 (unless (bobp) (backward-char))
2793 (point))))
2795 (save-excursion
2796 (kill-region (point) (progn (forward-visible-line 0) (point))))
2797 (kill-region (point)
2798 (progn (forward-visible-line arg) (point))))))
2800 (defun forward-visible-line (arg)
2801 "Move forward by ARG lines, ignoring currently invisible newlines only.
2802 If ARG is negative, move backward -ARG lines.
2803 If ARG is zero, move to the beginning of the current line."
2804 (condition-case nil
2805 (if (> arg 0)
2806 (progn
2807 (while (> arg 0)
2808 (or (zerop (forward-line 1))
2809 (signal 'end-of-buffer nil))
2810 ;; If the newline we just skipped is invisible,
2811 ;; don't count it.
2812 (let ((prop
2813 (get-char-property (1- (point)) 'invisible)))
2814 (if (if (eq buffer-invisibility-spec t)
2815 prop
2816 (or (memq prop buffer-invisibility-spec)
2817 (assq prop buffer-invisibility-spec)))
2818 (setq arg (1+ arg))))
2819 (setq arg (1- arg)))
2820 ;; If invisible text follows, and it is a number of complete lines,
2821 ;; skip it.
2822 (let ((opoint (point)))
2823 (while (and (not (eobp))
2824 (let ((prop
2825 (get-char-property (point) 'invisible)))
2826 (if (eq buffer-invisibility-spec t)
2827 prop
2828 (or (memq prop buffer-invisibility-spec)
2829 (assq prop buffer-invisibility-spec)))))
2830 (goto-char
2831 (if (get-text-property (point) 'invisible)
2832 (or (next-single-property-change (point) 'invisible)
2833 (point-max))
2834 (next-overlay-change (point)))))
2835 (unless (bolp)
2836 (goto-char opoint))))
2837 (let ((first t))
2838 (while (or first (<= arg 0))
2839 (if first
2840 (beginning-of-line)
2841 (or (zerop (forward-line -1))
2842 (signal 'beginning-of-buffer nil)))
2843 ;; If the newline we just moved to is invisible,
2844 ;; don't count it.
2845 (unless (bobp)
2846 (let ((prop
2847 (get-char-property (1- (point)) 'invisible)))
2848 (unless (if (eq buffer-invisibility-spec t)
2849 prop
2850 (or (memq prop buffer-invisibility-spec)
2851 (assq prop buffer-invisibility-spec)))
2852 (setq arg (1+ arg)))))
2853 (setq first nil))
2854 ;; If invisible text follows, and it is a number of complete lines,
2855 ;; skip it.
2856 (let ((opoint (point)))
2857 (while (and (not (bobp))
2858 (let ((prop
2859 (get-char-property (1- (point)) 'invisible)))
2860 (if (eq buffer-invisibility-spec t)
2861 prop
2862 (or (memq prop buffer-invisibility-spec)
2863 (assq prop buffer-invisibility-spec)))))
2864 (goto-char
2865 (if (get-text-property (1- (point)) 'invisible)
2866 (or (previous-single-property-change (point) 'invisible)
2867 (point-min))
2868 (previous-overlay-change (point)))))
2869 (unless (bolp)
2870 (goto-char opoint)))))
2871 ((beginning-of-buffer end-of-buffer)
2872 nil)))
2874 (defun end-of-visible-line ()
2875 "Move to end of current visible line."
2876 (end-of-line)
2877 ;; If the following character is currently invisible,
2878 ;; skip all characters with that same `invisible' property value,
2879 ;; then find the next newline.
2880 (while (and (not (eobp))
2881 (save-excursion
2882 (skip-chars-forward "^\n")
2883 (let ((prop
2884 (get-char-property (point) 'invisible)))
2885 (if (eq buffer-invisibility-spec t)
2886 prop
2887 (or (memq prop buffer-invisibility-spec)
2888 (assq prop buffer-invisibility-spec))))))
2889 (skip-chars-forward "^\n")
2890 (if (get-text-property (point) 'invisible)
2891 (goto-char (next-single-property-change (point) 'invisible))
2892 (goto-char (next-overlay-change (point))))
2893 (end-of-line)))
2895 (defun insert-buffer (buffer)
2896 "Insert after point the contents of BUFFER.
2897 Puts mark after the inserted text.
2898 BUFFER may be a buffer or a buffer name.
2900 This function is meant for the user to run interactively.
2901 Don't call it from programs: use `insert-buffer-substring' instead!"
2902 (interactive
2903 (list
2904 (progn
2905 (barf-if-buffer-read-only)
2906 (read-buffer "Insert buffer: "
2907 (if (eq (selected-window) (next-window (selected-window)))
2908 (other-buffer (current-buffer))
2909 (window-buffer (next-window (selected-window))))
2910 t))))
2911 (push-mark
2912 (save-excursion
2913 (insert-buffer-substring (get-buffer buffer))
2914 (point)))
2915 nil)
2917 (defun append-to-buffer (buffer start end)
2918 "Append to specified buffer the text of the region.
2919 It is inserted into that buffer before its point.
2921 When calling from a program, give three arguments:
2922 BUFFER (or buffer name), START and END.
2923 START and END specify the portion of the current buffer to be copied."
2924 (interactive
2925 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
2926 (region-beginning) (region-end)))
2927 (let ((oldbuf (current-buffer)))
2928 (save-excursion
2929 (let* ((append-to (get-buffer-create buffer))
2930 (windows (get-buffer-window-list append-to t t))
2931 point)
2932 (set-buffer append-to)
2933 (setq point (point))
2934 (barf-if-buffer-read-only)
2935 (insert-buffer-substring oldbuf start end)
2936 (dolist (window windows)
2937 (when (= (window-point window) point)
2938 (set-window-point window (point))))))))
2940 (defun prepend-to-buffer (buffer start end)
2941 "Prepend to specified buffer the text of the region.
2942 It is inserted into that buffer after its point.
2944 When calling from a program, give three arguments:
2945 BUFFER (or buffer name), START and END.
2946 START and END specify the portion of the current buffer to be copied."
2947 (interactive "BPrepend to buffer: \nr")
2948 (let ((oldbuf (current-buffer)))
2949 (save-excursion
2950 (set-buffer (get-buffer-create buffer))
2951 (barf-if-buffer-read-only)
2952 (save-excursion
2953 (insert-buffer-substring oldbuf start end)))))
2955 (defun copy-to-buffer (buffer start end)
2956 "Copy to specified buffer the text of the region.
2957 It is inserted into that buffer, replacing existing text there.
2959 When calling from a program, give three arguments:
2960 BUFFER (or buffer name), START and END.
2961 START and END specify the portion of the current buffer to be copied."
2962 (interactive "BCopy to buffer: \nr")
2963 (let ((oldbuf (current-buffer)))
2964 (save-excursion
2965 (set-buffer (get-buffer-create buffer))
2966 (barf-if-buffer-read-only)
2967 (erase-buffer)
2968 (save-excursion
2969 (insert-buffer-substring oldbuf start end)))))
2971 (put 'mark-inactive 'error-conditions '(mark-inactive error))
2972 (put 'mark-inactive 'error-message "The mark is not active now")
2974 (defvar activate-mark-hook nil
2975 "Hook run when the mark becomes active.
2976 It is also run at the end of a command, if the mark is active and
2977 it is possible that the region may have changed")
2979 (defvar deactivate-mark-hook nil
2980 "Hook run when the mark becomes inactive.")
2982 (defun mark (&optional force)
2983 "Return this buffer's mark value as integer; error if mark inactive.
2984 If optional argument FORCE is non-nil, access the mark value
2985 even if the mark is not currently active, and return nil
2986 if there is no mark at all.
2988 If you are using this in an editing command, you are most likely making
2989 a mistake; see the documentation of `set-mark'."
2990 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
2991 (marker-position (mark-marker))
2992 (signal 'mark-inactive nil)))
2994 ;; Many places set mark-active directly, and several of them failed to also
2995 ;; run deactivate-mark-hook. This shorthand should simplify.
2996 (defsubst deactivate-mark ()
2997 "Deactivate the mark by setting `mark-active' to nil.
2998 \(That makes a difference only in Transient Mark mode.)
2999 Also runs the hook `deactivate-mark-hook'."
3000 (cond
3001 ((eq transient-mark-mode 'lambda)
3002 (setq transient-mark-mode nil))
3003 (transient-mark-mode
3004 (setq mark-active nil)
3005 (run-hooks 'deactivate-mark-hook))))
3007 (defun set-mark (pos)
3008 "Set this buffer's mark to POS. Don't use this function!
3009 That is to say, don't use this function unless you want
3010 the user to see that the mark has moved, and you want the previous
3011 mark position to be lost.
3013 Normally, when a new mark is set, the old one should go on the stack.
3014 This is why most applications should use `push-mark', not `set-mark'.
3016 Novice Emacs Lisp programmers often try to use the mark for the wrong
3017 purposes. The mark saves a location for the user's convenience.
3018 Most editing commands should not alter the mark.
3019 To remember a location for internal use in the Lisp program,
3020 store it in a Lisp variable. Example:
3022 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3024 (if pos
3025 (progn
3026 (setq mark-active t)
3027 (run-hooks 'activate-mark-hook)
3028 (set-marker (mark-marker) pos (current-buffer)))
3029 ;; Normally we never clear mark-active except in Transient Mark mode.
3030 ;; But when we actually clear out the mark value too,
3031 ;; we must clear mark-active in any mode.
3032 (setq mark-active nil)
3033 (run-hooks 'deactivate-mark-hook)
3034 (set-marker (mark-marker) nil)))
3036 (defvar mark-ring nil
3037 "The list of former marks of the current buffer, most recent first.")
3038 (make-variable-buffer-local 'mark-ring)
3039 (put 'mark-ring 'permanent-local t)
3041 (defcustom mark-ring-max 16
3042 "*Maximum size of mark ring. Start discarding off end if gets this big."
3043 :type 'integer
3044 :group 'editing-basics)
3046 (defvar global-mark-ring nil
3047 "The list of saved global marks, most recent first.")
3049 (defcustom global-mark-ring-max 16
3050 "*Maximum size of global mark ring. \
3051 Start discarding off end if gets this big."
3052 :type 'integer
3053 :group 'editing-basics)
3055 (defun pop-to-mark-command ()
3056 "Jump to mark, and pop a new position for mark off the ring
3057 \(does not affect global mark ring\)."
3058 (interactive)
3059 (if (null (mark t))
3060 (error "No mark set in this buffer")
3061 (goto-char (mark t))
3062 (pop-mark)))
3064 (defun push-mark-command (arg &optional nomsg)
3065 "Set mark at where point is.
3066 If no prefix arg and mark is already set there, just activate it.
3067 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3068 (interactive "P")
3069 (let ((mark (marker-position (mark-marker))))
3070 (if (or arg (null mark) (/= mark (point)))
3071 (push-mark nil nomsg t)
3072 (setq mark-active t)
3073 (run-hooks 'activate-mark-hook)
3074 (unless nomsg
3075 (message "Mark activated")))))
3077 (defun set-mark-command (arg)
3078 "Set mark at where point is, or jump to mark.
3079 With no prefix argument, set mark, and push old mark position on local
3080 mark ring; also push mark on global mark ring if last mark was set in
3081 another buffer. Immediately repeating the command activates
3082 `transient-mark-mode' temporarily.
3084 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
3085 jump to mark, and pop a new position
3086 for mark off the local mark ring \(this does not affect the global
3087 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
3088 mark ring \(see `pop-global-mark'\).
3090 Repeating the \\[set-mark-command] command without the prefix jumps to
3091 the next position off the local (or global) mark ring.
3093 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
3094 \\[universal-argument] \\[set-mark-command], unconditionally
3095 set mark where point is.
3097 Novice Emacs Lisp programmers often try to use the mark for the wrong
3098 purposes. See the documentation of `set-mark' for more information."
3099 (interactive "P")
3100 (if (eq transient-mark-mode 'lambda)
3101 (setq transient-mark-mode nil))
3102 (cond
3103 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3104 (push-mark-command nil))
3105 ((not (eq this-command 'set-mark-command))
3106 (if arg
3107 (pop-to-mark-command)
3108 (push-mark-command t)))
3109 ((eq last-command 'pop-to-mark-command)
3110 (setq this-command 'pop-to-mark-command)
3111 (pop-to-mark-command))
3112 ((and (eq last-command 'pop-global-mark) (not arg))
3113 (setq this-command 'pop-global-mark)
3114 (pop-global-mark))
3115 (arg
3116 (setq this-command 'pop-to-mark-command)
3117 (pop-to-mark-command))
3118 ((and (eq last-command 'set-mark-command)
3119 mark-active (null transient-mark-mode))
3120 (setq transient-mark-mode 'lambda)
3121 (message "Transient-mark-mode temporarily enabled"))
3123 (push-mark-command nil))))
3125 (defun push-mark (&optional location nomsg activate)
3126 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3127 If the last global mark pushed was not in the current buffer,
3128 also push LOCATION on the global mark ring.
3129 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3130 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
3132 Novice Emacs Lisp programmers often try to use the mark for the wrong
3133 purposes. See the documentation of `set-mark' for more information.
3135 In Transient Mark mode, this does not activate the mark."
3136 (unless (null (mark t))
3137 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3138 (when (> (length mark-ring) mark-ring-max)
3139 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3140 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3141 (set-marker (mark-marker) (or location (point)) (current-buffer))
3142 ;; Now push the mark on the global mark ring.
3143 (if (and global-mark-ring
3144 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3145 ;; The last global mark pushed was in this same buffer.
3146 ;; Don't push another one.
3148 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3149 (when (> (length global-mark-ring) global-mark-ring-max)
3150 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3151 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3152 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3153 (message "Mark set"))
3154 (if (or activate (not transient-mark-mode))
3155 (set-mark (mark t)))
3156 nil)
3158 (defun pop-mark ()
3159 "Pop off mark ring into the buffer's actual mark.
3160 Does not set point. Does nothing if mark ring is empty."
3161 (when mark-ring
3162 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3163 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3164 (move-marker (car mark-ring) nil)
3165 (if (null (mark t)) (ding))
3166 (setq mark-ring (cdr mark-ring)))
3167 (deactivate-mark))
3169 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3170 (defun exchange-point-and-mark (&optional arg)
3171 "Put the mark where point is now, and point where the mark is now.
3172 This command works even when the mark is not active,
3173 and it reactivates the mark.
3174 With prefix arg, `transient-mark-mode' is enabled temporarily."
3175 (interactive "P")
3176 (if arg
3177 (if mark-active
3178 (if (null transient-mark-mode)
3179 (setq transient-mark-mode 'lambda))
3180 (setq arg nil)))
3181 (unless arg
3182 (let ((omark (mark t)))
3183 (if (null omark)
3184 (error "No mark set in this buffer"))
3185 (set-mark (point))
3186 (goto-char omark)
3187 nil)))
3189 (define-minor-mode transient-mark-mode
3190 "Toggle Transient Mark mode.
3191 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
3193 In Transient Mark mode, when the mark is active, the region is highlighted.
3194 Changing the buffer \"deactivates\" the mark.
3195 So do certain other operations that set the mark
3196 but whose main purpose is something else--for example,
3197 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3199 You can also deactivate the mark by typing \\[keyboard-quit] or
3200 \\[keyboard-escape-quit].
3202 Many commands change their behavior when Transient Mark mode is in effect
3203 and the mark is active, by acting on the region instead of their usual
3204 default part of the buffer's text. Examples of such commands include
3205 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3206 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3207 Invoke \\[apropos-documentation] and type \"transient\" or
3208 \"mark.*active\" at the prompt, to see the documentation of
3209 commands which are sensitive to the Transient Mark mode."
3210 :global t :group 'editing-basics :require nil)
3212 (defvar widen-automatically t
3213 "Non-nil means it is ok for commands to call `widen' when they want to.
3214 Some commands will do this in order to go to positions outside
3215 the current accessible part of the buffer.
3217 If `widen-automatically' is nil, these commands will do something else
3218 as a fallback, and won't change the buffer bounds.")
3220 (defun pop-global-mark ()
3221 "Pop off global mark ring and jump to the top location."
3222 (interactive)
3223 ;; Pop entries which refer to non-existent buffers.
3224 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3225 (setq global-mark-ring (cdr global-mark-ring)))
3226 (or global-mark-ring
3227 (error "No global mark set"))
3228 (let* ((marker (car global-mark-ring))
3229 (buffer (marker-buffer marker))
3230 (position (marker-position marker)))
3231 (setq global-mark-ring (nconc (cdr global-mark-ring)
3232 (list (car global-mark-ring))))
3233 (set-buffer buffer)
3234 (or (and (>= position (point-min))
3235 (<= position (point-max)))
3236 (if widen-automatically
3237 (error "Global mark position is outside accessible part of buffer")
3238 (widen)))
3239 (goto-char position)
3240 (switch-to-buffer buffer)))
3242 (defcustom next-line-add-newlines nil
3243 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3244 :type 'boolean
3245 :version "21.1"
3246 :group 'editing-basics)
3248 (defun next-line (&optional arg try-vscroll)
3249 "Move cursor vertically down ARG lines.
3250 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3251 If there is no character in the target line exactly under the current column,
3252 the cursor is positioned after the character in that line which spans this
3253 column, or at the end of the line if it is not long enough.
3254 If there is no line in the buffer after this one, behavior depends on the
3255 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3256 to create a line, and moves the cursor to that line. Otherwise it moves the
3257 cursor to the end of the buffer.
3259 The command \\[set-goal-column] can be used to create
3260 a semipermanent goal column for this command.
3261 Then instead of trying to move exactly vertically (or as close as possible),
3262 this command moves to the specified goal column (or as close as possible).
3263 The goal column is stored in the variable `goal-column', which is nil
3264 when there is no goal column.
3266 If you are thinking of using this in a Lisp program, consider
3267 using `forward-line' instead. It is usually easier to use
3268 and more reliable (no dependence on goal column, etc.)."
3269 (interactive "p\np")
3270 (or arg (setq arg 1))
3271 (if (and next-line-add-newlines (= arg 1))
3272 (if (save-excursion (end-of-line) (eobp))
3273 ;; When adding a newline, don't expand an abbrev.
3274 (let ((abbrev-mode nil))
3275 (end-of-line)
3276 (insert "\n"))
3277 (line-move arg nil nil try-vscroll))
3278 (if (interactive-p)
3279 (condition-case nil
3280 (line-move arg nil nil try-vscroll)
3281 ((beginning-of-buffer end-of-buffer) (ding)))
3282 (line-move arg nil nil try-vscroll)))
3283 nil)
3285 (defun previous-line (&optional arg try-vscroll)
3286 "Move cursor vertically up ARG lines.
3287 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3288 If there is no character in the target line exactly over the current column,
3289 the cursor is positioned after the character in that line which spans this
3290 column, or at the end of the line if it is not long enough.
3292 The command \\[set-goal-column] can be used to create
3293 a semipermanent goal column for this command.
3294 Then instead of trying to move exactly vertically (or as close as possible),
3295 this command moves to the specified goal column (or as close as possible).
3296 The goal column is stored in the variable `goal-column', which is nil
3297 when there is no goal column.
3299 If you are thinking of using this in a Lisp program, consider using
3300 `forward-line' with a negative argument instead. It is usually easier
3301 to use and more reliable (no dependence on goal column, etc.)."
3302 (interactive "p\np")
3303 (or arg (setq arg 1))
3304 (if (interactive-p)
3305 (condition-case nil
3306 (line-move (- arg) nil nil try-vscroll)
3307 ((beginning-of-buffer end-of-buffer) (ding)))
3308 (line-move (- arg) nil nil try-vscroll))
3309 nil)
3311 (defcustom track-eol nil
3312 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
3313 This means moving to the end of each line moved onto.
3314 The beginning of a blank line does not count as the end of a line."
3315 :type 'boolean
3316 :group 'editing-basics)
3318 (defcustom goal-column nil
3319 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3320 :type '(choice integer
3321 (const :tag "None" nil))
3322 :group 'editing-basics)
3323 (make-variable-buffer-local 'goal-column)
3325 (defvar temporary-goal-column 0
3326 "Current goal column for vertical motion.
3327 It is the column where point was
3328 at the start of current run of vertical motion commands.
3329 When the `track-eol' feature is doing its job, the value is 9999.")
3331 (defcustom line-move-ignore-invisible t
3332 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3333 Outline mode sets this."
3334 :type 'boolean
3335 :group 'editing-basics)
3337 (defun line-move-invisible-p (pos)
3338 "Return non-nil if the character after POS is currently invisible."
3339 (let ((prop
3340 (get-char-property pos 'invisible)))
3341 (if (eq buffer-invisibility-spec t)
3342 prop
3343 (or (memq prop buffer-invisibility-spec)
3344 (assq prop buffer-invisibility-spec)))))
3346 ;; This is like line-move-1 except that it also performs
3347 ;; vertical scrolling of tall images if appropriate.
3348 ;; That is not really a clean thing to do, since it mixes
3349 ;; scrolling with cursor motion. But so far we don't have
3350 ;; a cleaner solution to the problem of making C-n do something
3351 ;; useful given a tall image.
3352 (defun line-move (arg &optional noerror to-end try-vscroll)
3353 (if (and auto-window-vscroll try-vscroll
3354 ;; But don't vscroll in a keyboard macro.
3355 (not defining-kbd-macro)
3356 (not executing-kbd-macro))
3357 (let ((forward (> arg 0))
3358 (part (nth 2 (pos-visible-in-window-p (point) nil t))))
3359 (if (and (consp part)
3360 (> (if forward (cdr part) (car part)) 0))
3361 (set-window-vscroll nil
3362 (if forward
3363 (+ (window-vscroll nil t)
3364 (min (cdr part)
3365 (* (frame-char-height) arg)))
3366 (max 0
3367 (- (window-vscroll nil t)
3368 (min (car part)
3369 (* (frame-char-height) (- arg))))))
3371 (set-window-vscroll nil 0)
3372 (when (line-move-1 arg noerror to-end)
3373 (when (not forward)
3374 ;; Update display before calling pos-visible-in-window-p,
3375 ;; because it depends on window-start being up-to-date.
3376 (sit-for 0)
3377 ;; If the current line is partly hidden at the bottom,
3378 ;; scroll it partially up so as to unhide the bottom.
3379 (if (and (setq part (nth 2 (pos-visible-in-window-p
3380 (line-beginning-position) nil t)))
3381 (> (cdr part) 0))
3382 (set-window-vscroll nil (cdr part) t)))
3383 t)))
3384 (line-move-1 arg noerror to-end)))
3386 ;; This is the guts of next-line and previous-line.
3387 ;; Arg says how many lines to move.
3388 ;; The value is t if we can move the specified number of lines.
3389 (defun line-move-1 (arg &optional noerror to-end)
3390 ;; Don't run any point-motion hooks, and disregard intangibility,
3391 ;; for intermediate positions.
3392 (let ((inhibit-point-motion-hooks t)
3393 (opoint (point))
3394 (forward (> arg 0)))
3395 (unwind-protect
3396 (progn
3397 (if (not (memq last-command '(next-line previous-line)))
3398 (setq temporary-goal-column
3399 (if (and track-eol (eolp)
3400 ;; Don't count beg of empty line as end of line
3401 ;; unless we just did explicit end-of-line.
3402 (or (not (bolp)) (eq last-command 'end-of-line)))
3403 9999
3404 (current-column))))
3406 (if (and (not (integerp selective-display))
3407 (not line-move-ignore-invisible))
3408 ;; Use just newline characters.
3409 ;; Set ARG to 0 if we move as many lines as requested.
3410 (or (if (> arg 0)
3411 (progn (if (> arg 1) (forward-line (1- arg)))
3412 ;; This way of moving forward ARG lines
3413 ;; verifies that we have a newline after the last one.
3414 ;; It doesn't get confused by intangible text.
3415 (end-of-line)
3416 (if (zerop (forward-line 1))
3417 (setq arg 0)))
3418 (and (zerop (forward-line arg))
3419 (bolp)
3420 (setq arg 0)))
3421 (unless noerror
3422 (signal (if (< arg 0)
3423 'beginning-of-buffer
3424 'end-of-buffer)
3425 nil)))
3426 ;; Move by arg lines, but ignore invisible ones.
3427 (let (done)
3428 (while (and (> arg 0) (not done))
3429 ;; If the following character is currently invisible,
3430 ;; skip all characters with that same `invisible' property value.
3431 (while (and (not (eobp)) (line-move-invisible-p (point)))
3432 (goto-char (next-char-property-change (point))))
3433 ;; Now move a line.
3434 (end-of-line)
3435 ;; If there's no invisibility here, move over the newline.
3436 (let ((pos-before (point))
3437 line-done)
3438 (if (eobp)
3439 (if (not noerror)
3440 (signal 'end-of-buffer nil)
3441 (setq done t)))
3442 (when (and (not done)
3443 (not (integerp selective-display))
3444 (not (line-move-invisible-p (point))))
3445 (unless (overlays-in (max (1- pos-before) (point-min))
3446 (min (1+ (point)) (point-max)))
3447 ;; We avoid vertical-motion when possible
3448 ;; because that has to fontify.
3449 (forward-line 1)
3450 (setq line-done t)))
3451 (and (not done) (not line-done)
3452 ;; Otherwise move a more sophisticated way.
3453 (zerop (vertical-motion 1))
3454 (if (not noerror)
3455 (signal 'end-of-buffer nil)
3456 (setq done t))))
3457 (unless done
3458 (setq arg (1- arg))))
3459 ;; The logic of this is the same as the loop above,
3460 ;; it just goes in the other direction.
3461 (while (and (< arg 0) (not done))
3462 (beginning-of-line)
3463 (let ((pos-before (point))
3464 line-done)
3465 (if (bobp)
3466 (if (not noerror)
3467 (signal 'beginning-of-buffer nil)
3468 (setq done t)))
3469 (when (and (not done)
3470 (not (integerp selective-display))
3471 (not (line-move-invisible-p (1- (point)))))
3472 (unless (overlays-in (max (1- (point)) (point-min))
3473 (min (1+ pos-before) (point-max)))
3474 (forward-line -1)
3475 (setq line-done t)))
3476 (and (not done) (not line-done)
3477 (zerop (vertical-motion -1))
3478 (if (not noerror)
3479 (signal 'beginning-of-buffer nil)
3480 (setq done t))))
3481 (unless done
3482 (setq arg (1+ arg))
3483 (while (and ;; Don't move over previous invis lines
3484 ;; if our target is the middle of this line.
3485 (or (zerop (or goal-column temporary-goal-column))
3486 (< arg 0))
3487 (not (bobp)) (line-move-invisible-p (1- (point))))
3488 (goto-char (previous-char-property-change (point))))))))
3489 ;; This is the value the function returns.
3490 (= arg 0))
3492 (cond ((> arg 0)
3493 ;; If we did not move down as far as desired,
3494 ;; at least go to end of line.
3495 (end-of-line))
3496 ((< arg 0)
3497 ;; If we did not move down as far as desired,
3498 ;; at least go to end of line.
3499 (beginning-of-line))
3501 (line-move-finish (or goal-column temporary-goal-column)
3502 opoint forward))))))
3504 (defun line-move-finish (column opoint forward)
3505 (let ((repeat t))
3506 (while repeat
3507 ;; Set REPEAT to t to repeat the whole thing.
3508 (setq repeat nil)
3510 (let (new
3511 (line-beg (save-excursion (beginning-of-line) (point)))
3512 (line-end
3513 ;; Compute the end of the line
3514 ;; ignoring effectively invisible newlines.
3515 (save-excursion
3516 (end-of-line)
3517 (while (and (not (eobp)) (line-move-invisible-p (point)))
3518 (goto-char (next-char-property-change (point)))
3519 (end-of-line))
3520 (point))))
3522 ;; Move to the desired column.
3523 (line-move-to-column column)
3524 (setq new (point))
3526 ;; Process intangibility within a line.
3527 ;; Move to the chosen destination position from above,
3528 ;; with intangibility processing enabled.
3530 (goto-char (point-min))
3531 (let ((inhibit-point-motion-hooks nil))
3532 (goto-char new)
3534 ;; If intangibility moves us to a different (later) place
3535 ;; in the same line, use that as the destination.
3536 (if (<= (point) line-end)
3537 (setq new (point))
3538 ;; If that position is "too late",
3539 ;; try the previous allowable position.
3540 ;; See if it is ok.
3541 (backward-char)
3542 (if (if forward
3543 ;; If going forward, don't accept the previous
3544 ;; allowable position if it is before the target line.
3545 (< line-beg (point))
3546 ;; If going backward, don't accept the previous
3547 ;; allowable position if it is still after the target line.
3548 (<= (point) line-end))
3549 (setq new (point))
3550 ;; As a last resort, use the end of the line.
3551 (setq new line-end))))
3553 ;; Now move to the updated destination, processing fields
3554 ;; as well as intangibility.
3555 (goto-char opoint)
3556 (let ((inhibit-point-motion-hooks nil))
3557 (goto-char
3558 (constrain-to-field new opoint nil t
3559 'inhibit-line-move-field-capture)))
3561 ;; If all this moved us to a different line,
3562 ;; retry everything within that new line.
3563 (when (or (< (point) line-beg) (> (point) line-end))
3564 ;; Repeat the intangibility and field processing.
3565 (setq repeat t))))))
3567 (defun line-move-to-column (col)
3568 "Try to find column COL, considering invisibility.
3569 This function works only in certain cases,
3570 because what we really need is for `move-to-column'
3571 and `current-column' to be able to ignore invisible text."
3572 (if (zerop col)
3573 (beginning-of-line)
3574 (move-to-column col))
3576 (when (and line-move-ignore-invisible
3577 (not (bolp)) (line-move-invisible-p (1- (point))))
3578 (let ((normal-location (point))
3579 (normal-column (current-column)))
3580 ;; If the following character is currently invisible,
3581 ;; skip all characters with that same `invisible' property value.
3582 (while (and (not (eobp))
3583 (line-move-invisible-p (point)))
3584 (goto-char (next-char-property-change (point))))
3585 ;; Have we advanced to a larger column position?
3586 (if (> (current-column) normal-column)
3587 ;; We have made some progress towards the desired column.
3588 ;; See if we can make any further progress.
3589 (line-move-to-column (+ (current-column) (- col normal-column)))
3590 ;; Otherwise, go to the place we originally found
3591 ;; and move back over invisible text.
3592 ;; that will get us to the same place on the screen
3593 ;; but with a more reasonable buffer position.
3594 (goto-char normal-location)
3595 (let ((line-beg (save-excursion (beginning-of-line) (point))))
3596 (while (and (not (bolp)) (line-move-invisible-p (1- (point))))
3597 (goto-char (previous-char-property-change (point) line-beg))))))))
3599 (defun move-end-of-line (arg)
3600 "Move point to end of current line.
3601 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3602 If point reaches the beginning or end of buffer, it stops there.
3603 To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3605 This command does not move point across a field boundary unless doing so
3606 would move beyond there to a different line; if ARG is nil or 1, and
3607 point starts at a field boundary, point does not move. To ignore field
3608 boundaries bind `inhibit-field-text-motion' to t."
3609 (interactive "p")
3610 (or arg (setq arg 1))
3611 (let (done)
3612 (while (not done)
3613 (let ((newpos
3614 (save-excursion
3615 (let ((goal-column 0))
3616 (and (line-move arg t)
3617 (not (bobp))
3618 (progn
3619 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3620 (goto-char (previous-char-property-change (point))))
3621 (backward-char 1)))
3622 (point)))))
3623 (goto-char newpos)
3624 (if (and (> (point) newpos)
3625 (eq (preceding-char) ?\n))
3626 (backward-char 1)
3627 (if (and (> (point) newpos) (not (eobp))
3628 (not (eq (following-char) ?\n)))
3629 ;; If we skipped something intangible
3630 ;; and now we're not really at eol,
3631 ;; keep going.
3632 (setq arg 1)
3633 (setq done t)))))))
3635 (defun move-beginning-of-line (arg)
3636 "Move point to beginning of current display line.
3637 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3638 If point reaches the beginning or end of buffer, it stops there.
3639 To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3641 This command does not move point across a field boundary unless doing so
3642 would move beyond there to a different line; if ARG is nil or 1, and
3643 point starts at a field boundary, point does not move. To ignore field
3644 boundaries bind `inhibit-field-text-motion' to t."
3645 (interactive "p")
3646 (or arg (setq arg 1))
3647 (if (/= arg 1)
3648 (line-move (1- arg) t))
3649 (beginning-of-line 1)
3650 (let ((orig (point)))
3651 (vertical-motion 0)
3652 (if (/= orig (point))
3653 (goto-char (constrain-to-field (point) orig (/= arg 1) t nil)))))
3656 ;;; Many people have said they rarely use this feature, and often type
3657 ;;; it by accident. Maybe it shouldn't even be on a key.
3658 (put 'set-goal-column 'disabled t)
3660 (defun set-goal-column (arg)
3661 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3662 Those commands will move to this position in the line moved to
3663 rather than trying to keep the same horizontal position.
3664 With a non-nil argument, clears out the goal column
3665 so that \\[next-line] and \\[previous-line] resume vertical motion.
3666 The goal column is stored in the variable `goal-column'."
3667 (interactive "P")
3668 (if arg
3669 (progn
3670 (setq goal-column nil)
3671 (message "No goal column"))
3672 (setq goal-column (current-column))
3673 (message (substitute-command-keys
3674 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3675 goal-column))
3676 nil)
3679 (defun scroll-other-window-down (lines)
3680 "Scroll the \"other window\" down.
3681 For more details, see the documentation for `scroll-other-window'."
3682 (interactive "P")
3683 (scroll-other-window
3684 ;; Just invert the argument's meaning.
3685 ;; We can do that without knowing which window it will be.
3686 (if (eq lines '-) nil
3687 (if (null lines) '-
3688 (- (prefix-numeric-value lines))))))
3690 (defun beginning-of-buffer-other-window (arg)
3691 "Move point to the beginning of the buffer in the other window.
3692 Leave mark at previous position.
3693 With arg N, put point N/10 of the way from the true beginning."
3694 (interactive "P")
3695 (let ((orig-window (selected-window))
3696 (window (other-window-for-scrolling)))
3697 ;; We use unwind-protect rather than save-window-excursion
3698 ;; because the latter would preserve the things we want to change.
3699 (unwind-protect
3700 (progn
3701 (select-window window)
3702 ;; Set point and mark in that window's buffer.
3703 (with-no-warnings
3704 (beginning-of-buffer arg))
3705 ;; Set point accordingly.
3706 (recenter '(t)))
3707 (select-window orig-window))))
3709 (defun end-of-buffer-other-window (arg)
3710 "Move point to the end of the buffer in the other window.
3711 Leave mark at previous position.
3712 With arg N, put point N/10 of the way from the true end."
3713 (interactive "P")
3714 ;; See beginning-of-buffer-other-window for comments.
3715 (let ((orig-window (selected-window))
3716 (window (other-window-for-scrolling)))
3717 (unwind-protect
3718 (progn
3719 (select-window window)
3720 (with-no-warnings
3721 (end-of-buffer arg))
3722 (recenter '(t)))
3723 (select-window orig-window))))
3725 (defun transpose-chars (arg)
3726 "Interchange characters around point, moving forward one character.
3727 With prefix arg ARG, effect is to take character before point
3728 and drag it forward past ARG other characters (backward if ARG negative).
3729 If no argument and at end of line, the previous two chars are exchanged."
3730 (interactive "*P")
3731 (and (null arg) (eolp) (forward-char -1))
3732 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3734 (defun transpose-words (arg)
3735 "Interchange words around point, leaving point at end of them.
3736 With prefix arg ARG, effect is to take word before or around point
3737 and drag it forward past ARG other words (backward if ARG negative).
3738 If ARG is zero, the words around or after point and around or after mark
3739 are interchanged."
3740 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3741 (interactive "*p")
3742 (transpose-subr 'forward-word arg))
3744 (defun transpose-sexps (arg)
3745 "Like \\[transpose-words] but applies to sexps.
3746 Does not work on a sexp that point is in the middle of
3747 if it is a list or string."
3748 (interactive "*p")
3749 (transpose-subr
3750 (lambda (arg)
3751 ;; Here we should try to simulate the behavior of
3752 ;; (cons (progn (forward-sexp x) (point))
3753 ;; (progn (forward-sexp (- x)) (point)))
3754 ;; Except that we don't want to rely on the second forward-sexp
3755 ;; putting us back to where we want to be, since forward-sexp-function
3756 ;; might do funny things like infix-precedence.
3757 (if (if (> arg 0)
3758 (looking-at "\\sw\\|\\s_")
3759 (and (not (bobp))
3760 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3761 ;; Jumping over a symbol. We might be inside it, mind you.
3762 (progn (funcall (if (> arg 0)
3763 'skip-syntax-backward 'skip-syntax-forward)
3764 "w_")
3765 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3766 ;; Otherwise, we're between sexps. Take a step back before jumping
3767 ;; to make sure we'll obey the same precedence no matter which direction
3768 ;; we're going.
3769 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3770 (cons (save-excursion (forward-sexp arg) (point))
3771 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3772 (not (zerop (funcall (if (> arg 0)
3773 'skip-syntax-forward
3774 'skip-syntax-backward)
3775 ".")))))
3776 (point)))))
3777 arg 'special))
3779 (defun transpose-lines (arg)
3780 "Exchange current line and previous line, leaving point after both.
3781 With argument ARG, takes previous line and moves it past ARG lines.
3782 With argument 0, interchanges line point is in with line mark is in."
3783 (interactive "*p")
3784 (transpose-subr (function
3785 (lambda (arg)
3786 (if (> arg 0)
3787 (progn
3788 ;; Move forward over ARG lines,
3789 ;; but create newlines if necessary.
3790 (setq arg (forward-line arg))
3791 (if (/= (preceding-char) ?\n)
3792 (setq arg (1+ arg)))
3793 (if (> arg 0)
3794 (newline arg)))
3795 (forward-line arg))))
3796 arg))
3798 (defun transpose-subr (mover arg &optional special)
3799 (let ((aux (if special mover
3800 (lambda (x)
3801 (cons (progn (funcall mover x) (point))
3802 (progn (funcall mover (- x)) (point))))))
3803 pos1 pos2)
3804 (cond
3805 ((= arg 0)
3806 (save-excursion
3807 (setq pos1 (funcall aux 1))
3808 (goto-char (mark))
3809 (setq pos2 (funcall aux 1))
3810 (transpose-subr-1 pos1 pos2))
3811 (exchange-point-and-mark))
3812 ((> arg 0)
3813 (setq pos1 (funcall aux -1))
3814 (setq pos2 (funcall aux arg))
3815 (transpose-subr-1 pos1 pos2)
3816 (goto-char (car pos2)))
3818 (setq pos1 (funcall aux -1))
3819 (goto-char (car pos1))
3820 (setq pos2 (funcall aux arg))
3821 (transpose-subr-1 pos1 pos2)))))
3823 (defun transpose-subr-1 (pos1 pos2)
3824 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3825 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3826 (when (> (car pos1) (car pos2))
3827 (let ((swap pos1))
3828 (setq pos1 pos2 pos2 swap)))
3829 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3830 (atomic-change-group
3831 (let (word2)
3832 ;; FIXME: We first delete the two pieces of text, so markers that
3833 ;; used to point to after the text end up pointing to before it :-(
3834 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3835 (goto-char (car pos2))
3836 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3837 (goto-char (car pos1))
3838 (insert word2))))
3840 (defun backward-word (&optional arg)
3841 "Move backward until encountering the beginning of a word.
3842 With argument, do this that many times."
3843 (interactive "p")
3844 (forward-word (- (or arg 1))))
3846 (defun mark-word (&optional arg allow-extend)
3847 "Set mark ARG words away from point.
3848 The place mark goes is the same place \\[forward-word] would
3849 move to with the same argument.
3850 Interactively, if this command is repeated
3851 or (in Transient Mark mode) if the mark is active,
3852 it marks the next ARG words after the ones already marked."
3853 (interactive "P\np")
3854 (cond ((and allow-extend
3855 (or (and (eq last-command this-command) (mark t))
3856 (and transient-mark-mode mark-active)))
3857 (setq arg (if arg (prefix-numeric-value arg)
3858 (if (< (mark) (point)) -1 1)))
3859 (set-mark
3860 (save-excursion
3861 (goto-char (mark))
3862 (forward-word arg)
3863 (point))))
3865 (push-mark
3866 (save-excursion
3867 (forward-word (prefix-numeric-value arg))
3868 (point))
3869 nil t))))
3871 (defun kill-word (arg)
3872 "Kill characters forward until encountering the end of a word.
3873 With argument, do this that many times."
3874 (interactive "p")
3875 (kill-region (point) (progn (forward-word arg) (point))))
3877 (defun backward-kill-word (arg)
3878 "Kill characters backward until encountering the end of a word.
3879 With argument, do this that many times."
3880 (interactive "p")
3881 (kill-word (- arg)))
3883 (defun current-word (&optional strict really-word)
3884 "Return the symbol or word that point is on (or a nearby one) as a string.
3885 The return value includes no text properties.
3886 If optional arg STRICT is non-nil, return nil unless point is within
3887 or adjacent to a symbol or word. In all cases the value can be nil
3888 if there is no word nearby.
3889 The function, belying its name, normally finds a symbol.
3890 If optional arg REALLY-WORD is non-nil, it finds just a word."
3891 (save-excursion
3892 (let* ((oldpoint (point)) (start (point)) (end (point))
3893 (syntaxes (if really-word "w" "w_"))
3894 (not-syntaxes (concat "^" syntaxes)))
3895 (skip-syntax-backward syntaxes) (setq start (point))
3896 (goto-char oldpoint)
3897 (skip-syntax-forward syntaxes) (setq end (point))
3898 (when (and (eq start oldpoint) (eq end oldpoint)
3899 ;; Point is neither within nor adjacent to a word.
3900 (not strict))
3901 ;; Look for preceding word in same line.
3902 (skip-syntax-backward not-syntaxes
3903 (save-excursion (beginning-of-line)
3904 (point)))
3905 (if (bolp)
3906 ;; No preceding word in same line.
3907 ;; Look for following word in same line.
3908 (progn
3909 (skip-syntax-forward not-syntaxes
3910 (save-excursion (end-of-line)
3911 (point)))
3912 (setq start (point))
3913 (skip-syntax-forward syntaxes)
3914 (setq end (point)))
3915 (setq end (point))
3916 (skip-syntax-backward syntaxes)
3917 (setq start (point))))
3918 ;; If we found something nonempty, return it as a string.
3919 (unless (= start end)
3920 (buffer-substring-no-properties start end)))))
3922 (defcustom fill-prefix nil
3923 "*String for filling to insert at front of new line, or nil for none."
3924 :type '(choice (const :tag "None" nil)
3925 string)
3926 :group 'fill)
3927 (make-variable-buffer-local 'fill-prefix)
3929 (defcustom auto-fill-inhibit-regexp nil
3930 "*Regexp to match lines which should not be auto-filled."
3931 :type '(choice (const :tag "None" nil)
3932 regexp)
3933 :group 'fill)
3935 (defvar comment-line-break-function 'comment-indent-new-line
3936 "*Mode-specific function which line breaks and continues a comment.
3938 This function is only called during auto-filling of a comment section.
3939 The function should take a single optional argument, which is a flag
3940 indicating whether it should use soft newlines.")
3942 ;; This function is used as the auto-fill-function of a buffer
3943 ;; when Auto-Fill mode is enabled.
3944 ;; It returns t if it really did any work.
3945 ;; (Actually some major modes use a different auto-fill function,
3946 ;; but this one is the default one.)
3947 (defun do-auto-fill ()
3948 (let (fc justify give-up
3949 (fill-prefix fill-prefix))
3950 (if (or (not (setq justify (current-justification)))
3951 (null (setq fc (current-fill-column)))
3952 (and (eq justify 'left)
3953 (<= (current-column) fc))
3954 (and auto-fill-inhibit-regexp
3955 (save-excursion (beginning-of-line)
3956 (looking-at auto-fill-inhibit-regexp))))
3957 nil ;; Auto-filling not required
3958 (if (memq justify '(full center right))
3959 (save-excursion (unjustify-current-line)))
3961 ;; Choose a fill-prefix automatically.
3962 (when (and adaptive-fill-mode
3963 (or (null fill-prefix) (string= fill-prefix "")))
3964 (let ((prefix
3965 (fill-context-prefix
3966 (save-excursion (backward-paragraph 1) (point))
3967 (save-excursion (forward-paragraph 1) (point)))))
3968 (and prefix (not (equal prefix ""))
3969 ;; Use auto-indentation rather than a guessed empty prefix.
3970 (not (and fill-indent-according-to-mode
3971 (string-match "\\`[ \t]*\\'" prefix)))
3972 (setq fill-prefix prefix))))
3974 (while (and (not give-up) (> (current-column) fc))
3975 ;; Determine where to split the line.
3976 (let* (after-prefix
3977 (fill-point
3978 (save-excursion
3979 (beginning-of-line)
3980 (setq after-prefix (point))
3981 (and fill-prefix
3982 (looking-at (regexp-quote fill-prefix))
3983 (setq after-prefix (match-end 0)))
3984 (move-to-column (1+ fc))
3985 (fill-move-to-break-point after-prefix)
3986 (point))))
3988 ;; See whether the place we found is any good.
3989 (if (save-excursion
3990 (goto-char fill-point)
3991 (or (bolp)
3992 ;; There is no use breaking at end of line.
3993 (save-excursion (skip-chars-forward " ") (eolp))
3994 ;; It is futile to split at the end of the prefix
3995 ;; since we would just insert the prefix again.
3996 (and after-prefix (<= (point) after-prefix))
3997 ;; Don't split right after a comment starter
3998 ;; since we would just make another comment starter.
3999 (and comment-start-skip
4000 (let ((limit (point)))
4001 (beginning-of-line)
4002 (and (re-search-forward comment-start-skip
4003 limit t)
4004 (eq (point) limit))))))
4005 ;; No good place to break => stop trying.
4006 (setq give-up t)
4007 ;; Ok, we have a useful place to break the line. Do it.
4008 (let ((prev-column (current-column)))
4009 ;; If point is at the fill-point, do not `save-excursion'.
4010 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4011 ;; point will end up before it rather than after it.
4012 (if (save-excursion
4013 (skip-chars-backward " \t")
4014 (= (point) fill-point))
4015 (funcall comment-line-break-function t)
4016 (save-excursion
4017 (goto-char fill-point)
4018 (funcall comment-line-break-function t)))
4019 ;; Now do justification, if required
4020 (if (not (eq justify 'left))
4021 (save-excursion
4022 (end-of-line 0)
4023 (justify-current-line justify nil t)))
4024 ;; If making the new line didn't reduce the hpos of
4025 ;; the end of the line, then give up now;
4026 ;; trying again will not help.
4027 (if (>= (current-column) prev-column)
4028 (setq give-up t))))))
4029 ;; Justify last line.
4030 (justify-current-line justify t t)
4031 t)))
4033 (defvar normal-auto-fill-function 'do-auto-fill
4034 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4035 Some major modes set this.")
4037 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
4038 ;; FIXME: turn into a proper minor mode.
4039 ;; Add a global minor mode version of it.
4040 (defun auto-fill-mode (&optional arg)
4041 "Toggle Auto Fill mode.
4042 With arg, turn Auto Fill mode on if and only if arg is positive.
4043 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4044 automatically breaks the line at a previous space.
4046 The value of `normal-auto-fill-function' specifies the function to use
4047 for `auto-fill-function' when turning Auto Fill mode on."
4048 (interactive "P")
4049 (prog1 (setq auto-fill-function
4050 (if (if (null arg)
4051 (not auto-fill-function)
4052 (> (prefix-numeric-value arg) 0))
4053 normal-auto-fill-function
4054 nil))
4055 (force-mode-line-update)))
4057 ;; This holds a document string used to document auto-fill-mode.
4058 (defun auto-fill-function ()
4059 "Automatically break line at a previous space, in insertion of text."
4060 nil)
4062 (defun turn-on-auto-fill ()
4063 "Unconditionally turn on Auto Fill mode."
4064 (auto-fill-mode 1))
4066 (defun turn-off-auto-fill ()
4067 "Unconditionally turn off Auto Fill mode."
4068 (auto-fill-mode -1))
4070 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
4072 (defun set-fill-column (arg)
4073 "Set `fill-column' to specified argument.
4074 Use \\[universal-argument] followed by a number to specify a column.
4075 Just \\[universal-argument] as argument means to use the current column."
4076 (interactive "P")
4077 (if (consp arg)
4078 (setq arg (current-column)))
4079 (if (not (integerp arg))
4080 ;; Disallow missing argument; it's probably a typo for C-x C-f.
4081 (error "Set-fill-column requires an explicit argument")
4082 (message "Fill column set to %d (was %d)" arg fill-column)
4083 (setq fill-column arg)))
4085 (defun set-selective-display (arg)
4086 "Set `selective-display' to ARG; clear it if no arg.
4087 When the value of `selective-display' is a number > 0,
4088 lines whose indentation is >= that value are not displayed.
4089 The variable `selective-display' has a separate value for each buffer."
4090 (interactive "P")
4091 (if (eq selective-display t)
4092 (error "selective-display already in use for marked lines"))
4093 (let ((current-vpos
4094 (save-restriction
4095 (narrow-to-region (point-min) (point))
4096 (goto-char (window-start))
4097 (vertical-motion (window-height)))))
4098 (setq selective-display
4099 (and arg (prefix-numeric-value arg)))
4100 (recenter current-vpos))
4101 (set-window-start (selected-window) (window-start (selected-window)))
4102 (princ "selective-display set to " t)
4103 (prin1 selective-display t)
4104 (princ "." t))
4106 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
4107 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
4109 (defun toggle-truncate-lines (arg)
4110 "Toggle whether to fold or truncate long lines on the screen.
4111 With arg, truncate long lines iff arg is positive.
4112 Note that in side-by-side windows, truncation is always enabled."
4113 (interactive "P")
4114 (setq truncate-lines
4115 (if (null arg)
4116 (not truncate-lines)
4117 (> (prefix-numeric-value arg) 0)))
4118 (force-mode-line-update)
4119 (unless truncate-lines
4120 (let ((buffer (current-buffer)))
4121 (walk-windows (lambda (window)
4122 (if (eq buffer (window-buffer window))
4123 (set-window-hscroll window 0)))
4124 nil t)))
4125 (message "Truncate long lines %s"
4126 (if truncate-lines "enabled" "disabled")))
4128 (defvar overwrite-mode-textual " Ovwrt"
4129 "The string displayed in the mode line when in overwrite mode.")
4130 (defvar overwrite-mode-binary " Bin Ovwrt"
4131 "The string displayed in the mode line when in binary overwrite mode.")
4133 (defun overwrite-mode (arg)
4134 "Toggle overwrite mode.
4135 With arg, turn overwrite mode on iff arg is positive.
4136 In overwrite mode, printing characters typed in replace existing text
4137 on a one-for-one basis, rather than pushing it to the right. At the
4138 end of a line, such characters extend the line. Before a tab,
4139 such characters insert until the tab is filled in.
4140 \\[quoted-insert] still inserts characters in overwrite mode; this
4141 is supposed to make it easier to insert characters when necessary."
4142 (interactive "P")
4143 (setq overwrite-mode
4144 (if (if (null arg) (not overwrite-mode)
4145 (> (prefix-numeric-value arg) 0))
4146 'overwrite-mode-textual))
4147 (force-mode-line-update))
4149 (defun binary-overwrite-mode (arg)
4150 "Toggle binary overwrite mode.
4151 With arg, turn binary overwrite mode on iff arg is positive.
4152 In binary overwrite mode, printing characters typed in replace
4153 existing text. Newlines are not treated specially, so typing at the
4154 end of a line joins the line to the next, with the typed character
4155 between them. Typing before a tab character simply replaces the tab
4156 with the character typed.
4157 \\[quoted-insert] replaces the text at the cursor, just as ordinary
4158 typing characters do.
4160 Note that binary overwrite mode is not its own minor mode; it is a
4161 specialization of overwrite-mode, entered by setting the
4162 `overwrite-mode' variable to `overwrite-mode-binary'."
4163 (interactive "P")
4164 (setq overwrite-mode
4165 (if (if (null arg)
4166 (not (eq overwrite-mode 'overwrite-mode-binary))
4167 (> (prefix-numeric-value arg) 0))
4168 'overwrite-mode-binary))
4169 (force-mode-line-update))
4171 (define-minor-mode line-number-mode
4172 "Toggle Line Number mode.
4173 With arg, turn Line Number mode on iff arg is positive.
4174 When Line Number mode is enabled, the line number appears
4175 in the mode line.
4177 Line numbers do not appear for very large buffers and buffers
4178 with very long lines; see variables `line-number-display-limit'
4179 and `line-number-display-limit-width'."
4180 :init-value t :global t :group 'editing-basics :require nil)
4182 (define-minor-mode column-number-mode
4183 "Toggle Column Number mode.
4184 With arg, turn Column Number mode on iff arg is positive.
4185 When Column Number mode is enabled, the column number appears
4186 in the mode line."
4187 :global t :group 'editing-basics :require nil)
4189 (define-minor-mode size-indication-mode
4190 "Toggle Size Indication mode.
4191 With arg, turn Size Indication mode on iff arg is positive. When
4192 Size Indication mode is enabled, the size of the accessible part
4193 of the buffer appears in the mode line."
4194 :global t :group 'editing-basics :require nil)
4196 (defgroup paren-blinking nil
4197 "Blinking matching of parens and expressions."
4198 :prefix "blink-matching-"
4199 :group 'paren-matching)
4201 (defcustom blink-matching-paren t
4202 "*Non-nil means show matching open-paren when close-paren is inserted."
4203 :type 'boolean
4204 :group 'paren-blinking)
4206 (defcustom blink-matching-paren-on-screen t
4207 "*Non-nil means show matching open-paren when it is on screen.
4208 If nil, means don't show it (but the open-paren can still be shown
4209 when it is off screen)."
4210 :type 'boolean
4211 :group 'paren-blinking)
4213 (defcustom blink-matching-paren-distance (* 25 1024)
4214 "*If non-nil, is maximum distance to search for matching open-paren."
4215 :type 'integer
4216 :group 'paren-blinking)
4218 (defcustom blink-matching-delay 1
4219 "*Time in seconds to delay after showing a matching paren."
4220 :type 'number
4221 :group 'paren-blinking)
4223 (defcustom blink-matching-paren-dont-ignore-comments nil
4224 "*Non-nil means `blink-matching-paren' will not ignore comments."
4225 :type 'boolean
4226 :group 'paren-blinking)
4228 (defun blink-matching-open ()
4229 "Move cursor momentarily to the beginning of the sexp before point."
4230 (interactive)
4231 (and (> (point) (1+ (point-min)))
4232 blink-matching-paren
4233 ;; Verify an even number of quoting characters precede the close.
4234 (= 1 (logand 1 (- (point)
4235 (save-excursion
4236 (forward-char -1)
4237 (skip-syntax-backward "/\\")
4238 (point)))))
4239 (let* ((oldpos (point))
4240 (blinkpos)
4241 (mismatch)
4242 matching-paren)
4243 (save-excursion
4244 (save-restriction
4245 (if blink-matching-paren-distance
4246 (narrow-to-region (max (point-min)
4247 (- (point) blink-matching-paren-distance))
4248 oldpos))
4249 (condition-case ()
4250 (let ((parse-sexp-ignore-comments
4251 (and parse-sexp-ignore-comments
4252 (not blink-matching-paren-dont-ignore-comments))))
4253 (setq blinkpos (scan-sexps oldpos -1)))
4254 (error nil)))
4255 (and blinkpos
4256 ;; Not syntax '$'.
4257 (not (eq (syntax-class (syntax-after blinkpos)) 8))
4258 (setq matching-paren
4259 (let ((syntax (syntax-after blinkpos)))
4260 (and (consp syntax)
4261 (eq (syntax-class syntax) 4)
4262 (cdr syntax)))
4263 mismatch
4264 (or (null matching-paren)
4265 (/= (char-after (1- oldpos))
4266 matching-paren))))
4267 (if mismatch (setq blinkpos nil))
4268 (if blinkpos
4269 ;; Don't log messages about paren matching.
4270 (let (message-log-max)
4271 (goto-char blinkpos)
4272 (if (pos-visible-in-window-p)
4273 (and blink-matching-paren-on-screen
4274 (sit-for blink-matching-delay))
4275 (goto-char blinkpos)
4276 (message
4277 "Matches %s"
4278 ;; Show what precedes the open in its line, if anything.
4279 (if (save-excursion
4280 (skip-chars-backward " \t")
4281 (not (bolp)))
4282 (buffer-substring (progn (beginning-of-line) (point))
4283 (1+ blinkpos))
4284 ;; Show what follows the open in its line, if anything.
4285 (if (save-excursion
4286 (forward-char 1)
4287 (skip-chars-forward " \t")
4288 (not (eolp)))
4289 (buffer-substring blinkpos
4290 (progn (end-of-line) (point)))
4291 ;; Otherwise show the previous nonblank line,
4292 ;; if there is one.
4293 (if (save-excursion
4294 (skip-chars-backward "\n \t")
4295 (not (bobp)))
4296 (concat
4297 (buffer-substring (progn
4298 (skip-chars-backward "\n \t")
4299 (beginning-of-line)
4300 (point))
4301 (progn (end-of-line)
4302 (skip-chars-backward " \t")
4303 (point)))
4304 ;; Replace the newline and other whitespace with `...'.
4305 "..."
4306 (buffer-substring blinkpos (1+ blinkpos)))
4307 ;; There is nothing to show except the char itself.
4308 (buffer-substring blinkpos (1+ blinkpos))))))))
4309 (cond (mismatch
4310 (message "Mismatched parentheses"))
4311 ((not blink-matching-paren-distance)
4312 (message "Unmatched parenthesis"))))))))
4314 ;Turned off because it makes dbx bomb out.
4315 (setq blink-paren-function 'blink-matching-open)
4317 ;; This executes C-g typed while Emacs is waiting for a command.
4318 ;; Quitting out of a program does not go through here;
4319 ;; that happens in the QUIT macro at the C code level.
4320 (defun keyboard-quit ()
4321 "Signal a `quit' condition.
4322 During execution of Lisp code, this character causes a quit directly.
4323 At top-level, as an editor command, this simply beeps."
4324 (interactive)
4325 (deactivate-mark)
4326 (if (fboundp 'kmacro-keyboard-quit)
4327 (kmacro-keyboard-quit))
4328 (setq defining-kbd-macro nil)
4329 (signal 'quit nil))
4331 (defvar buffer-quit-function nil
4332 "Function to call to \"quit\" the current buffer, or nil if none.
4333 \\[keyboard-escape-quit] calls this function when its more local actions
4334 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4336 (defun keyboard-escape-quit ()
4337 "Exit the current \"mode\" (in a generalized sense of the word).
4338 This command can exit an interactive command such as `query-replace',
4339 can clear out a prefix argument or a region,
4340 can get out of the minibuffer or other recursive edit,
4341 cancel the use of the current buffer (for special-purpose buffers),
4342 or go back to just one window (by deleting all but the selected window)."
4343 (interactive)
4344 (cond ((eq last-command 'mode-exited) nil)
4345 ((> (minibuffer-depth) 0)
4346 (abort-recursive-edit))
4347 (current-prefix-arg
4348 nil)
4349 ((and transient-mark-mode mark-active)
4350 (deactivate-mark))
4351 ((> (recursion-depth) 0)
4352 (exit-recursive-edit))
4353 (buffer-quit-function
4354 (funcall buffer-quit-function))
4355 ((not (one-window-p t))
4356 (delete-other-windows))
4357 ((string-match "^ \\*" (buffer-name (current-buffer)))
4358 (bury-buffer))))
4360 (defun play-sound-file (file &optional volume device)
4361 "Play sound stored in FILE.
4362 VOLUME and DEVICE correspond to the keywords of the sound
4363 specification for `play-sound'."
4364 (interactive "fPlay sound file: ")
4365 (let ((sound (list :file file)))
4366 (if volume
4367 (plist-put sound :volume volume))
4368 (if device
4369 (plist-put sound :device device))
4370 (push 'sound sound)
4371 (play-sound sound)))
4374 (defcustom read-mail-command 'rmail
4375 "*Your preference for a mail reading package.
4376 This is used by some keybindings which support reading mail.
4377 See also `mail-user-agent' concerning sending mail."
4378 :type '(choice (function-item rmail)
4379 (function-item gnus)
4380 (function-item mh-rmail)
4381 (function :tag "Other"))
4382 :version "21.1"
4383 :group 'mail)
4385 (defcustom mail-user-agent 'sendmail-user-agent
4386 "*Your preference for a mail composition package.
4387 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
4388 outgoing email message. This variable lets you specify which
4389 mail-sending package you prefer.
4391 Valid values include:
4393 `sendmail-user-agent' -- use the default Emacs Mail package.
4394 See Info node `(emacs)Sending Mail'.
4395 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
4396 See Info node `(mh-e)'.
4397 `message-user-agent' -- use the Gnus Message package.
4398 See Info node `(message)'.
4399 `gnus-user-agent' -- like `message-user-agent', but with Gnus
4400 paraphernalia, particularly the Gcc: header for
4401 archiving.
4403 Additional valid symbols may be available; check with the author of
4404 your package for details. The function should return non-nil if it
4405 succeeds.
4407 See also `read-mail-command' concerning reading mail."
4408 :type '(radio (function-item :tag "Default Emacs mail"
4409 :format "%t\n"
4410 sendmail-user-agent)
4411 (function-item :tag "Emacs interface to MH"
4412 :format "%t\n"
4413 mh-e-user-agent)
4414 (function-item :tag "Gnus Message package"
4415 :format "%t\n"
4416 message-user-agent)
4417 (function-item :tag "Gnus Message with full Gnus features"
4418 :format "%t\n"
4419 gnus-user-agent)
4420 (function :tag "Other"))
4421 :group 'mail)
4423 (define-mail-user-agent 'sendmail-user-agent
4424 'sendmail-user-agent-compose
4425 'mail-send-and-exit)
4427 (defun rfc822-goto-eoh ()
4428 ;; Go to header delimiter line in a mail message, following RFC822 rules
4429 (goto-char (point-min))
4430 (when (re-search-forward
4431 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
4432 (goto-char (match-beginning 0))))
4434 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
4435 switch-function yank-action
4436 send-actions)
4437 (if switch-function
4438 (let ((special-display-buffer-names nil)
4439 (special-display-regexps nil)
4440 (same-window-buffer-names nil)
4441 (same-window-regexps nil))
4442 (funcall switch-function "*mail*")))
4443 (let ((cc (cdr (assoc-string "cc" other-headers t)))
4444 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
4445 (body (cdr (assoc-string "body" other-headers t))))
4446 (or (mail continue to subject in-reply-to cc yank-action send-actions)
4447 continue
4448 (error "Message aborted"))
4449 (save-excursion
4450 (rfc822-goto-eoh)
4451 (while other-headers
4452 (unless (member-ignore-case (car (car other-headers))
4453 '("in-reply-to" "cc" "body"))
4454 (insert (car (car other-headers)) ": "
4455 (cdr (car other-headers)) "\n"))
4456 (setq other-headers (cdr other-headers)))
4457 (when body
4458 (forward-line 1)
4459 (insert body))
4460 t)))
4462 (define-mail-user-agent 'mh-e-user-agent
4463 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
4464 'mh-before-send-letter-hook)
4466 (defun compose-mail (&optional to subject other-headers continue
4467 switch-function yank-action send-actions)
4468 "Start composing a mail message to send.
4469 This uses the user's chosen mail composition package
4470 as selected with the variable `mail-user-agent'.
4471 The optional arguments TO and SUBJECT specify recipients
4472 and the initial Subject field, respectively.
4474 OTHER-HEADERS is an alist specifying additional
4475 header fields. Elements look like (HEADER . VALUE) where both
4476 HEADER and VALUE are strings.
4478 CONTINUE, if non-nil, says to continue editing a message already
4479 being composed.
4481 SWITCH-FUNCTION, if non-nil, is a function to use to
4482 switch to and display the buffer used for mail composition.
4484 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
4485 to insert the raw text of the message being replied to.
4486 It has the form (FUNCTION . ARGS). The user agent will apply
4487 FUNCTION to ARGS, to insert the raw text of the original message.
4488 \(The user agent will also run `mail-citation-hook', *after* the
4489 original text has been inserted in this way.)
4491 SEND-ACTIONS is a list of actions to call when the message is sent.
4492 Each action has the form (FUNCTION . ARGS)."
4493 (interactive
4494 (list nil nil nil current-prefix-arg))
4495 (let ((function (get mail-user-agent 'composefunc)))
4496 (funcall function to subject other-headers continue
4497 switch-function yank-action send-actions)))
4499 (defun compose-mail-other-window (&optional to subject other-headers continue
4500 yank-action send-actions)
4501 "Like \\[compose-mail], but edit the outgoing message in another window."
4502 (interactive
4503 (list nil nil nil current-prefix-arg))
4504 (compose-mail to subject other-headers continue
4505 'switch-to-buffer-other-window yank-action send-actions))
4508 (defun compose-mail-other-frame (&optional to subject other-headers continue
4509 yank-action send-actions)
4510 "Like \\[compose-mail], but edit the outgoing message in another frame."
4511 (interactive
4512 (list nil nil nil current-prefix-arg))
4513 (compose-mail to subject other-headers continue
4514 'switch-to-buffer-other-frame yank-action send-actions))
4516 (defvar set-variable-value-history nil
4517 "History of values entered with `set-variable'.")
4519 (defun set-variable (variable value &optional make-local)
4520 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4521 VARIABLE should be a user option variable name, a Lisp variable
4522 meant to be customized by users. You should enter VALUE in Lisp syntax,
4523 so if you want VALUE to be a string, you must surround it with doublequotes.
4524 VALUE is used literally, not evaluated.
4526 If VARIABLE has a `variable-interactive' property, that is used as if
4527 it were the arg to `interactive' (which see) to interactively read VALUE.
4529 If VARIABLE has been defined with `defcustom', then the type information
4530 in the definition is used to check that VALUE is valid.
4532 With a prefix argument, set VARIABLE to VALUE buffer-locally."
4533 (interactive
4534 (let* ((default-var (variable-at-point))
4535 (var (if (symbolp default-var)
4536 (read-variable (format "Set variable (default %s): " default-var)
4537 default-var)
4538 (read-variable "Set variable: ")))
4539 (minibuffer-help-form '(describe-variable var))
4540 (prop (get var 'variable-interactive))
4541 (obsolete (car (get var 'byte-obsolete-variable)))
4542 (prompt (format "Set %s %s to value: " var
4543 (cond ((local-variable-p var)
4544 "(buffer-local)")
4545 ((or current-prefix-arg
4546 (local-variable-if-set-p var))
4547 "buffer-locally")
4548 (t "globally"))))
4549 (val (progn
4550 (when obsolete
4551 (message (concat "`%S' is obsolete; "
4552 (if (symbolp obsolete) "use `%S' instead" "%s"))
4553 var obsolete)
4554 (sit-for 3))
4555 (if prop
4556 ;; Use VAR's `variable-interactive' property
4557 ;; as an interactive spec for prompting.
4558 (call-interactively `(lambda (arg)
4559 (interactive ,prop)
4560 arg))
4561 (read
4562 (read-string prompt nil
4563 'set-variable-value-history))))))
4564 (list var val current-prefix-arg)))
4566 (and (custom-variable-p variable)
4567 (not (get variable 'custom-type))
4568 (custom-load-symbol variable))
4569 (let ((type (get variable 'custom-type)))
4570 (when type
4571 ;; Match with custom type.
4572 (require 'cus-edit)
4573 (setq type (widget-convert type))
4574 (unless (widget-apply type :match value)
4575 (error "Value `%S' does not match type %S of %S"
4576 value (car type) variable))))
4578 (if make-local
4579 (make-local-variable variable))
4581 (set variable value)
4583 ;; Force a thorough redisplay for the case that the variable
4584 ;; has an effect on the display, like `tab-width' has.
4585 (force-mode-line-update))
4587 ;; Define the major mode for lists of completions.
4589 (defvar completion-list-mode-map nil
4590 "Local map for completion list buffers.")
4591 (or completion-list-mode-map
4592 (let ((map (make-sparse-keymap)))
4593 (define-key map [mouse-2] 'mouse-choose-completion)
4594 (define-key map [follow-link] 'mouse-face)
4595 (define-key map [down-mouse-2] nil)
4596 (define-key map "\C-m" 'choose-completion)
4597 (define-key map "\e\e\e" 'delete-completion-window)
4598 (define-key map [left] 'previous-completion)
4599 (define-key map [right] 'next-completion)
4600 (setq completion-list-mode-map map)))
4602 ;; Completion mode is suitable only for specially formatted data.
4603 (put 'completion-list-mode 'mode-class 'special)
4605 (defvar completion-reference-buffer nil
4606 "Record the buffer that was current when the completion list was requested.
4607 This is a local variable in the completion list buffer.
4608 Initial value is nil to avoid some compiler warnings.")
4610 (defvar completion-no-auto-exit nil
4611 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4612 This also applies to other functions such as `choose-completion'
4613 and `mouse-choose-completion'.")
4615 (defvar completion-base-size nil
4616 "Number of chars at beginning of minibuffer not involved in completion.
4617 This is a local variable in the completion list buffer
4618 but it talks about the buffer in `completion-reference-buffer'.
4619 If this is nil, it means to compare text to determine which part
4620 of the tail end of the buffer's text is involved in completion.")
4622 (defun delete-completion-window ()
4623 "Delete the completion list window.
4624 Go to the window from which completion was requested."
4625 (interactive)
4626 (let ((buf completion-reference-buffer))
4627 (if (one-window-p t)
4628 (if (window-dedicated-p (selected-window))
4629 (delete-frame (selected-frame)))
4630 (delete-window (selected-window))
4631 (if (get-buffer-window buf)
4632 (select-window (get-buffer-window buf))))))
4634 (defun previous-completion (n)
4635 "Move to the previous item in the completion list."
4636 (interactive "p")
4637 (next-completion (- n)))
4639 (defun next-completion (n)
4640 "Move to the next item in the completion list.
4641 With prefix argument N, move N items (negative N means move backward)."
4642 (interactive "p")
4643 (let ((beg (point-min)) (end (point-max)))
4644 (while (and (> n 0) (not (eobp)))
4645 ;; If in a completion, move to the end of it.
4646 (when (get-text-property (point) 'mouse-face)
4647 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4648 ;; Move to start of next one.
4649 (unless (get-text-property (point) 'mouse-face)
4650 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4651 (setq n (1- n)))
4652 (while (and (< n 0) (not (bobp)))
4653 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4654 ;; If in a completion, move to the start of it.
4655 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
4656 (goto-char (previous-single-property-change
4657 (point) 'mouse-face nil beg)))
4658 ;; Move to end of the previous completion.
4659 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4660 (goto-char (previous-single-property-change
4661 (point) 'mouse-face nil beg)))
4662 ;; Move to the start of that one.
4663 (goto-char (previous-single-property-change
4664 (point) 'mouse-face nil beg))
4665 (setq n (1+ n))))))
4667 (defun choose-completion ()
4668 "Choose the completion that point is in or next to."
4669 (interactive)
4670 (let (beg end completion (buffer completion-reference-buffer)
4671 (base-size completion-base-size))
4672 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4673 (setq end (point) beg (1+ (point))))
4674 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
4675 (setq end (1- (point)) beg (point)))
4676 (if (null beg)
4677 (error "No completion here"))
4678 (setq beg (previous-single-property-change beg 'mouse-face))
4679 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
4680 (setq completion (buffer-substring beg end))
4681 (let ((owindow (selected-window)))
4682 (if (and (one-window-p t 'selected-frame)
4683 (window-dedicated-p (selected-window)))
4684 ;; This is a special buffer's frame
4685 (iconify-frame (selected-frame))
4686 (or (window-dedicated-p (selected-window))
4687 (bury-buffer)))
4688 (select-window owindow))
4689 (choose-completion-string completion buffer base-size)))
4691 ;; Delete the longest partial match for STRING
4692 ;; that can be found before POINT.
4693 (defun choose-completion-delete-max-match (string)
4694 (let ((opoint (point))
4695 len)
4696 ;; Try moving back by the length of the string.
4697 (goto-char (max (- (point) (length string))
4698 (minibuffer-prompt-end)))
4699 ;; See how far back we were actually able to move. That is the
4700 ;; upper bound on how much we can match and delete.
4701 (setq len (- opoint (point)))
4702 (if completion-ignore-case
4703 (setq string (downcase string)))
4704 (while (and (> len 0)
4705 (let ((tail (buffer-substring (point) opoint)))
4706 (if completion-ignore-case
4707 (setq tail (downcase tail)))
4708 (not (string= tail (substring string 0 len)))))
4709 (setq len (1- len))
4710 (forward-char 1))
4711 (delete-char len)))
4713 (defvar choose-completion-string-functions nil
4714 "Functions that may override the normal insertion of a completion choice.
4715 These functions are called in order with four arguments:
4716 CHOICE - the string to insert in the buffer,
4717 BUFFER - the buffer in which the choice should be inserted,
4718 MINI-P - non-nil iff BUFFER is a minibuffer, and
4719 BASE-SIZE - the number of characters in BUFFER before
4720 the string being completed.
4722 If a function in the list returns non-nil, that function is supposed
4723 to have inserted the CHOICE in the BUFFER, and possibly exited
4724 the minibuffer; no further functions will be called.
4726 If all functions in the list return nil, that means to use
4727 the default method of inserting the completion in BUFFER.")
4729 (defun choose-completion-string (choice &optional buffer base-size)
4730 "Switch to BUFFER and insert the completion choice CHOICE.
4731 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
4732 to keep. If it is nil, we call `choose-completion-delete-max-match'
4733 to decide what to delete."
4735 ;; If BUFFER is the minibuffer, exit the minibuffer
4736 ;; unless it is reading a file name and CHOICE is a directory,
4737 ;; or completion-no-auto-exit is non-nil.
4739 (let* ((buffer (or buffer completion-reference-buffer))
4740 (mini-p (minibufferp buffer)))
4741 ;; If BUFFER is a minibuffer, barf unless it's the currently
4742 ;; active minibuffer.
4743 (if (and mini-p
4744 (or (not (active-minibuffer-window))
4745 (not (equal buffer
4746 (window-buffer (active-minibuffer-window))))))
4747 (error "Minibuffer is not active for completion")
4748 ;; Set buffer so buffer-local choose-completion-string-functions works.
4749 (set-buffer buffer)
4750 (unless (run-hook-with-args-until-success
4751 'choose-completion-string-functions
4752 choice buffer mini-p base-size)
4753 ;; Insert the completion into the buffer where it was requested.
4754 (if base-size
4755 (delete-region (+ base-size (if mini-p
4756 (minibuffer-prompt-end)
4757 (point-min)))
4758 (point))
4759 (choose-completion-delete-max-match choice))
4760 (insert choice)
4761 (remove-text-properties (- (point) (length choice)) (point)
4762 '(mouse-face nil))
4763 ;; Update point in the window that BUFFER is showing in.
4764 (let ((window (get-buffer-window buffer t)))
4765 (set-window-point window (point)))
4766 ;; If completing for the minibuffer, exit it with this choice.
4767 (and (not completion-no-auto-exit)
4768 (equal buffer (window-buffer (minibuffer-window)))
4769 minibuffer-completion-table
4770 ;; If this is reading a file name, and the file name chosen
4771 ;; is a directory, don't exit the minibuffer.
4772 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4773 (file-directory-p (field-string (point-max))))
4774 (let ((mini (active-minibuffer-window)))
4775 (select-window mini)
4776 (when minibuffer-auto-raise
4777 (raise-frame (window-frame mini))))
4778 (exit-minibuffer)))))))
4780 (defun completion-list-mode ()
4781 "Major mode for buffers showing lists of possible completions.
4782 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4783 to select the completion near point.
4784 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4785 with the mouse."
4786 (interactive)
4787 (kill-all-local-variables)
4788 (use-local-map completion-list-mode-map)
4789 (setq mode-name "Completion List")
4790 (setq major-mode 'completion-list-mode)
4791 (make-local-variable 'completion-base-size)
4792 (setq completion-base-size nil)
4793 (run-mode-hooks 'completion-list-mode-hook))
4795 (defun completion-list-mode-finish ()
4796 "Finish setup of the completions buffer.
4797 Called from `temp-buffer-show-hook'."
4798 (when (eq major-mode 'completion-list-mode)
4799 (toggle-read-only 1)))
4801 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4803 (defvar completion-setup-hook nil
4804 "Normal hook run at the end of setting up a completion list buffer.
4805 When this hook is run, the current buffer is the one in which the
4806 command to display the completion list buffer was run.
4807 The completion list buffer is available as the value of `standard-output'.")
4809 ;; This function goes in completion-setup-hook, so that it is called
4810 ;; after the text of the completion list buffer is written.
4811 (defface completions-first-difference
4812 '((t (:inherit bold)))
4813 "Face put on the first uncommon character in completions in *Completions* buffer."
4814 :group 'completion)
4816 (defface completions-common-part
4817 '((t (:inherit default)))
4818 "Face put on the common prefix substring in completions in *Completions* buffer.
4819 The idea of `completions-common-part' is that you can use it to
4820 make the common parts less visible than normal, so that the rest
4821 of the differing parts is, by contrast, slightly highlighted."
4822 :group 'completion)
4824 ;; This is for packages that need to bind it to a non-default regexp
4825 ;; in order to make the first-differing character highlight work
4826 ;; to their liking
4827 (defvar completion-root-regexp "^/"
4828 "Regexp to use in `completion-setup-function' to find the root directory.")
4830 (defun completion-setup-function ()
4831 (let ((mainbuf (current-buffer))
4832 (mbuf-contents (minibuffer-contents)))
4833 ;; When reading a file name in the minibuffer,
4834 ;; set default-directory in the minibuffer
4835 ;; so it will get copied into the completion list buffer.
4836 (if minibuffer-completing-file-name
4837 (with-current-buffer mainbuf
4838 (setq default-directory (file-name-directory mbuf-contents))))
4839 ;; If partial-completion-mode is on, point might not be after the
4840 ;; last character in the minibuffer.
4841 ;; FIXME: This still doesn't work if the text to be completed
4842 ;; starts with a `-'.
4843 (when (and partial-completion-mode (not (eobp)))
4844 (setq mbuf-contents
4845 (substring mbuf-contents 0 (- (point) (point-max)))))
4846 (with-current-buffer standard-output
4847 (completion-list-mode)
4848 (make-local-variable 'completion-reference-buffer)
4849 (setq completion-reference-buffer mainbuf)
4850 (if minibuffer-completing-file-name
4851 ;; For file name completion,
4852 ;; use the number of chars before the start of the
4853 ;; last file name component.
4854 (setq completion-base-size
4855 (with-current-buffer mainbuf
4856 (save-excursion
4857 (goto-char (point-max))
4858 (skip-chars-backward completion-root-regexp)
4859 (- (point) (minibuffer-prompt-end)))))
4860 ;; Otherwise, in minibuffer, the whole input is being completed.
4861 (if (minibufferp mainbuf)
4862 (if (and (symbolp minibuffer-completion-table)
4863 (get minibuffer-completion-table 'completion-base-size-function))
4864 (setq completion-base-size
4865 (funcall (get minibuffer-completion-table 'completion-base-size-function)))
4866 (setq completion-base-size 0))))
4867 ;; Put faces on first uncommon characters and common parts.
4868 (when completion-base-size
4869 (let* ((common-string-length
4870 (- (length mbuf-contents) completion-base-size))
4871 (element-start (next-single-property-change
4872 (point-min)
4873 'mouse-face))
4874 (element-common-end
4875 (and element-start
4876 (+ (or element-start nil) common-string-length)))
4877 (maxp (point-max)))
4878 (while (and element-start (< element-common-end maxp))
4879 (when (and (get-char-property element-start 'mouse-face)
4880 (get-char-property element-common-end 'mouse-face))
4881 (put-text-property element-start element-common-end
4882 'font-lock-face 'completions-common-part)
4883 (put-text-property element-common-end (1+ element-common-end)
4884 'font-lock-face 'completions-first-difference))
4885 (setq element-start (next-single-property-change
4886 element-start
4887 'mouse-face))
4888 (if element-start
4889 (setq element-common-end (+ element-start common-string-length))))))
4890 ;; Insert help string.
4891 (goto-char (point-min))
4892 (if (display-mouse-p)
4893 (insert (substitute-command-keys
4894 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4895 (insert (substitute-command-keys
4896 "In this buffer, type \\[choose-completion] to \
4897 select the completion near point.\n\n")))))
4899 (add-hook 'completion-setup-hook 'completion-setup-function)
4901 (define-key minibuffer-local-completion-map [prior]
4902 'switch-to-completions)
4903 (define-key minibuffer-local-must-match-map [prior]
4904 'switch-to-completions)
4905 (define-key minibuffer-local-completion-map "\M-v"
4906 'switch-to-completions)
4907 (define-key minibuffer-local-must-match-map "\M-v"
4908 'switch-to-completions)
4910 (defun switch-to-completions ()
4911 "Select the completion list window."
4912 (interactive)
4913 ;; Make sure we have a completions window.
4914 (or (get-buffer-window "*Completions*")
4915 (minibuffer-completion-help))
4916 (let ((window (get-buffer-window "*Completions*")))
4917 (when window
4918 (select-window window)
4919 (goto-char (point-min))
4920 (search-forward "\n\n")
4921 (forward-line 1))))
4923 ;; Support keyboard commands to turn on various modifiers.
4925 ;; These functions -- which are not commands -- each add one modifier
4926 ;; to the following event.
4928 (defun event-apply-alt-modifier (ignore-prompt)
4929 "\\<function-key-map>Add the Alt modifier to the following event.
4930 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
4931 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4932 (defun event-apply-super-modifier (ignore-prompt)
4933 "\\<function-key-map>Add the Super modifier to the following event.
4934 For example, type \\[event-apply-super-modifier] & to enter Super-&."
4935 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4936 (defun event-apply-hyper-modifier (ignore-prompt)
4937 "\\<function-key-map>Add the Hyper modifier to the following event.
4938 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
4939 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4940 (defun event-apply-shift-modifier (ignore-prompt)
4941 "\\<function-key-map>Add the Shift modifier to the following event.
4942 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
4943 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4944 (defun event-apply-control-modifier (ignore-prompt)
4945 "\\<function-key-map>Add the Ctrl modifier to the following event.
4946 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
4947 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4948 (defun event-apply-meta-modifier (ignore-prompt)
4949 "\\<function-key-map>Add the Meta modifier to the following event.
4950 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
4951 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4953 (defun event-apply-modifier (event symbol lshiftby prefix)
4954 "Apply a modifier flag to event EVENT.
4955 SYMBOL is the name of this modifier, as a symbol.
4956 LSHIFTBY is the numeric value of this modifier, in keyboard events.
4957 PREFIX is the string that represents this modifier in an event type symbol."
4958 (if (numberp event)
4959 (cond ((eq symbol 'control)
4960 (if (and (<= (downcase event) ?z)
4961 (>= (downcase event) ?a))
4962 (- (downcase event) ?a -1)
4963 (if (and (<= (downcase event) ?Z)
4964 (>= (downcase event) ?A))
4965 (- (downcase event) ?A -1)
4966 (logior (lsh 1 lshiftby) event))))
4967 ((eq symbol 'shift)
4968 (if (and (<= (downcase event) ?z)
4969 (>= (downcase event) ?a))
4970 (upcase event)
4971 (logior (lsh 1 lshiftby) event)))
4973 (logior (lsh 1 lshiftby) event)))
4974 (if (memq symbol (event-modifiers event))
4975 event
4976 (let ((event-type (if (symbolp event) event (car event))))
4977 (setq event-type (intern (concat prefix (symbol-name event-type))))
4978 (if (symbolp event)
4979 event-type
4980 (cons event-type (cdr event)))))))
4982 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4983 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4984 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4985 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4986 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4987 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
4989 ;;;; Keypad support.
4991 ;;; Make the keypad keys act like ordinary typing keys. If people add
4992 ;;; bindings for the function key symbols, then those bindings will
4993 ;;; override these, so this shouldn't interfere with any existing
4994 ;;; bindings.
4996 ;; Also tell read-char how to handle these keys.
4997 (mapc
4998 (lambda (keypad-normal)
4999 (let ((keypad (nth 0 keypad-normal))
5000 (normal (nth 1 keypad-normal)))
5001 (put keypad 'ascii-character normal)
5002 (define-key function-key-map (vector keypad) (vector normal))))
5003 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
5004 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
5005 (kp-space ?\ )
5006 (kp-tab ?\t)
5007 (kp-enter ?\r)
5008 (kp-multiply ?*)
5009 (kp-add ?+)
5010 (kp-separator ?,)
5011 (kp-subtract ?-)
5012 (kp-decimal ?.)
5013 (kp-divide ?/)
5014 (kp-equal ?=)))
5016 ;;;;
5017 ;;;; forking a twin copy of a buffer.
5018 ;;;;
5020 (defvar clone-buffer-hook nil
5021 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5023 (defun clone-process (process &optional newname)
5024 "Create a twin copy of PROCESS.
5025 If NEWNAME is nil, it defaults to PROCESS' name;
5026 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5027 If PROCESS is associated with a buffer, the new process will be associated
5028 with the current buffer instead.
5029 Returns nil if PROCESS has already terminated."
5030 (setq newname (or newname (process-name process)))
5031 (if (string-match "<[0-9]+>\\'" newname)
5032 (setq newname (substring newname 0 (match-beginning 0))))
5033 (when (memq (process-status process) '(run stop open))
5034 (let* ((process-connection-type (process-tty-name process))
5035 (new-process
5036 (if (memq (process-status process) '(open))
5037 (let ((args (process-contact process t)))
5038 (setq args (plist-put args :name newname))
5039 (setq args (plist-put args :buffer
5040 (if (process-buffer process)
5041 (current-buffer))))
5042 (apply 'make-network-process args))
5043 (apply 'start-process newname
5044 (if (process-buffer process) (current-buffer))
5045 (process-command process)))))
5046 (set-process-query-on-exit-flag
5047 new-process (process-query-on-exit-flag process))
5048 (set-process-inherit-coding-system-flag
5049 new-process (process-inherit-coding-system-flag process))
5050 (set-process-filter new-process (process-filter process))
5051 (set-process-sentinel new-process (process-sentinel process))
5052 (set-process-plist new-process (copy-sequence (process-plist process)))
5053 new-process)))
5055 ;; things to maybe add (currently partly covered by `funcall mode'):
5056 ;; - syntax-table
5057 ;; - overlays
5058 (defun clone-buffer (&optional newname display-flag)
5059 "Create and return a twin copy of the current buffer.
5060 Unlike an indirect buffer, the new buffer can be edited
5061 independently of the old one (if it is not read-only).
5062 NEWNAME is the name of the new buffer. It may be modified by
5063 adding or incrementing <N> at the end as necessary to create a
5064 unique buffer name. If nil, it defaults to the name of the
5065 current buffer, with the proper suffix. If DISPLAY-FLAG is
5066 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
5067 clone a file-visiting buffer, or a buffer whose major mode symbol
5068 has a non-nil `no-clone' property, results in an error.
5070 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
5071 current buffer with appropriate suffix. However, if a prefix
5072 argument is given, then the command prompts for NEWNAME in the
5073 minibuffer.
5075 This runs the normal hook `clone-buffer-hook' in the new buffer
5076 after it has been set up properly in other respects."
5077 (interactive
5078 (progn
5079 (if buffer-file-name
5080 (error "Cannot clone a file-visiting buffer"))
5081 (if (get major-mode 'no-clone)
5082 (error "Cannot clone a buffer in %s mode" mode-name))
5083 (list (if current-prefix-arg (read-string "Name: "))
5084 t)))
5085 (if buffer-file-name
5086 (error "Cannot clone a file-visiting buffer"))
5087 (if (get major-mode 'no-clone)
5088 (error "Cannot clone a buffer in %s mode" mode-name))
5089 (setq newname (or newname (buffer-name)))
5090 (if (string-match "<[0-9]+>\\'" newname)
5091 (setq newname (substring newname 0 (match-beginning 0))))
5092 (let ((buf (current-buffer))
5093 (ptmin (point-min))
5094 (ptmax (point-max))
5095 (pt (point))
5096 (mk (if mark-active (mark t)))
5097 (modified (buffer-modified-p))
5098 (mode major-mode)
5099 (lvars (buffer-local-variables))
5100 (process (get-buffer-process (current-buffer)))
5101 (new (generate-new-buffer (or newname (buffer-name)))))
5102 (save-restriction
5103 (widen)
5104 (with-current-buffer new
5105 (insert-buffer-substring buf)))
5106 (with-current-buffer new
5107 (narrow-to-region ptmin ptmax)
5108 (goto-char pt)
5109 (if mk (set-mark mk))
5110 (set-buffer-modified-p modified)
5112 ;; Clone the old buffer's process, if any.
5113 (when process (clone-process process))
5115 ;; Now set up the major mode.
5116 (funcall mode)
5118 ;; Set up other local variables.
5119 (mapcar (lambda (v)
5120 (condition-case () ;in case var is read-only
5121 (if (symbolp v)
5122 (makunbound v)
5123 (set (make-local-variable (car v)) (cdr v)))
5124 (error nil)))
5125 lvars)
5127 ;; Run any hooks (typically set up by the major mode
5128 ;; for cloning to work properly).
5129 (run-hooks 'clone-buffer-hook))
5130 (if display-flag (pop-to-buffer new))
5131 new))
5134 (defun clone-indirect-buffer (newname display-flag &optional norecord)
5135 "Create an indirect buffer that is a twin copy of the current buffer.
5137 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
5138 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
5139 or if not called with a prefix arg, NEWNAME defaults to the current
5140 buffer's name. The name is modified by adding a `<N>' suffix to it
5141 or by incrementing the N in an existing suffix.
5143 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
5144 This is always done when called interactively.
5146 Optional last arg NORECORD non-nil means do not put this buffer at the
5147 front of the list of recently selected ones."
5148 (interactive
5149 (progn
5150 (if (get major-mode 'no-clone-indirect)
5151 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5152 (list (if current-prefix-arg
5153 (read-string "BName of indirect buffer: "))
5154 t)))
5155 (if (get major-mode 'no-clone-indirect)
5156 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5157 (setq newname (or newname (buffer-name)))
5158 (if (string-match "<[0-9]+>\\'" newname)
5159 (setq newname (substring newname 0 (match-beginning 0))))
5160 (let* ((name (generate-new-buffer-name newname))
5161 (buffer (make-indirect-buffer (current-buffer) name t)))
5162 (when display-flag
5163 (pop-to-buffer buffer norecord))
5164 buffer))
5167 (defun clone-indirect-buffer-other-window (buffer &optional norecord)
5168 "Create an indirect buffer that is a twin copy of BUFFER.
5169 Select the new buffer in another window.
5170 Optional second arg NORECORD non-nil means do not put this buffer at
5171 the front of the list of recently selected ones."
5172 (interactive "bClone buffer in other window: ")
5173 (let ((pop-up-windows t))
5174 (set-buffer buffer)
5175 (clone-indirect-buffer nil t norecord)))
5178 ;;; Handling of Backspace and Delete keys.
5180 (defcustom normal-erase-is-backspace
5181 (and (not noninteractive)
5182 (or (memq system-type '(ms-dos windows-nt))
5183 (eq window-system 'mac)
5184 (and (memq window-system '(x))
5185 (fboundp 'x-backspace-delete-keys-p)
5186 (x-backspace-delete-keys-p))
5187 ;; If the terminal Emacs is running on has erase char
5188 ;; set to ^H, use the Backspace key for deleting
5189 ;; backward and, and the Delete key for deleting forward.
5190 (and (null window-system)
5191 (eq tty-erase-char ?\^H))))
5192 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
5194 On window systems, the default value of this option is chosen
5195 according to the keyboard used. If the keyboard has both a Backspace
5196 key and a Delete key, and both are mapped to their usual meanings, the
5197 option's default value is set to t, so that Backspace can be used to
5198 delete backward, and Delete can be used to delete forward.
5200 If not running under a window system, customizing this option accomplishes
5201 a similar effect by mapping C-h, which is usually generated by the
5202 Backspace key, to DEL, and by mapping DEL to C-d via
5203 `keyboard-translate'. The former functionality of C-h is available on
5204 the F1 key. You should probably not use this setting if you don't
5205 have both Backspace, Delete and F1 keys.
5207 Setting this variable with setq doesn't take effect. Programmatically,
5208 call `normal-erase-is-backspace-mode' (which see) instead."
5209 :type 'boolean
5210 :group 'editing-basics
5211 :version "21.1"
5212 :set (lambda (symbol value)
5213 ;; The fboundp is because of a problem with :set when
5214 ;; dumping Emacs. It doesn't really matter.
5215 (if (fboundp 'normal-erase-is-backspace-mode)
5216 (normal-erase-is-backspace-mode (or value 0))
5217 (set-default symbol value))))
5220 (defun normal-erase-is-backspace-mode (&optional arg)
5221 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5223 With numeric arg, turn the mode on if and only if ARG is positive.
5225 On window systems, when this mode is on, Delete is mapped to C-d and
5226 Backspace is mapped to DEL; when this mode is off, both Delete and
5227 Backspace are mapped to DEL. (The remapping goes via
5228 `function-key-map', so binding Delete or Backspace in the global or
5229 local keymap will override that.)
5231 In addition, on window systems, the bindings of C-Delete, M-Delete,
5232 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5233 the global keymap in accordance with the functionality of Delete and
5234 Backspace. For example, if Delete is remapped to C-d, which deletes
5235 forward, C-Delete is bound to `kill-word', but if Delete is remapped
5236 to DEL, which deletes backward, C-Delete is bound to
5237 `backward-kill-word'.
5239 If not running on a window system, a similar effect is accomplished by
5240 remapping C-h (normally produced by the Backspace key) and DEL via
5241 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5242 to C-d; if it's off, the keys are not remapped.
5244 When not running on a window system, and this mode is turned on, the
5245 former functionality of C-h is available on the F1 key. You should
5246 probably not turn on this mode on a text-only terminal if you don't
5247 have both Backspace, Delete and F1 keys.
5249 See also `normal-erase-is-backspace'."
5250 (interactive "P")
5251 (setq normal-erase-is-backspace
5252 (if arg
5253 (> (prefix-numeric-value arg) 0)
5254 (not normal-erase-is-backspace)))
5256 (cond ((or (memq window-system '(x w32 mac pc))
5257 (memq system-type '(ms-dos windows-nt)))
5258 (let ((bindings
5259 `(([C-delete] [C-backspace])
5260 ([M-delete] [M-backspace])
5261 ([C-M-delete] [C-M-backspace])
5262 (,esc-map
5263 [C-delete] [C-backspace])))
5264 (old-state (lookup-key function-key-map [delete])))
5266 (if normal-erase-is-backspace
5267 (progn
5268 (define-key function-key-map [delete] [?\C-d])
5269 (define-key function-key-map [kp-delete] [?\C-d])
5270 (define-key function-key-map [backspace] [?\C-?]))
5271 (define-key function-key-map [delete] [?\C-?])
5272 (define-key function-key-map [kp-delete] [?\C-?])
5273 (define-key function-key-map [backspace] [?\C-?]))
5275 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5276 (unless (equal old-state (lookup-key function-key-map [delete]))
5277 (dolist (binding bindings)
5278 (let ((map global-map))
5279 (when (keymapp (car binding))
5280 (setq map (car binding) binding (cdr binding)))
5281 (let* ((key1 (nth 0 binding))
5282 (key2 (nth 1 binding))
5283 (binding1 (lookup-key map key1))
5284 (binding2 (lookup-key map key2)))
5285 (define-key map key1 binding2)
5286 (define-key map key2 binding1)))))))
5288 (if normal-erase-is-backspace
5289 (progn
5290 (keyboard-translate ?\C-h ?\C-?)
5291 (keyboard-translate ?\C-? ?\C-d))
5292 (keyboard-translate ?\C-h ?\C-h)
5293 (keyboard-translate ?\C-? ?\C-?))))
5295 (run-hooks 'normal-erase-is-backspace-hook)
5296 (if (interactive-p)
5297 (message "Delete key deletes %s"
5298 (if normal-erase-is-backspace "forward" "backward"))))
5300 (defvar vis-mode-saved-buffer-invisibility-spec nil
5301 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
5303 (define-minor-mode visible-mode
5304 "Toggle Visible mode.
5305 With argument ARG turn Visible mode on iff ARG is positive.
5307 Enabling Visible mode makes all invisible text temporarily visible.
5308 Disabling Visible mode turns off that effect. Visible mode
5309 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
5310 :lighter " Vis"
5311 :group 'editing-basics
5312 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
5313 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
5314 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
5315 (when visible-mode
5316 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
5317 buffer-invisibility-spec)
5318 (setq buffer-invisibility-spec nil)))
5320 ;; Minibuffer prompt stuff.
5322 ;(defun minibuffer-prompt-modification (start end)
5323 ; (error "You cannot modify the prompt"))
5326 ;(defun minibuffer-prompt-insertion (start end)
5327 ; (let ((inhibit-modification-hooks t))
5328 ; (delete-region start end)
5329 ; ;; Discard undo information for the text insertion itself
5330 ; ;; and for the text deletion.above.
5331 ; (when (consp buffer-undo-list)
5332 ; (setq buffer-undo-list (cddr buffer-undo-list)))
5333 ; (message "You cannot modify the prompt")))
5336 ;(setq minibuffer-prompt-properties
5337 ; (list 'modification-hooks '(minibuffer-prompt-modification)
5338 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
5341 (provide 'simple)
5343 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
5344 ;;; simple.el ends here