Revision: emacs@sv.gnu.org/emacs--devo--0--patch-57
[emacs.git] / lisp / simple.el
blob58b0ba2de571d4f0f1e59d52a829e7006f7558fb
1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 ;; 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
6 ;; Maintainer: FSF
7 ;; Keywords: internal
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
26 ;;; Commentary:
28 ;; A grab-bag of basic Emacs commands not specifically related to some
29 ;; major mode or to file-handling.
31 ;;; Code:
33 (eval-when-compile
34 (autoload 'widget-convert "wid-edit")
35 (autoload 'shell-mode "shell"))
37 (defvar compilation-current-error)
39 (defcustom idle-update-delay 0.5
40 "*Idle time delay before updating various things on the screen.
41 Various Emacs features that update auxiliary information when point moves
42 wait this many seconds after Emacs becomes idle before doing an update."
43 :type 'number
44 :group 'display
45 :version "22.1")
47 (defgroup killing nil
48 "Killing and yanking commands."
49 :group 'editing)
51 (defgroup paren-matching nil
52 "Highlight (un)matching of parens and expressions."
53 :group 'matching)
55 (defun get-next-valid-buffer (list &optional buffer visible-ok frame)
56 "Search LIST for a valid buffer to display in FRAME.
57 Return nil when all buffers in LIST are undesirable for display,
58 otherwise return the first suitable buffer in LIST.
60 Buffers not visible in windows are preferred to visible buffers,
61 unless VISIBLE-OK is non-nil.
62 If the optional argument FRAME is nil, it defaults to the selected frame.
63 If BUFFER is non-nil, ignore occurrences of that buffer in LIST."
64 ;; This logic is more or less copied from other-buffer.
65 (setq frame (or frame (selected-frame)))
66 (let ((pred (frame-parameter frame 'buffer-predicate))
67 found buf)
68 (while (and (not found) list)
69 (setq buf (car list))
70 (if (and (not (eq buffer buf))
71 (buffer-live-p buf)
72 (or (null pred) (funcall pred buf))
73 (not (eq (aref (buffer-name buf) 0) ?\s))
74 (or visible-ok (null (get-buffer-window buf 'visible))))
75 (setq found buf)
76 (setq list (cdr list))))
77 (car list)))
79 (defun last-buffer (&optional buffer visible-ok frame)
80 "Return the last non-hidden displayable buffer in the buffer list.
81 If BUFFER is non-nil, last-buffer will ignore that buffer.
82 Buffers not visible in windows are preferred to visible buffers,
83 unless optional argument VISIBLE-OK is non-nil.
84 If the optional third argument FRAME is non-nil, use that frame's
85 buffer list instead of the selected frame's buffer list.
86 If no other buffer exists, the buffer `*scratch*' is returned."
87 (setq frame (or frame (selected-frame)))
88 (or (get-next-valid-buffer (frame-parameter frame 'buried-buffer-list)
89 buffer visible-ok frame)
90 (get-next-valid-buffer (nreverse (buffer-list frame))
91 buffer visible-ok frame)
92 (progn
93 (set-buffer-major-mode (get-buffer-create "*scratch*"))
94 (get-buffer "*scratch*"))))
96 (defun next-buffer ()
97 "Switch to the next buffer in cyclic order."
98 (interactive)
99 (let ((buffer (current-buffer))
100 (bbl (frame-parameter nil 'buried-buffer-list)))
101 (switch-to-buffer (other-buffer buffer t))
102 (bury-buffer buffer)
103 (set-frame-parameter nil 'buried-buffer-list
104 (cons buffer (delq buffer bbl)))))
106 (defun previous-buffer ()
107 "Switch to the previous buffer in cyclic order."
108 (interactive)
109 (let ((buffer (last-buffer (current-buffer) t))
110 (bbl (frame-parameter nil 'buried-buffer-list)))
111 (switch-to-buffer buffer)
112 ;; Clean up buried-buffer-list up to and including the chosen buffer.
113 (while (and bbl (not (eq (car bbl) buffer)))
114 (setq bbl (cdr bbl)))
115 (set-frame-parameter nil 'buried-buffer-list bbl)))
118 ;;; next-error support framework
120 (defgroup next-error nil
121 "`next-error' support framework."
122 :group 'compilation
123 :version "22.1")
125 (defface next-error
126 '((t (:inherit region)))
127 "Face used to highlight next error locus."
128 :group 'next-error
129 :version "22.1")
131 (defcustom next-error-highlight 0.1
132 "*Highlighting of locations in selected source buffers.
133 If number, highlight the locus in `next-error' face for given time in seconds.
134 If t, use persistent overlays fontified in `next-error' face.
135 If nil, don't highlight the locus in the source buffer.
136 If `fringe-arrow', indicate the locus by the fringe arrow."
137 :type '(choice (number :tag "Delay")
138 (const :tag "Persistent overlay" t)
139 (const :tag "No highlighting" nil)
140 (const :tag "Fringe arrow" 'fringe-arrow))
141 :group 'next-error
142 :version "22.1")
144 (defcustom next-error-highlight-no-select 0.1
145 "*Highlighting of locations in non-selected source buffers.
146 If number, highlight the locus in `next-error' face for given time in seconds.
147 If t, use persistent overlays fontified in `next-error' face.
148 If nil, don't highlight the locus in the source buffer.
149 If `fringe-arrow', indicate the locus by the fringe arrow."
150 :type '(choice (number :tag "Delay")
151 (const :tag "Persistent overlay" t)
152 (const :tag "No highlighting" nil)
153 (const :tag "Fringe arrow" 'fringe-arrow))
154 :group 'next-error
155 :version "22.1")
157 (defcustom next-error-hook nil
158 "*List of hook functions run by `next-error' after visiting source file."
159 :type 'hook
160 :group 'next-error)
162 (defvar next-error-highlight-timer nil)
164 (defvar next-error-overlay-arrow-position nil)
165 (put 'next-error-overlay-arrow-position 'overlay-arrow-string "=>")
166 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
168 (defvar next-error-last-buffer nil
169 "The most recent `next-error' buffer.
170 A buffer becomes most recent when its compilation, grep, or
171 similar mode is started, or when it is used with \\[next-error]
172 or \\[compile-goto-error].")
174 (defvar next-error-function nil
175 "Function to use to find the next error in the current buffer.
176 The function is called with 2 parameters:
177 ARG is an integer specifying by how many errors to move.
178 RESET is a boolean which, if non-nil, says to go back to the beginning
179 of the errors before moving.
180 Major modes providing compile-like functionality should set this variable
181 to indicate to `next-error' that this is a candidate buffer and how
182 to navigate in it.")
184 (make-variable-buffer-local 'next-error-function)
186 (defsubst next-error-buffer-p (buffer
187 &optional avoid-current
188 extra-test-inclusive
189 extra-test-exclusive)
190 "Test if BUFFER is a `next-error' capable buffer.
192 If AVOID-CURRENT is non-nil, treat the current buffer
193 as an absolute last resort only.
195 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
196 that normally would not qualify. If it returns t, the buffer
197 in question is treated as usable.
199 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
200 that would normally be considered usable. If it returns nil,
201 that buffer is rejected."
202 (and (buffer-name buffer) ;First make sure it's live.
203 (not (and avoid-current (eq buffer (current-buffer))))
204 (with-current-buffer buffer
205 (if next-error-function ; This is the normal test.
206 ;; Optionally reject some buffers.
207 (if extra-test-exclusive
208 (funcall extra-test-exclusive)
210 ;; Optionally accept some other buffers.
211 (and extra-test-inclusive
212 (funcall extra-test-inclusive))))))
214 (defun next-error-find-buffer (&optional avoid-current
215 extra-test-inclusive
216 extra-test-exclusive)
217 "Return a `next-error' capable buffer.
219 If AVOID-CURRENT is non-nil, treat the current buffer
220 as an absolute last resort only.
222 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
223 that normally would not qualify. If it returns t, the buffer
224 in question is treated as usable.
226 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
227 that would normally be considered usable. If it returns nil,
228 that buffer is rejected."
230 ;; 1. If one window on the selected frame displays such buffer, return it.
231 (let ((window-buffers
232 (delete-dups
233 (delq nil (mapcar (lambda (w)
234 (if (next-error-buffer-p
235 (window-buffer w)
236 avoid-current
237 extra-test-inclusive extra-test-exclusive)
238 (window-buffer w)))
239 (window-list))))))
240 (if (eq (length window-buffers) 1)
241 (car window-buffers)))
242 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
243 (if (and next-error-last-buffer
244 (next-error-buffer-p next-error-last-buffer avoid-current
245 extra-test-inclusive extra-test-exclusive))
246 next-error-last-buffer)
247 ;; 3. If the current buffer is acceptable, choose it.
248 (if (next-error-buffer-p (current-buffer) avoid-current
249 extra-test-inclusive extra-test-exclusive)
250 (current-buffer))
251 ;; 4. Look for any acceptable buffer.
252 (let ((buffers (buffer-list)))
253 (while (and buffers
254 (not (next-error-buffer-p
255 (car buffers) avoid-current
256 extra-test-inclusive extra-test-exclusive)))
257 (setq buffers (cdr buffers)))
258 (car buffers))
259 ;; 5. Use the current buffer as a last resort if it qualifies,
260 ;; even despite AVOID-CURRENT.
261 (and avoid-current
262 (next-error-buffer-p (current-buffer) nil
263 extra-test-inclusive extra-test-exclusive)
264 (progn
265 (message "This is the only next-error capable buffer")
266 (current-buffer)))
267 ;; 6. Give up.
268 (error "No next-error capable buffer found")))
270 (defun next-error (&optional arg reset)
271 "Visit next `next-error' message and corresponding source code.
273 If all the error messages parsed so far have been processed already,
274 the message buffer is checked for new ones.
276 A prefix ARG specifies how many error messages to move;
277 negative means move back to previous error messages.
278 Just \\[universal-argument] as a prefix means reparse the error message buffer
279 and start at the first error.
281 The RESET argument specifies that we should restart from the beginning.
283 \\[next-error] normally uses the most recently started
284 compilation, grep, or occur buffer. It can also operate on any
285 buffer with output from the \\[compile], \\[grep] commands, or,
286 more generally, on any buffer in Compilation mode or with
287 Compilation Minor mode enabled, or any buffer in which
288 `next-error-function' is bound to an appropriate function.
289 To specify use of a particular buffer for error messages, type
290 \\[next-error] in that buffer when it is the only one displayed
291 in the current frame.
293 Once \\[next-error] has chosen the buffer for error messages, it
294 runs `next-error-hook' with `run-hooks', and stays with that buffer
295 until you use it in some other buffer which uses Compilation mode
296 or Compilation Minor mode.
298 See variables `compilation-parse-errors-function' and
299 \`compilation-error-regexp-alist' for customization ideas."
300 (interactive "P")
301 (if (consp arg) (setq reset t arg nil))
302 (when (setq next-error-last-buffer (next-error-find-buffer))
303 ;; we know here that next-error-function is a valid symbol we can funcall
304 (with-current-buffer next-error-last-buffer
305 (funcall next-error-function (prefix-numeric-value arg) reset)
306 (run-hooks 'next-error-hook))))
308 (defun next-error-internal ()
309 "Visit the source code corresponding to the `next-error' message at point."
310 (setq next-error-last-buffer (current-buffer))
311 ;; we know here that next-error-function is a valid symbol we can funcall
312 (with-current-buffer next-error-last-buffer
313 (funcall next-error-function 0 nil)
314 (run-hooks 'next-error-hook)))
316 (defalias 'goto-next-locus 'next-error)
317 (defalias 'next-match 'next-error)
319 (defun previous-error (&optional n)
320 "Visit previous `next-error' message and corresponding source code.
322 Prefix arg N says how many error messages to move backwards (or
323 forwards, if negative).
325 This operates on the output from the \\[compile] and \\[grep] commands."
326 (interactive "p")
327 (next-error (- (or n 1))))
329 (defun first-error (&optional n)
330 "Restart at the first error.
331 Visit corresponding source code.
332 With prefix arg N, visit the source code of the Nth error.
333 This operates on the output from the \\[compile] command, for instance."
334 (interactive "p")
335 (next-error n t))
337 (defun next-error-no-select (&optional n)
338 "Move point to the next error in the `next-error' buffer and highlight match.
339 Prefix arg N says how many error messages to move forwards (or
340 backwards, if negative).
341 Finds and highlights the source line like \\[next-error], but does not
342 select the source buffer."
343 (interactive "p")
344 (let ((next-error-highlight next-error-highlight-no-select))
345 (next-error n))
346 (pop-to-buffer next-error-last-buffer))
348 (defun previous-error-no-select (&optional n)
349 "Move point to the previous error in the `next-error' buffer and highlight match.
350 Prefix arg N says how many error messages to move backwards (or
351 forwards, if negative).
352 Finds and highlights the source line like \\[previous-error], but does not
353 select the source buffer."
354 (interactive "p")
355 (next-error-no-select (- (or n 1))))
357 ;;; Internal variable for `next-error-follow-mode-post-command-hook'.
358 (defvar next-error-follow-last-line nil)
360 (define-minor-mode next-error-follow-minor-mode
361 "Minor mode for compilation, occur and diff modes.
362 When turned on, cursor motion in the compilation, grep, occur or diff
363 buffer causes automatic display of the corresponding source code
364 location."
365 :group 'next-error :init-value nil :lighter " Fol"
366 (if (not next-error-follow-minor-mode)
367 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
368 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
369 (make-local-variable 'next-error-follow-last-line)))
371 ;;; Used as a `post-command-hook' by `next-error-follow-mode'
372 ;;; for the *Compilation* *grep* and *Occur* buffers.
373 (defun next-error-follow-mode-post-command-hook ()
374 (unless (equal next-error-follow-last-line (line-number-at-pos))
375 (setq next-error-follow-last-line (line-number-at-pos))
376 (condition-case nil
377 (let ((compilation-context-lines nil))
378 (setq compilation-current-error (point))
379 (next-error-no-select 0))
380 (error t))))
385 (defun fundamental-mode ()
386 "Major mode not specialized for anything in particular.
387 Other major modes are defined by comparison with this one."
388 (interactive)
389 (kill-all-local-variables)
390 (unless delay-mode-hooks
391 (run-hooks 'after-change-major-mode-hook)))
393 ;; Making and deleting lines.
395 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard)))
397 (defun newline (&optional arg)
398 "Insert a newline, and move to left margin of the new line if it's blank.
399 If `use-hard-newlines' is non-nil, the newline is marked with the
400 text-property `hard'.
401 With ARG, insert that many newlines.
402 Call `auto-fill-function' if the current column number is greater
403 than the value of `fill-column' and ARG is nil."
404 (interactive "*P")
405 (barf-if-buffer-read-only)
406 ;; Inserting a newline at the end of a line produces better redisplay in
407 ;; try_window_id than inserting at the beginning of a line, and the textual
408 ;; result is the same. So, if we're at beginning of line, pretend to be at
409 ;; the end of the previous line.
410 (let ((flag (and (not (bobp))
411 (bolp)
412 ;; Make sure no functions want to be told about
413 ;; the range of the changes.
414 (not after-change-functions)
415 (not before-change-functions)
416 ;; Make sure there are no markers here.
417 (not (buffer-has-markers-at (1- (point))))
418 (not (buffer-has-markers-at (point)))
419 ;; Make sure no text properties want to know
420 ;; where the change was.
421 (not (get-char-property (1- (point)) 'modification-hooks))
422 (not (get-char-property (1- (point)) 'insert-behind-hooks))
423 (or (eobp)
424 (not (get-char-property (point) 'insert-in-front-hooks)))
425 ;; Make sure the newline before point isn't intangible.
426 (not (get-char-property (1- (point)) 'intangible))
427 ;; Make sure the newline before point isn't read-only.
428 (not (get-char-property (1- (point)) 'read-only))
429 ;; Make sure the newline before point isn't invisible.
430 (not (get-char-property (1- (point)) 'invisible))
431 ;; Make sure the newline before point has the same
432 ;; properties as the char before it (if any).
433 (< (or (previous-property-change (point)) -2)
434 (- (point) 2))))
435 (was-page-start (and (bolp)
436 (looking-at page-delimiter)))
437 (beforepos (point)))
438 (if flag (backward-char 1))
439 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
440 ;; Set last-command-char to tell self-insert what to insert.
441 (let ((last-command-char ?\n)
442 ;; Don't auto-fill if we have a numeric argument.
443 ;; Also not if flag is true (it would fill wrong line);
444 ;; there is no need to since we're at BOL.
445 (auto-fill-function (if (or arg flag) nil auto-fill-function)))
446 (unwind-protect
447 (self-insert-command (prefix-numeric-value arg))
448 ;; If we get an error in self-insert-command, put point at right place.
449 (if flag (forward-char 1))))
450 ;; Even if we did *not* get an error, keep that forward-char;
451 ;; all further processing should apply to the newline that the user
452 ;; thinks he inserted.
454 ;; Mark the newline(s) `hard'.
455 (if use-hard-newlines
456 (set-hard-newline-properties
457 (- (point) (if arg (prefix-numeric-value arg) 1)) (point)))
458 ;; If the newline leaves the previous line blank,
459 ;; and we have a left margin, delete that from the blank line.
460 (or flag
461 (save-excursion
462 (goto-char beforepos)
463 (beginning-of-line)
464 (and (looking-at "[ \t]$")
465 (> (current-left-margin) 0)
466 (delete-region (point) (progn (end-of-line) (point))))))
467 ;; Indent the line after the newline, except in one case:
468 ;; when we added the newline at the beginning of a line
469 ;; which starts a page.
470 (or was-page-start
471 (move-to-left-margin nil t)))
472 nil)
474 (defun set-hard-newline-properties (from to)
475 (let ((sticky (get-text-property from 'rear-nonsticky)))
476 (put-text-property from to 'hard 't)
477 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
478 (if (and (listp sticky) (not (memq 'hard sticky)))
479 (put-text-property from (point) 'rear-nonsticky
480 (cons 'hard sticky)))))
482 (defun open-line (n)
483 "Insert a newline and leave point before it.
484 If there is a fill prefix and/or a `left-margin', insert them
485 on the new line if the line would have been blank.
486 With arg N, insert N newlines."
487 (interactive "*p")
488 (let* ((do-fill-prefix (and fill-prefix (bolp)))
489 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
490 (loc (point))
491 ;; Don't expand an abbrev before point.
492 (abbrev-mode nil))
493 (newline n)
494 (goto-char loc)
495 (while (> n 0)
496 (cond ((bolp)
497 (if do-left-margin (indent-to (current-left-margin)))
498 (if do-fill-prefix (insert-and-inherit fill-prefix))))
499 (forward-line 1)
500 (setq n (1- n)))
501 (goto-char loc)
502 (end-of-line)))
504 (defun split-line (&optional arg)
505 "Split current line, moving portion beyond point vertically down.
506 If the current line starts with `fill-prefix', insert it on the new
507 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
509 When called from Lisp code, ARG may be a prefix string to copy."
510 (interactive "*P")
511 (skip-chars-forward " \t")
512 (let* ((col (current-column))
513 (pos (point))
514 ;; What prefix should we check for (nil means don't).
515 (prefix (cond ((stringp arg) arg)
516 (arg nil)
517 (t fill-prefix)))
518 ;; Does this line start with it?
519 (have-prfx (and prefix
520 (save-excursion
521 (beginning-of-line)
522 (looking-at (regexp-quote prefix))))))
523 (newline 1)
524 (if have-prfx (insert-and-inherit prefix))
525 (indent-to col 0)
526 (goto-char pos)))
528 (defun delete-indentation (&optional arg)
529 "Join this line to previous and fix up whitespace at join.
530 If there is a fill prefix, delete it from the beginning of this line.
531 With argument, join this line to following line."
532 (interactive "*P")
533 (beginning-of-line)
534 (if arg (forward-line 1))
535 (if (eq (preceding-char) ?\n)
536 (progn
537 (delete-region (point) (1- (point)))
538 ;; If the second line started with the fill prefix,
539 ;; delete the prefix.
540 (if (and fill-prefix
541 (<= (+ (point) (length fill-prefix)) (point-max))
542 (string= fill-prefix
543 (buffer-substring (point)
544 (+ (point) (length fill-prefix)))))
545 (delete-region (point) (+ (point) (length fill-prefix))))
546 (fixup-whitespace))))
548 (defalias 'join-line #'delete-indentation) ; easier to find
550 (defun delete-blank-lines ()
551 "On blank line, delete all surrounding blank lines, leaving just one.
552 On isolated blank line, delete that one.
553 On nonblank line, delete any immediately following blank lines."
554 (interactive "*")
555 (let (thisblank singleblank)
556 (save-excursion
557 (beginning-of-line)
558 (setq thisblank (looking-at "[ \t]*$"))
559 ;; Set singleblank if there is just one blank line here.
560 (setq singleblank
561 (and thisblank
562 (not (looking-at "[ \t]*\n[ \t]*$"))
563 (or (bobp)
564 (progn (forward-line -1)
565 (not (looking-at "[ \t]*$")))))))
566 ;; Delete preceding blank lines, and this one too if it's the only one.
567 (if thisblank
568 (progn
569 (beginning-of-line)
570 (if singleblank (forward-line 1))
571 (delete-region (point)
572 (if (re-search-backward "[^ \t\n]" nil t)
573 (progn (forward-line 1) (point))
574 (point-min)))))
575 ;; Delete following blank lines, unless the current line is blank
576 ;; and there are no following blank lines.
577 (if (not (and thisblank singleblank))
578 (save-excursion
579 (end-of-line)
580 (forward-line 1)
581 (delete-region (point)
582 (if (re-search-forward "[^ \t\n]" nil t)
583 (progn (beginning-of-line) (point))
584 (point-max)))))
585 ;; Handle the special case where point is followed by newline and eob.
586 ;; Delete the line, leaving point at eob.
587 (if (looking-at "^[ \t]*\n\\'")
588 (delete-region (point) (point-max)))))
590 (defun delete-trailing-whitespace ()
591 "Delete all the trailing whitespace across the current buffer.
592 All whitespace after the last non-whitespace character in a line is deleted.
593 This respects narrowing, created by \\[narrow-to-region] and friends.
594 A formfeed is not considered whitespace by this function."
595 (interactive "*")
596 (save-match-data
597 (save-excursion
598 (goto-char (point-min))
599 (while (re-search-forward "\\s-$" nil t)
600 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
601 ;; Don't delete formfeeds, even if they are considered whitespace.
602 (save-match-data
603 (if (looking-at ".*\f")
604 (goto-char (match-end 0))))
605 (delete-region (point) (match-end 0))))))
607 (defun newline-and-indent ()
608 "Insert a newline, then indent according to major mode.
609 Indentation is done using the value of `indent-line-function'.
610 In programming language modes, this is the same as TAB.
611 In some text modes, where TAB inserts a tab, this command indents to the
612 column specified by the function `current-left-margin'."
613 (interactive "*")
614 (delete-horizontal-space t)
615 (newline)
616 (indent-according-to-mode))
618 (defun reindent-then-newline-and-indent ()
619 "Reindent current line, insert newline, then indent the new line.
620 Indentation of both lines is done according to the current major mode,
621 which means calling the current value of `indent-line-function'.
622 In programming language modes, this is the same as TAB.
623 In some text modes, where TAB inserts a tab, this indents to the
624 column specified by the function `current-left-margin'."
625 (interactive "*")
626 (let ((pos (point)))
627 ;; Be careful to insert the newline before indenting the line.
628 ;; Otherwise, the indentation might be wrong.
629 (newline)
630 (save-excursion
631 (goto-char pos)
632 (indent-according-to-mode)
633 (delete-horizontal-space t))
634 (indent-according-to-mode)))
636 (defun quoted-insert (arg)
637 "Read next input character and insert it.
638 This is useful for inserting control characters.
640 If the first character you type after this command is an octal digit,
641 you should type a sequence of octal digits which specify a character code.
642 Any nondigit terminates the sequence. If the terminator is a RET,
643 it is discarded; any other terminator is used itself as input.
644 The variable `read-quoted-char-radix' specifies the radix for this feature;
645 set it to 10 or 16 to use decimal or hex instead of octal.
647 In overwrite mode, this function inserts the character anyway, and
648 does not handle octal digits specially. This means that if you use
649 overwrite as your normal editing mode, you can use this function to
650 insert characters when necessary.
652 In binary overwrite mode, this function does overwrite, and octal
653 digits are interpreted as a character code. This is intended to be
654 useful for editing binary files."
655 (interactive "*p")
656 (let* ((char (let (translation-table-for-input input-method-function)
657 (if (or (not overwrite-mode)
658 (eq overwrite-mode 'overwrite-mode-binary))
659 (read-quoted-char)
660 (read-char)))))
661 ;; Assume character codes 0240 - 0377 stand for characters in some
662 ;; single-byte character set, and convert them to Emacs
663 ;; characters.
664 (if (and enable-multibyte-characters
665 (>= char ?\240)
666 (<= char ?\377))
667 (setq char (unibyte-char-to-multibyte char)))
668 (if (> arg 0)
669 (if (eq overwrite-mode 'overwrite-mode-binary)
670 (delete-char arg)))
671 (while (> arg 0)
672 (insert-and-inherit char)
673 (setq arg (1- arg)))))
675 (defun forward-to-indentation (&optional arg)
676 "Move forward ARG lines and position at first nonblank character."
677 (interactive "p")
678 (forward-line (or arg 1))
679 (skip-chars-forward " \t"))
681 (defun backward-to-indentation (&optional arg)
682 "Move backward ARG lines and position at first nonblank character."
683 (interactive "p")
684 (forward-line (- (or arg 1)))
685 (skip-chars-forward " \t"))
687 (defun back-to-indentation ()
688 "Move point to the first non-whitespace character on this line."
689 (interactive)
690 (beginning-of-line 1)
691 (skip-syntax-forward " " (line-end-position))
692 ;; Move back over chars that have whitespace syntax but have the p flag.
693 (backward-prefix-chars))
695 (defun fixup-whitespace ()
696 "Fixup white space between objects around point.
697 Leave one space or none, according to the context."
698 (interactive "*")
699 (save-excursion
700 (delete-horizontal-space)
701 (if (or (looking-at "^\\|\\s)")
702 (save-excursion (forward-char -1)
703 (looking-at "$\\|\\s(\\|\\s'")))
705 (insert ?\s))))
707 (defun delete-horizontal-space (&optional backward-only)
708 "Delete all spaces and tabs around point.
709 If BACKWARD-ONLY is non-nil, only delete spaces before point."
710 (interactive "*")
711 (let ((orig-pos (point)))
712 (delete-region
713 (if backward-only
714 orig-pos
715 (progn
716 (skip-chars-forward " \t")
717 (constrain-to-field nil orig-pos t)))
718 (progn
719 (skip-chars-backward " \t")
720 (constrain-to-field nil orig-pos)))))
722 (defun just-one-space (&optional n)
723 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
724 (interactive "*p")
725 (let ((orig-pos (point)))
726 (skip-chars-backward " \t")
727 (constrain-to-field nil orig-pos)
728 (dotimes (i (or n 1))
729 (if (= (following-char) ?\s)
730 (forward-char 1)
731 (insert ?\s)))
732 (delete-region
733 (point)
734 (progn
735 (skip-chars-forward " \t")
736 (constrain-to-field nil orig-pos t)))))
738 (defun beginning-of-buffer (&optional arg)
739 "Move point to the beginning of the buffer; leave mark at previous position.
740 With \\[universal-argument] prefix, do not set mark at previous position.
741 With numeric arg N, put point N/10 of the way from the beginning.
743 If the buffer is narrowed, this command uses the beginning and size
744 of the accessible part of the buffer.
746 Don't use this command in Lisp programs!
747 \(goto-char (point-min)) is faster and avoids clobbering the mark."
748 (interactive "P")
749 (or (consp arg)
750 (and transient-mark-mode mark-active)
751 (push-mark))
752 (let ((size (- (point-max) (point-min))))
753 (goto-char (if (and arg (not (consp arg)))
754 (+ (point-min)
755 (if (> size 10000)
756 ;; Avoid overflow for large buffer sizes!
757 (* (prefix-numeric-value arg)
758 (/ size 10))
759 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
760 (point-min))))
761 (if arg (forward-line 1)))
763 (defun end-of-buffer (&optional arg)
764 "Move point to the end of the buffer; leave mark at previous position.
765 With \\[universal-argument] prefix, do not set mark at previous position.
766 With numeric arg N, put point N/10 of the way from the end.
768 If the buffer is narrowed, this command uses the beginning and size
769 of the accessible part of the buffer.
771 Don't use this command in Lisp programs!
772 \(goto-char (point-max)) is faster and avoids clobbering the mark."
773 (interactive "P")
774 (or (consp arg)
775 (and transient-mark-mode mark-active)
776 (push-mark))
777 (let ((size (- (point-max) (point-min))))
778 (goto-char (if (and arg (not (consp arg)))
779 (- (point-max)
780 (if (> size 10000)
781 ;; Avoid overflow for large buffer sizes!
782 (* (prefix-numeric-value arg)
783 (/ size 10))
784 (/ (* size (prefix-numeric-value arg)) 10)))
785 (point-max))))
786 ;; If we went to a place in the middle of the buffer,
787 ;; adjust it to the beginning of a line.
788 (cond (arg (forward-line 1))
789 ((> (point) (window-end nil t))
790 ;; If the end of the buffer is not already on the screen,
791 ;; then scroll specially to put it near, but not at, the bottom.
792 (overlay-recenter (point))
793 (recenter -3))))
795 (defun mark-whole-buffer ()
796 "Put point at beginning and mark at end of buffer.
797 You probably should not use this function in Lisp programs;
798 it is usually a mistake for a Lisp function to use any subroutine
799 that uses or sets the mark."
800 (interactive)
801 (push-mark (point))
802 (push-mark (point-max) nil t)
803 (goto-char (point-min)))
806 ;; Counting lines, one way or another.
808 (defun goto-line (arg &optional buffer)
809 "Goto line ARG, counting from line 1 at beginning of buffer.
810 Normally, move point in the current buffer.
811 With just \\[universal-argument] as argument, move point in the most recently
812 displayed other buffer, and switch to it. When called from Lisp code,
813 the optional argument BUFFER specifies a buffer to switch to.
815 If there's a number in the buffer at point, it is the default for ARG."
816 (interactive
817 (if (and current-prefix-arg (not (consp current-prefix-arg)))
818 (list (prefix-numeric-value current-prefix-arg))
819 ;; Look for a default, a number in the buffer at point.
820 (let* ((default
821 (save-excursion
822 (skip-chars-backward "0-9")
823 (if (looking-at "[0-9]")
824 (buffer-substring-no-properties
825 (point)
826 (progn (skip-chars-forward "0-9")
827 (point))))))
828 ;; Decide if we're switching buffers.
829 (buffer
830 (if (consp current-prefix-arg)
831 (other-buffer (current-buffer) t)))
832 (buffer-prompt
833 (if buffer
834 (concat " in " (buffer-name buffer))
835 "")))
836 ;; Read the argument, offering that number (if any) as default.
837 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
838 "Goto line%s: ")
839 buffer-prompt
840 default)
841 nil nil t
842 'minibuffer-history
843 default)
844 buffer))))
845 ;; Switch to the desired buffer, one way or another.
846 (if buffer
847 (let ((window (get-buffer-window buffer)))
848 (if window (select-window window)
849 (switch-to-buffer-other-window buffer))))
850 ;; Move to the specified line number in that buffer.
851 (save-restriction
852 (widen)
853 (goto-char 1)
854 (if (eq selective-display t)
855 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
856 (forward-line (1- arg)))))
858 (defun count-lines-region (start end)
859 "Print number of lines and characters in the region."
860 (interactive "r")
861 (message "Region has %d lines, %d characters"
862 (count-lines start end) (- end start)))
864 (defun what-line ()
865 "Print the current buffer line number and narrowed line number of point."
866 (interactive)
867 (let ((start (point-min))
868 (n (line-number-at-pos)))
869 (if (= start 1)
870 (message "Line %d" n)
871 (save-excursion
872 (save-restriction
873 (widen)
874 (message "line %d (narrowed line %d)"
875 (+ n (line-number-at-pos start) -1) n))))))
877 (defun count-lines (start end)
878 "Return number of lines between START and END.
879 This is usually the number of newlines between them,
880 but can be one more if START is not equal to END
881 and the greater of them is not at the start of a line."
882 (save-excursion
883 (save-restriction
884 (narrow-to-region start end)
885 (goto-char (point-min))
886 (if (eq selective-display t)
887 (save-match-data
888 (let ((done 0))
889 (while (re-search-forward "[\n\C-m]" nil t 40)
890 (setq done (+ 40 done)))
891 (while (re-search-forward "[\n\C-m]" nil t 1)
892 (setq done (+ 1 done)))
893 (goto-char (point-max))
894 (if (and (/= start end)
895 (not (bolp)))
896 (1+ done)
897 done)))
898 (- (buffer-size) (forward-line (buffer-size)))))))
900 (defun line-number-at-pos (&optional pos)
901 "Return (narrowed) buffer line number at position POS.
902 If POS is nil, use current buffer location."
903 (let ((opoint (or pos (point))) start)
904 (save-excursion
905 (goto-char (point-min))
906 (setq start (point))
907 (goto-char opoint)
908 (forward-line 0)
909 (1+ (count-lines start (point))))))
911 (defun what-cursor-position (&optional detail)
912 "Print info on cursor position (on screen and within buffer).
913 Also describe the character after point, and give its character code
914 in octal, decimal and hex.
916 For a non-ASCII multibyte character, also give its encoding in the
917 buffer's selected coding system if the coding system encodes the
918 character safely. If the character is encoded into one byte, that
919 code is shown in hex. If the character is encoded into more than one
920 byte, just \"...\" is shown.
922 In addition, with prefix argument, show details about that character
923 in *Help* buffer. See also the command `describe-char'."
924 (interactive "P")
925 (let* ((char (following-char))
926 (beg (point-min))
927 (end (point-max))
928 (pos (point))
929 (total (buffer-size))
930 (percent (if (> total 50000)
931 ;; Avoid overflow from multiplying by 100!
932 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
933 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
934 (hscroll (if (= (window-hscroll) 0)
936 (format " Hscroll=%d" (window-hscroll))))
937 (col (current-column)))
938 (if (= pos end)
939 (if (or (/= beg 1) (/= end (1+ total)))
940 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
941 pos total percent beg end col hscroll)
942 (message "point=%d of %d (EOB) column=%d%s"
943 pos total col hscroll))
944 (let ((coding buffer-file-coding-system)
945 encoded encoding-msg display-prop under-display)
946 (if (or (not coding)
947 (eq (coding-system-type coding) t))
948 (setq coding default-buffer-file-coding-system))
949 (if (not (char-valid-p char))
950 (setq encoding-msg
951 (format "(%d, #o%o, #x%x, invalid)" char char char))
952 ;; Check if the character is displayed with some `display'
953 ;; text property. In that case, set under-display to the
954 ;; buffer substring covered by that property.
955 (setq display-prop (get-text-property pos 'display))
956 (if display-prop
957 (let ((to (or (next-single-property-change pos 'display)
958 (point-max))))
959 (if (< to (+ pos 4))
960 (setq under-display "")
961 (setq under-display "..."
962 to (+ pos 4)))
963 (setq under-display
964 (concat (buffer-substring-no-properties pos to)
965 under-display)))
966 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
967 (setq encoding-msg
968 (if display-prop
969 (if (not (stringp display-prop))
970 (format "(%d, #o%o, #x%x, part of display \"%s\")"
971 char char char under-display)
972 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
973 char char char under-display display-prop))
974 (if encoded
975 (format "(%d, #o%o, #x%x, file %s)"
976 char char char
977 (if (> (length encoded) 1)
978 "..."
979 (encoded-string-description encoded coding)))
980 (format "(%d, #o%o, #x%x)" char char char)))))
981 (if detail
982 ;; We show the detailed information about CHAR.
983 (describe-char (point)))
984 (if (or (/= beg 1) (/= end (1+ total)))
985 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
986 (if (< char 256)
987 (single-key-description char)
988 (buffer-substring-no-properties (point) (1+ (point))))
989 encoding-msg pos total percent beg end col hscroll)
990 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
991 (if enable-multibyte-characters
992 (if (< char 128)
993 (single-key-description char)
994 (buffer-substring-no-properties (point) (1+ (point))))
995 (single-key-description char))
996 encoding-msg pos total percent col hscroll))))))
998 (defvar read-expression-map
999 (let ((m (make-sparse-keymap)))
1000 (define-key m "\M-\t" 'lisp-complete-symbol)
1001 (set-keymap-parent m minibuffer-local-map)
1003 "Minibuffer keymap used for reading Lisp expressions.")
1005 (defvar read-expression-history nil)
1007 (defcustom eval-expression-print-level 4
1008 "Value for `print-level' while printing value in `eval-expression'.
1009 A value of nil means no limit."
1010 :group 'lisp
1011 :type '(choice (const :tag "No Limit" nil) integer)
1012 :version "21.1")
1014 (defcustom eval-expression-print-length 12
1015 "Value for `print-length' while printing value in `eval-expression'.
1016 A value of nil means no limit."
1017 :group 'lisp
1018 :type '(choice (const :tag "No Limit" nil) integer)
1019 :version "21.1")
1021 (defcustom eval-expression-debug-on-error t
1022 "If non-nil set `debug-on-error' to t in `eval-expression'.
1023 If nil, don't change the value of `debug-on-error'."
1024 :group 'lisp
1025 :type 'boolean
1026 :version "21.1")
1028 (defun eval-expression-print-format (value)
1029 "Format VALUE as a result of evaluated expression.
1030 Return a formatted string which is displayed in the echo area
1031 in addition to the value printed by prin1 in functions which
1032 display the result of expression evaluation."
1033 (if (and (integerp value)
1034 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1035 (eq this-command last-command)
1036 (if (boundp 'edebug-active) edebug-active)))
1037 (let ((char-string
1038 (if (or (if (boundp 'edebug-active) edebug-active)
1039 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1040 (prin1-char value))))
1041 (if char-string
1042 (format " (#o%o, #x%x, %s)" value value char-string)
1043 (format " (#o%o, #x%x)" value value)))))
1045 ;; We define this, rather than making `eval' interactive,
1046 ;; for the sake of completion of names like eval-region, eval-current-buffer.
1047 (defun eval-expression (eval-expression-arg
1048 &optional eval-expression-insert-value)
1049 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1050 Value is also consed on to front of the variable `values'.
1051 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
1052 insert the result into the current buffer instead of printing it in
1053 the echo area."
1054 (interactive
1055 (list (read-from-minibuffer "Eval: "
1056 nil read-expression-map t
1057 'read-expression-history)
1058 current-prefix-arg))
1060 (if (null eval-expression-debug-on-error)
1061 (setq values (cons (eval eval-expression-arg) values))
1062 (let ((old-value (make-symbol "t")) new-value)
1063 ;; Bind debug-on-error to something unique so that we can
1064 ;; detect when evaled code changes it.
1065 (let ((debug-on-error old-value))
1066 (setq values (cons (eval eval-expression-arg) values))
1067 (setq new-value debug-on-error))
1068 ;; If evaled code has changed the value of debug-on-error,
1069 ;; propagate that change to the global binding.
1070 (unless (eq old-value new-value)
1071 (setq debug-on-error new-value))))
1073 (let ((print-length eval-expression-print-length)
1074 (print-level eval-expression-print-level))
1075 (if eval-expression-insert-value
1076 (with-no-warnings
1077 (let ((standard-output (current-buffer)))
1078 (eval-last-sexp-print-value (car values))))
1079 (prog1
1080 (prin1 (car values) t)
1081 (let ((str (eval-expression-print-format (car values))))
1082 (if str (princ str t)))))))
1084 (defun edit-and-eval-command (prompt command)
1085 "Prompting with PROMPT, let user edit COMMAND and eval result.
1086 COMMAND is a Lisp expression. Let user edit that expression in
1087 the minibuffer, then read and evaluate the result."
1088 (let ((command
1089 (let ((print-level nil)
1090 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1091 (unwind-protect
1092 (read-from-minibuffer prompt
1093 (prin1-to-string command)
1094 read-expression-map t
1095 'command-history)
1096 ;; If command was added to command-history as a string,
1097 ;; get rid of that. We want only evaluable expressions there.
1098 (if (stringp (car command-history))
1099 (setq command-history (cdr command-history)))))))
1101 ;; If command to be redone does not match front of history,
1102 ;; add it to the history.
1103 (or (equal command (car command-history))
1104 (setq command-history (cons command command-history)))
1105 (eval command)))
1107 (defun repeat-complex-command (arg)
1108 "Edit and re-evaluate last complex command, or ARGth from last.
1109 A complex command is one which used the minibuffer.
1110 The command is placed in the minibuffer as a Lisp form for editing.
1111 The result is executed, repeating the command as changed.
1112 If the command has been changed or is not the most recent previous command
1113 it is added to the front of the command history.
1114 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1115 to get different commands to edit and resubmit."
1116 (interactive "p")
1117 (let ((elt (nth (1- arg) command-history))
1118 newcmd)
1119 (if elt
1120 (progn
1121 (setq newcmd
1122 (let ((print-level nil)
1123 (minibuffer-history-position arg)
1124 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1125 (unwind-protect
1126 (read-from-minibuffer
1127 "Redo: " (prin1-to-string elt) read-expression-map t
1128 (cons 'command-history arg))
1130 ;; If command was added to command-history as a
1131 ;; string, get rid of that. We want only
1132 ;; evaluable expressions there.
1133 (if (stringp (car command-history))
1134 (setq command-history (cdr command-history))))))
1136 ;; If command to be redone does not match front of history,
1137 ;; add it to the history.
1138 (or (equal newcmd (car command-history))
1139 (setq command-history (cons newcmd command-history)))
1140 (eval newcmd))
1141 (if command-history
1142 (error "Argument %d is beyond length of command history" arg)
1143 (error "There are no previous complex commands to repeat")))))
1145 (defvar minibuffer-history nil
1146 "Default minibuffer history list.
1147 This is used for all minibuffer input
1148 except when an alternate history list is specified.")
1149 (defvar minibuffer-history-sexp-flag nil
1150 "Control whether history list elements are expressions or strings.
1151 If the value of this variable equals current minibuffer depth,
1152 they are expressions; otherwise they are strings.
1153 \(That convention is designed to do the right thing for
1154 recursive uses of the minibuffer.)")
1155 (setq minibuffer-history-variable 'minibuffer-history)
1156 (setq minibuffer-history-position nil)
1157 (defvar minibuffer-history-search-history nil)
1159 (defvar minibuffer-text-before-history nil
1160 "Text that was in this minibuffer before any history commands.
1161 This is nil if there have not yet been any history commands
1162 in this use of the minibuffer.")
1164 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1166 (defun minibuffer-history-initialize ()
1167 (setq minibuffer-text-before-history nil))
1169 (defun minibuffer-avoid-prompt (new old)
1170 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1171 (constrain-to-field nil (point-max)))
1173 (defcustom minibuffer-history-case-insensitive-variables nil
1174 "*Minibuffer history variables for which matching should ignore case.
1175 If a history variable is a member of this list, then the
1176 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1177 commands ignore case when searching it, regardless of `case-fold-search'."
1178 :type '(repeat variable)
1179 :group 'minibuffer)
1181 (defun previous-matching-history-element (regexp n)
1182 "Find the previous history element that matches REGEXP.
1183 \(Previous history elements refer to earlier actions.)
1184 With prefix argument N, search for Nth previous match.
1185 If N is negative, find the next or Nth next match.
1186 Normally, history elements are matched case-insensitively if
1187 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1188 makes the search case-sensitive.
1189 See also `minibuffer-history-case-insensitive-variables'."
1190 (interactive
1191 (let* ((enable-recursive-minibuffers t)
1192 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1194 minibuffer-local-map
1196 'minibuffer-history-search-history
1197 (car minibuffer-history-search-history))))
1198 ;; Use the last regexp specified, by default, if input is empty.
1199 (list (if (string= regexp "")
1200 (if minibuffer-history-search-history
1201 (car minibuffer-history-search-history)
1202 (error "No previous history search regexp"))
1203 regexp)
1204 (prefix-numeric-value current-prefix-arg))))
1205 (unless (zerop n)
1206 (if (and (zerop minibuffer-history-position)
1207 (null minibuffer-text-before-history))
1208 (setq minibuffer-text-before-history
1209 (minibuffer-contents-no-properties)))
1210 (let ((history (symbol-value minibuffer-history-variable))
1211 (case-fold-search
1212 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1213 ;; On some systems, ignore case for file names.
1214 (if (memq minibuffer-history-variable
1215 minibuffer-history-case-insensitive-variables)
1217 ;; Respect the user's setting for case-fold-search:
1218 case-fold-search)
1219 nil))
1220 prevpos
1221 match-string
1222 match-offset
1223 (pos minibuffer-history-position))
1224 (while (/= n 0)
1225 (setq prevpos pos)
1226 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1227 (when (= pos prevpos)
1228 (error (if (= pos 1)
1229 "No later matching history item"
1230 "No earlier matching history item")))
1231 (setq match-string
1232 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1233 (let ((print-level nil))
1234 (prin1-to-string (nth (1- pos) history)))
1235 (nth (1- pos) history)))
1236 (setq match-offset
1237 (if (< n 0)
1238 (and (string-match regexp match-string)
1239 (match-end 0))
1240 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1241 (match-beginning 1))))
1242 (when match-offset
1243 (setq n (+ n (if (< n 0) 1 -1)))))
1244 (setq minibuffer-history-position pos)
1245 (goto-char (point-max))
1246 (delete-minibuffer-contents)
1247 (insert match-string)
1248 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1249 (if (memq (car (car command-history)) '(previous-matching-history-element
1250 next-matching-history-element))
1251 (setq command-history (cdr command-history))))
1253 (defun next-matching-history-element (regexp n)
1254 "Find the next history element that matches REGEXP.
1255 \(The next history element refers to a more recent action.)
1256 With prefix argument N, search for Nth next match.
1257 If N is negative, find the previous or Nth previous match.
1258 Normally, history elements are matched case-insensitively if
1259 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1260 makes the search case-sensitive."
1261 (interactive
1262 (let* ((enable-recursive-minibuffers t)
1263 (regexp (read-from-minibuffer "Next element matching (regexp): "
1265 minibuffer-local-map
1267 'minibuffer-history-search-history
1268 (car minibuffer-history-search-history))))
1269 ;; Use the last regexp specified, by default, if input is empty.
1270 (list (if (string= regexp "")
1271 (if minibuffer-history-search-history
1272 (car minibuffer-history-search-history)
1273 (error "No previous history search regexp"))
1274 regexp)
1275 (prefix-numeric-value current-prefix-arg))))
1276 (previous-matching-history-element regexp (- n)))
1278 (defvar minibuffer-temporary-goal-position nil)
1280 (defun next-history-element (n)
1281 "Insert the next element of the minibuffer history into the minibuffer."
1282 (interactive "p")
1283 (or (zerop n)
1284 (let ((narg (- minibuffer-history-position n))
1285 (minimum (if minibuffer-default -1 0))
1286 elt minibuffer-returned-to-present)
1287 (if (and (zerop minibuffer-history-position)
1288 (null minibuffer-text-before-history))
1289 (setq minibuffer-text-before-history
1290 (minibuffer-contents-no-properties)))
1291 (if (< narg minimum)
1292 (if minibuffer-default
1293 (error "End of history; no next item")
1294 (error "End of history; no default available")))
1295 (if (> narg (length (symbol-value minibuffer-history-variable)))
1296 (error "Beginning of history; no preceding item"))
1297 (unless (memq last-command '(next-history-element
1298 previous-history-element))
1299 (let ((prompt-end (minibuffer-prompt-end)))
1300 (set (make-local-variable 'minibuffer-temporary-goal-position)
1301 (cond ((<= (point) prompt-end) prompt-end)
1302 ((eobp) nil)
1303 (t (point))))))
1304 (goto-char (point-max))
1305 (delete-minibuffer-contents)
1306 (setq minibuffer-history-position narg)
1307 (cond ((= narg -1)
1308 (setq elt minibuffer-default))
1309 ((= narg 0)
1310 (setq elt (or minibuffer-text-before-history ""))
1311 (setq minibuffer-returned-to-present t)
1312 (setq minibuffer-text-before-history nil))
1313 (t (setq elt (nth (1- minibuffer-history-position)
1314 (symbol-value minibuffer-history-variable)))))
1315 (insert
1316 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1317 (not minibuffer-returned-to-present))
1318 (let ((print-level nil))
1319 (prin1-to-string elt))
1320 elt))
1321 (goto-char (or minibuffer-temporary-goal-position (point-max))))))
1323 (defun previous-history-element (n)
1324 "Inserts the previous element of the minibuffer history into the minibuffer."
1325 (interactive "p")
1326 (next-history-element (- n)))
1328 (defun next-complete-history-element (n)
1329 "Get next history element which completes the minibuffer before the point.
1330 The contents of the minibuffer after the point are deleted, and replaced
1331 by the new completion."
1332 (interactive "p")
1333 (let ((point-at-start (point)))
1334 (next-matching-history-element
1335 (concat
1336 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1338 ;; next-matching-history-element always puts us at (point-min).
1339 ;; Move to the position we were at before changing the buffer contents.
1340 ;; This is still sensical, because the text before point has not changed.
1341 (goto-char point-at-start)))
1343 (defun previous-complete-history-element (n)
1345 Get previous history element which completes the minibuffer before the point.
1346 The contents of the minibuffer after the point are deleted, and replaced
1347 by the new completion."
1348 (interactive "p")
1349 (next-complete-history-element (- n)))
1351 ;; For compatibility with the old subr of the same name.
1352 (defun minibuffer-prompt-width ()
1353 "Return the display width of the minibuffer prompt.
1354 Return 0 if current buffer is not a minibuffer."
1355 ;; Return the width of everything before the field at the end of
1356 ;; the buffer; this should be 0 for normal buffers.
1357 (1- (minibuffer-prompt-end)))
1359 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1360 (defalias 'advertised-undo 'undo)
1362 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1363 "Table mapping redo records to the corresponding undo one.
1364 A redo record for undo-in-region maps to t.
1365 A redo record for ordinary undo maps to the following (earlier) undo.")
1367 (defvar undo-in-region nil
1368 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1370 (defvar undo-no-redo nil
1371 "If t, `undo' doesn't go through redo entries.")
1373 (defvar pending-undo-list nil
1374 "Within a run of consecutive undo commands, list remaining to be undone.
1375 If t, we undid all the way to the end of it.")
1377 (defun undo (&optional arg)
1378 "Undo some previous changes.
1379 Repeat this command to undo more changes.
1380 A numeric argument serves as a repeat count.
1382 In Transient Mark mode when the mark is active, only undo changes within
1383 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1384 as an argument limits undo to changes within the current region."
1385 (interactive "*P")
1386 ;; Make last-command indicate for the next command that this was an undo.
1387 ;; That way, another undo will undo more.
1388 ;; If we get to the end of the undo history and get an error,
1389 ;; another undo command will find the undo history empty
1390 ;; and will get another error. To begin undoing the undos,
1391 ;; you must type some other command.
1392 (let ((modified (buffer-modified-p))
1393 (recent-save (recent-auto-save-p))
1394 message)
1395 ;; If we get an error in undo-start,
1396 ;; the next command should not be a "consecutive undo".
1397 ;; So set `this-command' to something other than `undo'.
1398 (setq this-command 'undo-start)
1400 (unless (and (eq last-command 'undo)
1401 (or (eq pending-undo-list t)
1402 ;; If something (a timer or filter?) changed the buffer
1403 ;; since the previous command, don't continue the undo seq.
1404 (let ((list buffer-undo-list))
1405 (while (eq (car list) nil)
1406 (setq list (cdr list)))
1407 ;; If the last undo record made was made by undo
1408 ;; it shows nothing else happened in between.
1409 (gethash list undo-equiv-table))))
1410 (setq undo-in-region
1411 (if transient-mark-mode mark-active (and arg (not (numberp arg)))))
1412 (if undo-in-region
1413 (undo-start (region-beginning) (region-end))
1414 (undo-start))
1415 ;; get rid of initial undo boundary
1416 (undo-more 1))
1417 ;; If we got this far, the next command should be a consecutive undo.
1418 (setq this-command 'undo)
1419 ;; Check to see whether we're hitting a redo record, and if
1420 ;; so, ask the user whether she wants to skip the redo/undo pair.
1421 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1422 (or (eq (selected-window) (minibuffer-window))
1423 (setq message (if undo-in-region
1424 (if equiv "Redo in region!" "Undo in region!")
1425 (if equiv "Redo!" "Undo!"))))
1426 (when (and (consp equiv) undo-no-redo)
1427 ;; The equiv entry might point to another redo record if we have done
1428 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1429 (while (let ((next (gethash equiv undo-equiv-table)))
1430 (if next (setq equiv next))))
1431 (setq pending-undo-list equiv)))
1432 (undo-more
1433 (if (or transient-mark-mode (numberp arg))
1434 (prefix-numeric-value arg)
1436 ;; Record the fact that the just-generated undo records come from an
1437 ;; undo operation--that is, they are redo records.
1438 ;; In the ordinary case (not within a region), map the redo
1439 ;; record to the following undos.
1440 ;; I don't know how to do that in the undo-in-region case.
1441 (puthash buffer-undo-list
1442 (if undo-in-region t pending-undo-list)
1443 undo-equiv-table)
1444 ;; Don't specify a position in the undo record for the undo command.
1445 ;; Instead, undoing this should move point to where the change is.
1446 (let ((tail buffer-undo-list)
1447 (prev nil))
1448 (while (car tail)
1449 (when (integerp (car tail))
1450 (let ((pos (car tail)))
1451 (if prev
1452 (setcdr prev (cdr tail))
1453 (setq buffer-undo-list (cdr tail)))
1454 (setq tail (cdr tail))
1455 (while (car tail)
1456 (if (eq pos (car tail))
1457 (if prev
1458 (setcdr prev (cdr tail))
1459 (setq buffer-undo-list (cdr tail)))
1460 (setq prev tail))
1461 (setq tail (cdr tail)))
1462 (setq tail nil)))
1463 (setq prev tail tail (cdr tail))))
1464 ;; Record what the current undo list says,
1465 ;; so the next command can tell if the buffer was modified in between.
1466 (and modified (not (buffer-modified-p))
1467 (delete-auto-save-file-if-necessary recent-save))
1468 ;; Display a message announcing success.
1469 (if message
1470 (message message))))
1472 (defun buffer-disable-undo (&optional buffer)
1473 "Make BUFFER stop keeping undo information.
1474 No argument or nil as argument means do this for the current buffer."
1475 (interactive)
1476 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
1477 (setq buffer-undo-list t)))
1479 (defun undo-only (&optional arg)
1480 "Undo some previous changes.
1481 Repeat this command to undo more changes.
1482 A numeric argument serves as a repeat count.
1483 Contrary to `undo', this will not redo a previous undo."
1484 (interactive "*p")
1485 (let ((undo-no-redo t)) (undo arg)))
1487 (defvar undo-in-progress nil
1488 "Non-nil while performing an undo.
1489 Some change-hooks test this variable to do something different.")
1491 (defun undo-more (n)
1492 "Undo back N undo-boundaries beyond what was already undone recently.
1493 Call `undo-start' to get ready to undo recent changes,
1494 then call `undo-more' one or more times to undo them."
1495 (or (listp pending-undo-list)
1496 (error (concat "No further undo information"
1497 (and transient-mark-mode mark-active
1498 " for region"))))
1499 (let ((undo-in-progress t))
1500 (setq pending-undo-list (primitive-undo n pending-undo-list))
1501 (if (null pending-undo-list)
1502 (setq pending-undo-list t))))
1504 ;; Deep copy of a list
1505 (defun undo-copy-list (list)
1506 "Make a copy of undo list LIST."
1507 (mapcar 'undo-copy-list-1 list))
1509 (defun undo-copy-list-1 (elt)
1510 (if (consp elt)
1511 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1512 elt))
1514 (defun undo-start (&optional beg end)
1515 "Set `pending-undo-list' to the front of the undo list.
1516 The next call to `undo-more' will undo the most recently made change.
1517 If BEG and END are specified, then only undo elements
1518 that apply to text between BEG and END are used; other undo elements
1519 are ignored. If BEG and END are nil, all undo elements are used."
1520 (if (eq buffer-undo-list t)
1521 (error "No undo information in this buffer"))
1522 (setq pending-undo-list
1523 (if (and beg end (not (= beg end)))
1524 (undo-make-selective-list (min beg end) (max beg end))
1525 buffer-undo-list)))
1527 (defvar undo-adjusted-markers)
1529 (defun undo-make-selective-list (start end)
1530 "Return a list of undo elements for the region START to END.
1531 The elements come from `buffer-undo-list', but we keep only
1532 the elements inside this region, and discard those outside this region.
1533 If we find an element that crosses an edge of this region,
1534 we stop and ignore all further elements."
1535 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1536 (undo-list (list nil))
1537 undo-adjusted-markers
1538 some-rejected
1539 undo-elt undo-elt temp-undo-list delta)
1540 (while undo-list-copy
1541 (setq undo-elt (car undo-list-copy))
1542 (let ((keep-this
1543 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1544 ;; This is a "was unmodified" element.
1545 ;; Keep it if we have kept everything thus far.
1546 (not some-rejected))
1548 (undo-elt-in-region undo-elt start end)))))
1549 (if keep-this
1550 (progn
1551 (setq end (+ end (cdr (undo-delta undo-elt))))
1552 ;; Don't put two nils together in the list
1553 (if (not (and (eq (car undo-list) nil)
1554 (eq undo-elt nil)))
1555 (setq undo-list (cons undo-elt undo-list))))
1556 (if (undo-elt-crosses-region undo-elt start end)
1557 (setq undo-list-copy nil)
1558 (setq some-rejected t)
1559 (setq temp-undo-list (cdr undo-list-copy))
1560 (setq delta (undo-delta undo-elt))
1562 (when (/= (cdr delta) 0)
1563 (let ((position (car delta))
1564 (offset (cdr delta)))
1566 ;; Loop down the earlier events adjusting their buffer
1567 ;; positions to reflect the fact that a change to the buffer
1568 ;; isn't being undone. We only need to process those element
1569 ;; types which undo-elt-in-region will return as being in
1570 ;; the region since only those types can ever get into the
1571 ;; output
1573 (while temp-undo-list
1574 (setq undo-elt (car temp-undo-list))
1575 (cond ((integerp undo-elt)
1576 (if (>= undo-elt position)
1577 (setcar temp-undo-list (- undo-elt offset))))
1578 ((atom undo-elt) nil)
1579 ((stringp (car undo-elt))
1580 ;; (TEXT . POSITION)
1581 (let ((text-pos (abs (cdr undo-elt)))
1582 (point-at-end (< (cdr undo-elt) 0 )))
1583 (if (>= text-pos position)
1584 (setcdr undo-elt (* (if point-at-end -1 1)
1585 (- text-pos offset))))))
1586 ((integerp (car undo-elt))
1587 ;; (BEGIN . END)
1588 (when (>= (car undo-elt) position)
1589 (setcar undo-elt (- (car undo-elt) offset))
1590 (setcdr undo-elt (- (cdr undo-elt) offset))))
1591 ((null (car undo-elt))
1592 ;; (nil PROPERTY VALUE BEG . END)
1593 (let ((tail (nthcdr 3 undo-elt)))
1594 (when (>= (car tail) position)
1595 (setcar tail (- (car tail) offset))
1596 (setcdr tail (- (cdr tail) offset))))))
1597 (setq temp-undo-list (cdr temp-undo-list))))))))
1598 (setq undo-list-copy (cdr undo-list-copy)))
1599 (nreverse undo-list)))
1601 (defun undo-elt-in-region (undo-elt start end)
1602 "Determine whether UNDO-ELT falls inside the region START ... END.
1603 If it crosses the edge, we return nil."
1604 (cond ((integerp undo-elt)
1605 (and (>= undo-elt start)
1606 (<= undo-elt end)))
1607 ((eq undo-elt nil)
1609 ((atom undo-elt)
1610 nil)
1611 ((stringp (car undo-elt))
1612 ;; (TEXT . POSITION)
1613 (and (>= (abs (cdr undo-elt)) start)
1614 (< (abs (cdr undo-elt)) end)))
1615 ((and (consp undo-elt) (markerp (car undo-elt)))
1616 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1617 ;; See if MARKER is inside the region.
1618 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1619 (unless alist-elt
1620 (setq alist-elt (cons (car undo-elt)
1621 (marker-position (car undo-elt))))
1622 (setq undo-adjusted-markers
1623 (cons alist-elt undo-adjusted-markers)))
1624 (and (cdr alist-elt)
1625 (>= (cdr alist-elt) start)
1626 (<= (cdr alist-elt) end))))
1627 ((null (car undo-elt))
1628 ;; (nil PROPERTY VALUE BEG . END)
1629 (let ((tail (nthcdr 3 undo-elt)))
1630 (and (>= (car tail) start)
1631 (<= (cdr tail) end))))
1632 ((integerp (car undo-elt))
1633 ;; (BEGIN . END)
1634 (and (>= (car undo-elt) start)
1635 (<= (cdr undo-elt) end)))))
1637 (defun undo-elt-crosses-region (undo-elt start end)
1638 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1639 This assumes we have already decided that UNDO-ELT
1640 is not *inside* the region START...END."
1641 (cond ((atom undo-elt) nil)
1642 ((null (car undo-elt))
1643 ;; (nil PROPERTY VALUE BEG . END)
1644 (let ((tail (nthcdr 3 undo-elt)))
1645 (not (or (< (car tail) end)
1646 (> (cdr tail) start)))))
1647 ((integerp (car undo-elt))
1648 ;; (BEGIN . END)
1649 (not (or (< (car undo-elt) end)
1650 (> (cdr undo-elt) start))))))
1652 ;; Return the first affected buffer position and the delta for an undo element
1653 ;; delta is defined as the change in subsequent buffer positions if we *did*
1654 ;; the undo.
1655 (defun undo-delta (undo-elt)
1656 (if (consp undo-elt)
1657 (cond ((stringp (car undo-elt))
1658 ;; (TEXT . POSITION)
1659 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1660 ((integerp (car undo-elt))
1661 ;; (BEGIN . END)
1662 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1664 '(0 . 0)))
1665 '(0 . 0)))
1667 (defcustom undo-ask-before-discard t
1668 "If non-nil ask about discarding undo info for the current command.
1669 Normally, Emacs discards the undo info for the current command if
1670 it exceeds `undo-outer-limit'. But if you set this option
1671 non-nil, it asks in the echo area whether to discard the info.
1672 If you answer no, there a slight risk that Emacs might crash, so
1673 only do it if you really want to undo the command.
1675 This option is mainly intended for debugging. You have to be
1676 careful if you use it for other purposes. Garbage collection is
1677 inhibited while the question is asked, meaning that Emacs might
1678 leak memory. So you should make sure that you do not wait
1679 excessively long before answering the question."
1680 :type 'boolean
1681 :group 'undo
1682 :version "22.1")
1684 (defvar undo-extra-outer-limit nil
1685 "If non-nil, an extra level of size that's ok in an undo item.
1686 We don't ask the user about truncating the undo list until the
1687 current item gets bigger than this amount.
1689 This variable only matters if `undo-ask-before-discard' is non-nil.")
1690 (make-variable-buffer-local 'undo-extra-outer-limit)
1692 ;; When the first undo batch in an undo list is longer than
1693 ;; undo-outer-limit, this function gets called to warn the user that
1694 ;; the undo info for the current command was discarded. Garbage
1695 ;; collection is inhibited around the call, so it had better not do a
1696 ;; lot of consing.
1697 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
1698 (defun undo-outer-limit-truncate (size)
1699 (if undo-ask-before-discard
1700 (when (or (null undo-extra-outer-limit)
1701 (> size undo-extra-outer-limit))
1702 ;; Don't ask the question again unless it gets even bigger.
1703 ;; This applies, in particular, if the user quits from the question.
1704 ;; Such a quit quits out of GC, but something else will call GC
1705 ;; again momentarily. It will call this function again,
1706 ;; but we don't want to ask the question again.
1707 (setq undo-extra-outer-limit (+ size 50000))
1708 (if (let (use-dialog-box track-mouse executing-kbd-macro )
1709 (yes-or-no-p (format "Buffer %s undo info is %d bytes long; discard it? "
1710 (buffer-name) size)))
1711 (progn (setq buffer-undo-list nil)
1712 (setq undo-extra-outer-limit nil)
1714 nil))
1715 (display-warning '(undo discard-info)
1716 (concat
1717 (format "Buffer %s undo info was %d bytes long.\n"
1718 (buffer-name) size)
1719 "The undo info was discarded because it exceeded \
1720 `undo-outer-limit'.
1722 This is normal if you executed a command that made a huge change
1723 to the buffer. In that case, to prevent similar problems in the
1724 future, set `undo-outer-limit' to a value that is large enough to
1725 cover the maximum size of normal changes you expect a single
1726 command to make, but not so large that it might exceed the
1727 maximum memory allotted to Emacs.
1729 If you did not execute any such command, the situation is
1730 probably due to a bug and you should report it.
1732 You can disable the popping up of this buffer by adding the entry
1733 \(undo discard-info) to the user option `warning-suppress-types'.\n")
1734 :warning)
1735 (setq buffer-undo-list nil)
1738 (defvar shell-command-history nil
1739 "History list for some commands that read shell commands.")
1741 (defvar shell-command-switch "-c"
1742 "Switch used to have the shell execute its command line argument.")
1744 (defvar shell-command-default-error-buffer nil
1745 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1746 This buffer is used when `shell-command' or `shell-command-on-region'
1747 is run interactively. A value of nil means that output to stderr and
1748 stdout will be intermixed in the output stream.")
1750 (defun shell-command (command &optional output-buffer error-buffer)
1751 "Execute string COMMAND in inferior shell; display output, if any.
1752 With prefix argument, insert the COMMAND's output at point.
1754 If COMMAND ends in ampersand, execute it asynchronously.
1755 The output appears in the buffer `*Async Shell Command*'.
1756 That buffer is in shell mode.
1758 Otherwise, COMMAND is executed synchronously. The output appears in
1759 the buffer `*Shell Command Output*'. If the output is short enough to
1760 display in the echo area (which is determined by the variables
1761 `resize-mini-windows' and `max-mini-window-height'), it is shown
1762 there, but it is nonetheless available in buffer `*Shell Command
1763 Output*' even though that buffer is not automatically displayed.
1765 To specify a coding system for converting non-ASCII characters
1766 in the shell command output, use \\[universal-coding-system-argument]
1767 before this command.
1769 Noninteractive callers can specify coding systems by binding
1770 `coding-system-for-read' and `coding-system-for-write'.
1772 The optional second argument OUTPUT-BUFFER, if non-nil,
1773 says to put the output in some other buffer.
1774 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1775 If OUTPUT-BUFFER is not a buffer and not nil,
1776 insert output in current buffer. (This cannot be done asynchronously.)
1777 In either case, the output is inserted after point (leaving mark after it).
1779 If the command terminates without error, but generates output,
1780 and you did not specify \"insert it in the current buffer\",
1781 the output can be displayed in the echo area or in its buffer.
1782 If the output is short enough to display in the echo area
1783 \(determined by the variable `max-mini-window-height' if
1784 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
1785 the buffer containing the output is displayed.
1787 If there is output and an error, and you did not specify \"insert it
1788 in the current buffer\", a message about the error goes at the end
1789 of the output.
1791 If there is no output, or if output is inserted in the current buffer,
1792 then `*Shell Command Output*' is deleted.
1794 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1795 or buffer name to which to direct the command's standard error output.
1796 If it is nil, error output is mingled with regular output.
1797 In an interactive call, the variable `shell-command-default-error-buffer'
1798 specifies the value of ERROR-BUFFER."
1800 (interactive (list (read-from-minibuffer "Shell command: "
1801 nil nil nil 'shell-command-history)
1802 current-prefix-arg
1803 shell-command-default-error-buffer))
1804 ;; Look for a handler in case default-directory is a remote file name.
1805 (let ((handler
1806 (find-file-name-handler (directory-file-name default-directory)
1807 'shell-command)))
1808 (if handler
1809 (funcall handler 'shell-command command output-buffer error-buffer)
1810 (if (and output-buffer
1811 (not (or (bufferp output-buffer) (stringp output-buffer))))
1812 ;; Output goes in current buffer.
1813 (let ((error-file
1814 (if error-buffer
1815 (make-temp-file
1816 (expand-file-name "scor"
1817 (or small-temporary-file-directory
1818 temporary-file-directory)))
1819 nil)))
1820 (barf-if-buffer-read-only)
1821 (push-mark nil t)
1822 ;; We do not use -f for csh; we will not support broken use of
1823 ;; .cshrcs. Even the BSD csh manual says to use
1824 ;; "if ($?prompt) exit" before things which are not useful
1825 ;; non-interactively. Besides, if someone wants their other
1826 ;; aliases for shell commands then they can still have them.
1827 (call-process shell-file-name nil
1828 (if error-file
1829 (list t error-file)
1831 nil shell-command-switch command)
1832 (when (and error-file (file-exists-p error-file))
1833 (if (< 0 (nth 7 (file-attributes error-file)))
1834 (with-current-buffer (get-buffer-create error-buffer)
1835 (let ((pos-from-end (- (point-max) (point))))
1836 (or (bobp)
1837 (insert "\f\n"))
1838 ;; Do no formatting while reading error file,
1839 ;; because that can run a shell command, and we
1840 ;; don't want that to cause an infinite recursion.
1841 (format-insert-file error-file nil)
1842 ;; Put point after the inserted errors.
1843 (goto-char (- (point-max) pos-from-end)))
1844 (display-buffer (current-buffer))))
1845 (delete-file error-file))
1846 ;; This is like exchange-point-and-mark, but doesn't
1847 ;; activate the mark. It is cleaner to avoid activation,
1848 ;; even though the command loop would deactivate the mark
1849 ;; because we inserted text.
1850 (goto-char (prog1 (mark t)
1851 (set-marker (mark-marker) (point)
1852 (current-buffer)))))
1853 ;; Output goes in a separate buffer.
1854 ;; Preserve the match data in case called from a program.
1855 (save-match-data
1856 (if (string-match "[ \t]*&[ \t]*\\'" command)
1857 ;; Command ending with ampersand means asynchronous.
1858 (let ((buffer (get-buffer-create
1859 (or output-buffer "*Async Shell Command*")))
1860 (directory default-directory)
1861 proc)
1862 ;; Remove the ampersand.
1863 (setq command (substring command 0 (match-beginning 0)))
1864 ;; If will kill a process, query first.
1865 (setq proc (get-buffer-process buffer))
1866 (if proc
1867 (if (yes-or-no-p "A command is running. Kill it? ")
1868 (kill-process proc)
1869 (error "Shell command in progress")))
1870 (with-current-buffer buffer
1871 (setq buffer-read-only nil)
1872 (erase-buffer)
1873 (display-buffer buffer)
1874 (setq default-directory directory)
1875 (setq proc (start-process "Shell" buffer shell-file-name
1876 shell-command-switch command))
1877 (setq mode-line-process '(":%s"))
1878 (require 'shell) (shell-mode)
1879 (set-process-sentinel proc 'shell-command-sentinel)
1881 (shell-command-on-region (point) (point) command
1882 output-buffer nil error-buffer)))))))
1884 (defun display-message-or-buffer (message
1885 &optional buffer-name not-this-window frame)
1886 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1887 MESSAGE may be either a string or a buffer.
1889 A buffer is displayed using `display-buffer' if MESSAGE is too long for
1890 the maximum height of the echo area, as defined by `max-mini-window-height'
1891 if `resize-mini-windows' is non-nil.
1893 Returns either the string shown in the echo area, or when a pop-up
1894 buffer is used, the window used to display it.
1896 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1897 name of the buffer used to display it in the case where a pop-up buffer
1898 is used, defaulting to `*Message*'. In the case where MESSAGE is a
1899 string and it is displayed in the echo area, it is not specified whether
1900 the contents are inserted into the buffer anyway.
1902 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1903 and only used if a buffer is displayed."
1904 (cond ((and (stringp message)
1905 (not (string-match "\n" message))
1906 (<= (length message) (frame-width)))
1907 ;; Trivial case where we can use the echo area
1908 (message "%s" message))
1909 ((and (stringp message)
1910 (= (string-match "\n" message) (1- (length message)))
1911 (<= (1- (length message)) (frame-width)))
1912 ;; Trivial case where we can just remove single trailing newline
1913 (message "%s" (substring message 0 (1- (length message)))))
1915 ;; General case
1916 (with-current-buffer
1917 (if (bufferp message)
1918 message
1919 (get-buffer-create (or buffer-name "*Message*")))
1921 (unless (bufferp message)
1922 (erase-buffer)
1923 (insert message))
1925 (let ((lines
1926 (if (= (buffer-size) 0)
1928 (count-screen-lines nil nil nil (minibuffer-window)))))
1929 (cond ((= lines 0))
1930 ((and (or (<= lines 1)
1931 (<= lines
1932 (if resize-mini-windows
1933 (cond ((floatp max-mini-window-height)
1934 (* (frame-height)
1935 max-mini-window-height))
1936 ((integerp max-mini-window-height)
1937 max-mini-window-height)
1940 1)))
1941 ;; Don't use the echo area if the output buffer is
1942 ;; already dispayed in the selected frame.
1943 (not (get-buffer-window (current-buffer))))
1944 ;; Echo area
1945 (goto-char (point-max))
1946 (when (bolp)
1947 (backward-char 1))
1948 (message "%s" (buffer-substring (point-min) (point))))
1950 ;; Buffer
1951 (goto-char (point-min))
1952 (display-buffer (current-buffer)
1953 not-this-window frame))))))))
1956 ;; We have a sentinel to prevent insertion of a termination message
1957 ;; in the buffer itself.
1958 (defun shell-command-sentinel (process signal)
1959 (if (memq (process-status process) '(exit signal))
1960 (message "%s: %s."
1961 (car (cdr (cdr (process-command process))))
1962 (substring signal 0 -1))))
1964 (defun shell-command-on-region (start end command
1965 &optional output-buffer replace
1966 error-buffer display-error-buffer)
1967 "Execute string COMMAND in inferior shell with region as input.
1968 Normally display output (if any) in temp buffer `*Shell Command Output*';
1969 Prefix arg means replace the region with it. Return the exit code of
1970 COMMAND.
1972 To specify a coding system for converting non-ASCII characters
1973 in the input and output to the shell command, use \\[universal-coding-system-argument]
1974 before this command. By default, the input (from the current buffer)
1975 is encoded in the same coding system that will be used to save the file,
1976 `buffer-file-coding-system'. If the output is going to replace the region,
1977 then it is decoded from that same coding system.
1979 The noninteractive arguments are START, END, COMMAND,
1980 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
1981 Noninteractive callers can specify coding systems by binding
1982 `coding-system-for-read' and `coding-system-for-write'.
1984 If the command generates output, the output may be displayed
1985 in the echo area or in a buffer.
1986 If the output is short enough to display in the echo area
1987 \(determined by the variable `max-mini-window-height' if
1988 `resize-mini-windows' is non-nil), it is shown there. Otherwise
1989 it is displayed in the buffer `*Shell Command Output*'. The output
1990 is available in that buffer in both cases.
1992 If there is output and an error, a message about the error
1993 appears at the end of the output.
1995 If there is no output, or if output is inserted in the current buffer,
1996 then `*Shell Command Output*' is deleted.
1998 If the optional fourth argument OUTPUT-BUFFER is non-nil,
1999 that says to put the output in some other buffer.
2000 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2001 If OUTPUT-BUFFER is not a buffer and not nil,
2002 insert output in the current buffer.
2003 In either case, the output is inserted after point (leaving mark after it).
2005 If REPLACE, the optional fifth argument, is non-nil, that means insert
2006 the output in place of text from START to END, putting point and mark
2007 around it.
2009 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2010 or buffer name to which to direct the command's standard error output.
2011 If it is nil, error output is mingled with regular output.
2012 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2013 were any errors. (This is always t, interactively.)
2014 In an interactive call, the variable `shell-command-default-error-buffer'
2015 specifies the value of ERROR-BUFFER."
2016 (interactive (let (string)
2017 (unless (mark)
2018 (error "The mark is not set now, so there is no region"))
2019 ;; Do this before calling region-beginning
2020 ;; and region-end, in case subprocess output
2021 ;; relocates them while we are in the minibuffer.
2022 (setq string (read-from-minibuffer "Shell command on region: "
2023 nil nil nil
2024 'shell-command-history))
2025 ;; call-interactively recognizes region-beginning and
2026 ;; region-end specially, leaving them in the history.
2027 (list (region-beginning) (region-end)
2028 string
2029 current-prefix-arg
2030 current-prefix-arg
2031 shell-command-default-error-buffer
2032 t)))
2033 (let ((error-file
2034 (if error-buffer
2035 (make-temp-file
2036 (expand-file-name "scor"
2037 (or small-temporary-file-directory
2038 temporary-file-directory)))
2039 nil))
2040 exit-status)
2041 (if (or replace
2042 (and output-buffer
2043 (not (or (bufferp output-buffer) (stringp output-buffer)))))
2044 ;; Replace specified region with output from command.
2045 (let ((swap (and replace (< start end))))
2046 ;; Don't muck with mark unless REPLACE says we should.
2047 (goto-char start)
2048 (and replace (push-mark (point) 'nomsg))
2049 (setq exit-status
2050 (call-process-region start end shell-file-name t
2051 (if error-file
2052 (list t error-file)
2054 nil shell-command-switch command))
2055 ;; It is rude to delete a buffer which the command is not using.
2056 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2057 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2058 ;; (kill-buffer shell-buffer)))
2059 ;; Don't muck with mark unless REPLACE says we should.
2060 (and replace swap (exchange-point-and-mark)))
2061 ;; No prefix argument: put the output in a temp buffer,
2062 ;; replacing its entire contents.
2063 (let ((buffer (get-buffer-create
2064 (or output-buffer "*Shell Command Output*"))))
2065 (unwind-protect
2066 (if (eq buffer (current-buffer))
2067 ;; If the input is the same buffer as the output,
2068 ;; delete everything but the specified region,
2069 ;; then replace that region with the output.
2070 (progn (setq buffer-read-only nil)
2071 (delete-region (max start end) (point-max))
2072 (delete-region (point-min) (min start end))
2073 (setq exit-status
2074 (call-process-region (point-min) (point-max)
2075 shell-file-name t
2076 (if error-file
2077 (list t error-file)
2079 nil shell-command-switch
2080 command)))
2081 ;; Clear the output buffer, then run the command with
2082 ;; output there.
2083 (let ((directory default-directory))
2084 (save-excursion
2085 (set-buffer buffer)
2086 (setq buffer-read-only nil)
2087 (if (not output-buffer)
2088 (setq default-directory directory))
2089 (erase-buffer)))
2090 (setq exit-status
2091 (call-process-region start end shell-file-name nil
2092 (if error-file
2093 (list buffer error-file)
2094 buffer)
2095 nil shell-command-switch command)))
2096 ;; Report the output.
2097 (with-current-buffer buffer
2098 (setq mode-line-process
2099 (cond ((null exit-status)
2100 " - Error")
2101 ((stringp exit-status)
2102 (format " - Signal [%s]" exit-status))
2103 ((not (equal 0 exit-status))
2104 (format " - Exit [%d]" exit-status)))))
2105 (if (with-current-buffer buffer (> (point-max) (point-min)))
2106 ;; There's some output, display it
2107 (display-message-or-buffer buffer)
2108 ;; No output; error?
2109 (let ((output
2110 (if (and error-file
2111 (< 0 (nth 7 (file-attributes error-file))))
2112 "some error output"
2113 "no output")))
2114 (cond ((null exit-status)
2115 (message "(Shell command failed with error)"))
2116 ((equal 0 exit-status)
2117 (message "(Shell command succeeded with %s)"
2118 output))
2119 ((stringp exit-status)
2120 (message "(Shell command killed by signal %s)"
2121 exit-status))
2123 (message "(Shell command failed with code %d and %s)"
2124 exit-status output))))
2125 ;; Don't kill: there might be useful info in the undo-log.
2126 ;; (kill-buffer buffer)
2127 ))))
2129 (when (and error-file (file-exists-p error-file))
2130 (if (< 0 (nth 7 (file-attributes error-file)))
2131 (with-current-buffer (get-buffer-create error-buffer)
2132 (let ((pos-from-end (- (point-max) (point))))
2133 (or (bobp)
2134 (insert "\f\n"))
2135 ;; Do no formatting while reading error file,
2136 ;; because that can run a shell command, and we
2137 ;; don't want that to cause an infinite recursion.
2138 (format-insert-file error-file nil)
2139 ;; Put point after the inserted errors.
2140 (goto-char (- (point-max) pos-from-end)))
2141 (and display-error-buffer
2142 (display-buffer (current-buffer)))))
2143 (delete-file error-file))
2144 exit-status))
2146 (defun shell-command-to-string (command)
2147 "Execute shell command COMMAND and return its output as a string."
2148 (with-output-to-string
2149 (with-current-buffer
2150 standard-output
2151 (call-process shell-file-name nil t nil shell-command-switch command))))
2153 (defun process-file (program &optional infile buffer display &rest args)
2154 "Process files synchronously in a separate process.
2155 Similar to `call-process', but may invoke a file handler based on
2156 `default-directory'. The current working directory of the
2157 subprocess is `default-directory'.
2159 File names in INFILE and BUFFER are handled normally, but file
2160 names in ARGS should be relative to `default-directory', as they
2161 are passed to the process verbatim. \(This is a difference to
2162 `call-process' which does not support file handlers for INFILE
2163 and BUFFER.\)
2165 Some file handlers might not support all variants, for example
2166 they might behave as if DISPLAY was nil, regardless of the actual
2167 value passed."
2168 (let ((fh (find-file-name-handler default-directory 'process-file))
2169 lc stderr-file)
2170 (unwind-protect
2171 (if fh (apply fh 'process-file program infile buffer display args)
2172 (when infile (setq lc (file-local-copy infile)))
2173 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
2174 (make-temp-file "emacs")))
2175 (prog1
2176 (apply 'call-process program
2177 (or lc infile)
2178 (if stderr-file (list (car buffer) stderr-file) buffer)
2179 display args)
2180 (when stderr-file (copy-file stderr-file (cadr buffer)))))
2181 (when stderr-file (delete-file stderr-file))
2182 (when lc (delete-file lc)))))
2186 (defvar universal-argument-map
2187 (let ((map (make-sparse-keymap)))
2188 (define-key map [t] 'universal-argument-other-key)
2189 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2190 (define-key map [switch-frame] nil)
2191 (define-key map [?\C-u] 'universal-argument-more)
2192 (define-key map [?-] 'universal-argument-minus)
2193 (define-key map [?0] 'digit-argument)
2194 (define-key map [?1] 'digit-argument)
2195 (define-key map [?2] 'digit-argument)
2196 (define-key map [?3] 'digit-argument)
2197 (define-key map [?4] 'digit-argument)
2198 (define-key map [?5] 'digit-argument)
2199 (define-key map [?6] 'digit-argument)
2200 (define-key map [?7] 'digit-argument)
2201 (define-key map [?8] 'digit-argument)
2202 (define-key map [?9] 'digit-argument)
2203 (define-key map [kp-0] 'digit-argument)
2204 (define-key map [kp-1] 'digit-argument)
2205 (define-key map [kp-2] 'digit-argument)
2206 (define-key map [kp-3] 'digit-argument)
2207 (define-key map [kp-4] 'digit-argument)
2208 (define-key map [kp-5] 'digit-argument)
2209 (define-key map [kp-6] 'digit-argument)
2210 (define-key map [kp-7] 'digit-argument)
2211 (define-key map [kp-8] 'digit-argument)
2212 (define-key map [kp-9] 'digit-argument)
2213 (define-key map [kp-subtract] 'universal-argument-minus)
2214 map)
2215 "Keymap used while processing \\[universal-argument].")
2217 (defvar universal-argument-num-events nil
2218 "Number of argument-specifying events read by `universal-argument'.
2219 `universal-argument-other-key' uses this to discard those events
2220 from (this-command-keys), and reread only the final command.")
2222 (defvar overriding-map-is-bound nil
2223 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2225 (defvar saved-overriding-map nil
2226 "The saved value of `overriding-terminal-local-map'.
2227 That variable gets restored to this value on exiting \"universal
2228 argument mode\".")
2230 (defun ensure-overriding-map-is-bound ()
2231 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2232 (unless overriding-map-is-bound
2233 (setq saved-overriding-map overriding-terminal-local-map)
2234 (setq overriding-terminal-local-map universal-argument-map)
2235 (setq overriding-map-is-bound t)))
2237 (defun restore-overriding-map ()
2238 "Restore `overriding-terminal-local-map' to its saved value."
2239 (setq overriding-terminal-local-map saved-overriding-map)
2240 (setq overriding-map-is-bound nil))
2242 (defun universal-argument ()
2243 "Begin a numeric argument for the following command.
2244 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2245 \\[universal-argument] following the digits or minus sign ends the argument.
2246 \\[universal-argument] without digits or minus sign provides 4 as argument.
2247 Repeating \\[universal-argument] without digits or minus sign
2248 multiplies the argument by 4 each time.
2249 For some commands, just \\[universal-argument] by itself serves as a flag
2250 which is different in effect from any particular numeric argument.
2251 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2252 (interactive)
2253 (setq prefix-arg (list 4))
2254 (setq universal-argument-num-events (length (this-command-keys)))
2255 (ensure-overriding-map-is-bound))
2257 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2258 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2259 (defun universal-argument-more (arg)
2260 (interactive "P")
2261 (if (consp arg)
2262 (setq prefix-arg (list (* 4 (car arg))))
2263 (if (eq arg '-)
2264 (setq prefix-arg (list -4))
2265 (setq prefix-arg arg)
2266 (restore-overriding-map)))
2267 (setq universal-argument-num-events (length (this-command-keys))))
2269 (defun negative-argument (arg)
2270 "Begin a negative numeric argument for the next command.
2271 \\[universal-argument] following digits or minus sign ends the argument."
2272 (interactive "P")
2273 (cond ((integerp arg)
2274 (setq prefix-arg (- arg)))
2275 ((eq arg '-)
2276 (setq prefix-arg nil))
2278 (setq prefix-arg '-)))
2279 (setq universal-argument-num-events (length (this-command-keys)))
2280 (ensure-overriding-map-is-bound))
2282 (defun digit-argument (arg)
2283 "Part of the numeric argument for the next command.
2284 \\[universal-argument] following digits or minus sign ends the argument."
2285 (interactive "P")
2286 (let* ((char (if (integerp last-command-char)
2287 last-command-char
2288 (get last-command-char 'ascii-character)))
2289 (digit (- (logand char ?\177) ?0)))
2290 (cond ((integerp arg)
2291 (setq prefix-arg (+ (* arg 10)
2292 (if (< arg 0) (- digit) digit))))
2293 ((eq arg '-)
2294 ;; Treat -0 as just -, so that -01 will work.
2295 (setq prefix-arg (if (zerop digit) '- (- digit))))
2297 (setq prefix-arg digit))))
2298 (setq universal-argument-num-events (length (this-command-keys)))
2299 (ensure-overriding-map-is-bound))
2301 ;; For backward compatibility, minus with no modifiers is an ordinary
2302 ;; command if digits have already been entered.
2303 (defun universal-argument-minus (arg)
2304 (interactive "P")
2305 (if (integerp arg)
2306 (universal-argument-other-key arg)
2307 (negative-argument arg)))
2309 ;; Anything else terminates the argument and is left in the queue to be
2310 ;; executed as a command.
2311 (defun universal-argument-other-key (arg)
2312 (interactive "P")
2313 (setq prefix-arg arg)
2314 (let* ((key (this-command-keys))
2315 (keylist (listify-key-sequence key)))
2316 (setq unread-command-events
2317 (append (nthcdr universal-argument-num-events keylist)
2318 unread-command-events)))
2319 (reset-this-command-lengths)
2320 (restore-overriding-map))
2322 (defvar buffer-substring-filters nil
2323 "List of filter functions for `filter-buffer-substring'.
2324 Each function must accept a single argument, a string, and return
2325 a string. The buffer substring is passed to the first function
2326 in the list, and the return value of each function is passed to
2327 the next. The return value of the last function is used as the
2328 return value of `filter-buffer-substring'.
2330 If this variable is nil, no filtering is performed.")
2332 (defun filter-buffer-substring (beg end &optional delete)
2333 "Return the buffer substring between BEG and END, after filtering.
2334 The buffer substring is passed through each of the filter
2335 functions in `buffer-substring-filters', and the value from the
2336 last filter function is returned. If `buffer-substring-filters'
2337 is nil, the buffer substring is returned unaltered.
2339 If DELETE is non-nil, the text between BEG and END is deleted
2340 from the buffer.
2342 Point is temporarily set to BEG before calling
2343 `buffer-substring-filters', in case the functions need to know
2344 where the text came from.
2346 This function should be used instead of `buffer-substring' or
2347 `delete-and-extract-region' when you want to allow filtering to
2348 take place. For example, major or minor modes can use
2349 `buffer-substring-filters' to extract characters that are special
2350 to a buffer, and should not be copied into other buffers."
2351 (save-excursion
2352 (goto-char beg)
2353 (let ((string (if delete (delete-and-extract-region beg end)
2354 (buffer-substring beg end))))
2355 (dolist (filter buffer-substring-filters string)
2356 (setq string (funcall filter string))))))
2358 ;;;; Window system cut and paste hooks.
2360 (defvar interprogram-cut-function nil
2361 "Function to call to make a killed region available to other programs.
2363 Most window systems provide some sort of facility for cutting and
2364 pasting text between the windows of different programs.
2365 This variable holds a function that Emacs calls whenever text
2366 is put in the kill ring, to make the new kill available to other
2367 programs.
2369 The function takes one or two arguments.
2370 The first argument, TEXT, is a string containing
2371 the text which should be made available.
2372 The second, optional, argument PUSH, has the same meaning as the
2373 similar argument to `x-set-cut-buffer', which see.")
2375 (defvar interprogram-paste-function nil
2376 "Function to call to get text cut from other programs.
2378 Most window systems provide some sort of facility for cutting and
2379 pasting text between the windows of different programs.
2380 This variable holds a function that Emacs calls to obtain
2381 text that other programs have provided for pasting.
2383 The function should be called with no arguments. If the function
2384 returns nil, then no other program has provided such text, and the top
2385 of the Emacs kill ring should be used. If the function returns a
2386 string, then the caller of the function \(usually `current-kill')
2387 should put this string in the kill ring as the latest kill.
2389 Note that the function should return a string only if a program other
2390 than Emacs has provided a string for pasting; if Emacs provided the
2391 most recent string, the function should return nil. If it is
2392 difficult to tell whether Emacs or some other program provided the
2393 current string, it is probably good enough to return nil if the string
2394 is equal (according to `string=') to the last text Emacs provided.")
2398 ;;;; The kill ring data structure.
2400 (defvar kill-ring nil
2401 "List of killed text sequences.
2402 Since the kill ring is supposed to interact nicely with cut-and-paste
2403 facilities offered by window systems, use of this variable should
2404 interact nicely with `interprogram-cut-function' and
2405 `interprogram-paste-function'. The functions `kill-new',
2406 `kill-append', and `current-kill' are supposed to implement this
2407 interaction; you may want to use them instead of manipulating the kill
2408 ring directly.")
2410 (defcustom kill-ring-max 60
2411 "*Maximum length of kill ring before oldest elements are thrown away."
2412 :type 'integer
2413 :group 'killing)
2415 (defvar kill-ring-yank-pointer nil
2416 "The tail of the kill ring whose car is the last thing yanked.")
2418 (defun kill-new (string &optional replace yank-handler)
2419 "Make STRING the latest kill in the kill ring.
2420 Set `kill-ring-yank-pointer' to point to it.
2421 If `interprogram-cut-function' is non-nil, apply it to STRING.
2422 Optional second argument REPLACE non-nil means that STRING will replace
2423 the front of the kill ring, rather than being added to the list.
2425 Optional third arguments YANK-HANDLER controls how the STRING is later
2426 inserted into a buffer; see `insert-for-yank' for details.
2427 When a yank handler is specified, STRING must be non-empty (the yank
2428 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2430 When the yank handler has a non-nil PARAM element, the original STRING
2431 argument is not used by `insert-for-yank'. However, since Lisp code
2432 may access and use elements from the kill ring directly, the STRING
2433 argument should still be a \"useful\" string for such uses."
2434 (if (> (length string) 0)
2435 (if yank-handler
2436 (put-text-property 0 (length string)
2437 'yank-handler yank-handler string))
2438 (if yank-handler
2439 (signal 'args-out-of-range
2440 (list string "yank-handler specified for empty string"))))
2441 (if (fboundp 'menu-bar-update-yank-menu)
2442 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2443 (if (and replace kill-ring)
2444 (setcar kill-ring string)
2445 (push string kill-ring)
2446 (if (> (length kill-ring) kill-ring-max)
2447 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2448 (setq kill-ring-yank-pointer kill-ring)
2449 (if interprogram-cut-function
2450 (funcall interprogram-cut-function string (not replace))))
2452 (defun kill-append (string before-p &optional yank-handler)
2453 "Append STRING to the end of the latest kill in the kill ring.
2454 If BEFORE-P is non-nil, prepend STRING to the kill.
2455 Optional third argument YANK-HANDLER, if non-nil, specifies the
2456 yank-handler text property to be set on the combined kill ring
2457 string. If the specified yank-handler arg differs from the
2458 yank-handler property of the latest kill string, this function
2459 adds the combined string to the kill ring as a new element,
2460 instead of replacing the last kill with it.
2461 If `interprogram-cut-function' is set, pass the resulting kill to it."
2462 (let* ((cur (car kill-ring)))
2463 (kill-new (if before-p (concat string cur) (concat cur string))
2464 (or (= (length cur) 0)
2465 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2466 yank-handler)))
2468 (defun current-kill (n &optional do-not-move)
2469 "Rotate the yanking point by N places, and then return that kill.
2470 If N is zero, `interprogram-paste-function' is set, and calling it
2471 returns a string, then that string is added to the front of the
2472 kill ring and returned as the latest kill.
2473 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
2474 yanking point; just return the Nth kill forward."
2475 (let ((interprogram-paste (and (= n 0)
2476 interprogram-paste-function
2477 (funcall interprogram-paste-function))))
2478 (if interprogram-paste
2479 (progn
2480 ;; Disable the interprogram cut function when we add the new
2481 ;; text to the kill ring, so Emacs doesn't try to own the
2482 ;; selection, with identical text.
2483 (let ((interprogram-cut-function nil))
2484 (kill-new interprogram-paste))
2485 interprogram-paste)
2486 (or kill-ring (error "Kill ring is empty"))
2487 (let ((ARGth-kill-element
2488 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2489 (length kill-ring))
2490 kill-ring)))
2491 (or do-not-move
2492 (setq kill-ring-yank-pointer ARGth-kill-element))
2493 (car ARGth-kill-element)))))
2497 ;;;; Commands for manipulating the kill ring.
2499 (defcustom kill-read-only-ok nil
2500 "*Non-nil means don't signal an error for killing read-only text."
2501 :type 'boolean
2502 :group 'killing)
2504 (put 'text-read-only 'error-conditions
2505 '(text-read-only buffer-read-only error))
2506 (put 'text-read-only 'error-message "Text is read-only")
2508 (defun kill-region (beg end &optional yank-handler)
2509 "Kill between point and mark.
2510 The text is deleted but saved in the kill ring.
2511 The command \\[yank] can retrieve it from there.
2512 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2514 If you want to append the killed region to the last killed text,
2515 use \\[append-next-kill] before \\[kill-region].
2517 If the buffer is read-only, Emacs will beep and refrain from deleting
2518 the text, but put the text in the kill ring anyway. This means that
2519 you can use the killing commands to copy text from a read-only buffer.
2521 This is the primitive for programs to kill text (as opposed to deleting it).
2522 Supply two arguments, character positions indicating the stretch of text
2523 to be killed.
2524 Any command that calls this function is a \"kill command\".
2525 If the previous command was also a kill command,
2526 the text killed this time appends to the text killed last time
2527 to make one entry in the kill ring.
2529 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2530 specifies the yank-handler text property to be set on the killed
2531 text. See `insert-for-yank'."
2532 (interactive "r")
2533 (condition-case nil
2534 (let ((string (filter-buffer-substring beg end t)))
2535 (when string ;STRING is nil if BEG = END
2536 ;; Add that string to the kill ring, one way or another.
2537 (if (eq last-command 'kill-region)
2538 (kill-append string (< end beg) yank-handler)
2539 (kill-new string nil yank-handler)))
2540 (when (or string (eq last-command 'kill-region))
2541 (setq this-command 'kill-region))
2542 nil)
2543 ((buffer-read-only text-read-only)
2544 ;; The code above failed because the buffer, or some of the characters
2545 ;; in the region, are read-only.
2546 ;; We should beep, in case the user just isn't aware of this.
2547 ;; However, there's no harm in putting
2548 ;; the region's text in the kill ring, anyway.
2549 (copy-region-as-kill beg end)
2550 ;; Set this-command now, so it will be set even if we get an error.
2551 (setq this-command 'kill-region)
2552 ;; This should barf, if appropriate, and give us the correct error.
2553 (if kill-read-only-ok
2554 (progn (message "Read only text copied to kill ring") nil)
2555 ;; Signal an error if the buffer is read-only.
2556 (barf-if-buffer-read-only)
2557 ;; If the buffer isn't read-only, the text is.
2558 (signal 'text-read-only (list (current-buffer)))))))
2560 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2561 ;; to get two copies of the text when the user accidentally types M-w and
2562 ;; then corrects it with the intended C-w.
2563 (defun copy-region-as-kill (beg end)
2564 "Save the region as if killed, but don't kill it.
2565 In Transient Mark mode, deactivate the mark.
2566 If `interprogram-cut-function' is non-nil, also save the text for a window
2567 system cut and paste."
2568 (interactive "r")
2569 (if (eq last-command 'kill-region)
2570 (kill-append (filter-buffer-substring beg end) (< end beg))
2571 (kill-new (filter-buffer-substring beg end)))
2572 (if transient-mark-mode
2573 (setq deactivate-mark t))
2574 nil)
2576 (defun kill-ring-save (beg end)
2577 "Save the region as if killed, but don't kill it.
2578 In Transient Mark mode, deactivate the mark.
2579 If `interprogram-cut-function' is non-nil, also save the text for a window
2580 system cut and paste.
2582 If you want to append the killed line to the last killed text,
2583 use \\[append-next-kill] before \\[kill-ring-save].
2585 This command is similar to `copy-region-as-kill', except that it gives
2586 visual feedback indicating the extent of the region being copied."
2587 (interactive "r")
2588 (copy-region-as-kill beg end)
2589 ;; This use of interactive-p is correct
2590 ;; because the code it controls just gives the user visual feedback.
2591 (if (interactive-p)
2592 (let ((other-end (if (= (point) beg) end beg))
2593 (opoint (point))
2594 ;; Inhibit quitting so we can make a quit here
2595 ;; look like a C-g typed as a command.
2596 (inhibit-quit t))
2597 (if (pos-visible-in-window-p other-end (selected-window))
2598 (unless (and transient-mark-mode
2599 (face-background 'region))
2600 ;; Swap point and mark.
2601 (set-marker (mark-marker) (point) (current-buffer))
2602 (goto-char other-end)
2603 (sit-for blink-matching-delay)
2604 ;; Swap back.
2605 (set-marker (mark-marker) other-end (current-buffer))
2606 (goto-char opoint)
2607 ;; If user quit, deactivate the mark
2608 ;; as C-g would as a command.
2609 (and quit-flag mark-active
2610 (deactivate-mark)))
2611 (let* ((killed-text (current-kill 0))
2612 (message-len (min (length killed-text) 40)))
2613 (if (= (point) beg)
2614 ;; Don't say "killed"; that is misleading.
2615 (message "Saved text until \"%s\""
2616 (substring killed-text (- message-len)))
2617 (message "Saved text from \"%s\""
2618 (substring killed-text 0 message-len))))))))
2620 (defun append-next-kill (&optional interactive)
2621 "Cause following command, if it kills, to append to previous kill.
2622 The argument is used for internal purposes; do not supply one."
2623 (interactive "p")
2624 ;; We don't use (interactive-p), since that breaks kbd macros.
2625 (if interactive
2626 (progn
2627 (setq this-command 'kill-region)
2628 (message "If the next command is a kill, it will append"))
2629 (setq last-command 'kill-region)))
2631 ;; Yanking.
2633 ;; This is actually used in subr.el but defcustom does not work there.
2634 (defcustom yank-excluded-properties
2635 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2636 yank-handler follow-link)
2637 "*Text properties to discard when yanking.
2638 The value should be a list of text properties to discard or t,
2639 which means to discard all text properties."
2640 :type '(choice (const :tag "All" t) (repeat symbol))
2641 :group 'killing
2642 :version "22.1")
2644 (defvar yank-window-start nil)
2645 (defvar yank-undo-function nil
2646 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2647 Function is called with two parameters, START and END corresponding to
2648 the value of the mark and point; it is guaranteed that START <= END.
2649 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2651 (defun yank-pop (&optional arg)
2652 "Replace just-yanked stretch of killed text with a different stretch.
2653 This command is allowed only immediately after a `yank' or a `yank-pop'.
2654 At such a time, the region contains a stretch of reinserted
2655 previously-killed text. `yank-pop' deletes that text and inserts in its
2656 place a different stretch of killed text.
2658 With no argument, the previous kill is inserted.
2659 With argument N, insert the Nth previous kill.
2660 If N is negative, this is a more recent kill.
2662 The sequence of kills wraps around, so that after the oldest one
2663 comes the newest one.
2665 When this command inserts killed text into the buffer, it honors
2666 `yank-excluded-properties' and `yank-handler' as described in the
2667 doc string for `insert-for-yank-1', which see."
2668 (interactive "*p")
2669 (if (not (eq last-command 'yank))
2670 (error "Previous command was not a yank"))
2671 (setq this-command 'yank)
2672 (unless arg (setq arg 1))
2673 (let ((inhibit-read-only t)
2674 (before (< (point) (mark t))))
2675 (if before
2676 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2677 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2678 (setq yank-undo-function nil)
2679 (set-marker (mark-marker) (point) (current-buffer))
2680 (insert-for-yank (current-kill arg))
2681 ;; Set the window start back where it was in the yank command,
2682 ;; if possible.
2683 (set-window-start (selected-window) yank-window-start t)
2684 (if before
2685 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2686 ;; It is cleaner to avoid activation, even though the command
2687 ;; loop would deactivate the mark because we inserted text.
2688 (goto-char (prog1 (mark t)
2689 (set-marker (mark-marker) (point) (current-buffer))))))
2690 nil)
2692 (defun yank (&optional arg)
2693 "Reinsert the last stretch of killed text.
2694 More precisely, reinsert the stretch of killed text most recently
2695 killed OR yanked. Put point at end, and set mark at beginning.
2696 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2697 With argument N, reinsert the Nth most recently killed stretch of killed
2698 text.
2700 When this command inserts killed text into the buffer, it honors
2701 `yank-excluded-properties' and `yank-handler' as described in the
2702 doc string for `insert-for-yank-1', which see.
2704 See also the command \\[yank-pop]."
2705 (interactive "*P")
2706 (setq yank-window-start (window-start))
2707 ;; If we don't get all the way thru, make last-command indicate that
2708 ;; for the following command.
2709 (setq this-command t)
2710 (push-mark (point))
2711 (insert-for-yank (current-kill (cond
2712 ((listp arg) 0)
2713 ((eq arg '-) -2)
2714 (t (1- arg)))))
2715 (if (consp arg)
2716 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2717 ;; It is cleaner to avoid activation, even though the command
2718 ;; loop would deactivate the mark because we inserted text.
2719 (goto-char (prog1 (mark t)
2720 (set-marker (mark-marker) (point) (current-buffer)))))
2721 ;; If we do get all the way thru, make this-command indicate that.
2722 (if (eq this-command t)
2723 (setq this-command 'yank))
2724 nil)
2726 (defun rotate-yank-pointer (arg)
2727 "Rotate the yanking point in the kill ring.
2728 With argument, rotate that many kills forward (or backward, if negative)."
2729 (interactive "p")
2730 (current-kill arg))
2732 ;; Some kill commands.
2734 ;; Internal subroutine of delete-char
2735 (defun kill-forward-chars (arg)
2736 (if (listp arg) (setq arg (car arg)))
2737 (if (eq arg '-) (setq arg -1))
2738 (kill-region (point) (forward-point arg)))
2740 ;; Internal subroutine of backward-delete-char
2741 (defun kill-backward-chars (arg)
2742 (if (listp arg) (setq arg (car arg)))
2743 (if (eq arg '-) (setq arg -1))
2744 (kill-region (point) (forward-point (- arg))))
2746 (defcustom backward-delete-char-untabify-method 'untabify
2747 "*The method for untabifying when deleting backward.
2748 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2749 `hungry' -- delete all whitespace, both tabs and spaces;
2750 `all' -- delete all whitespace, including tabs, spaces and newlines;
2751 nil -- just delete one character."
2752 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2753 :version "20.3"
2754 :group 'killing)
2756 (defun backward-delete-char-untabify (arg &optional killp)
2757 "Delete characters backward, changing tabs into spaces.
2758 The exact behavior depends on `backward-delete-char-untabify-method'.
2759 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2760 Interactively, ARG is the prefix arg (default 1)
2761 and KILLP is t if a prefix arg was specified."
2762 (interactive "*p\nP")
2763 (when (eq backward-delete-char-untabify-method 'untabify)
2764 (let ((count arg))
2765 (save-excursion
2766 (while (and (> count 0) (not (bobp)))
2767 (if (= (preceding-char) ?\t)
2768 (let ((col (current-column)))
2769 (forward-char -1)
2770 (setq col (- col (current-column)))
2771 (insert-char ?\s col)
2772 (delete-char 1)))
2773 (forward-char -1)
2774 (setq count (1- count))))))
2775 (delete-backward-char
2776 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2777 ((eq backward-delete-char-untabify-method 'all)
2778 " \t\n\r"))))
2779 (if skip
2780 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2781 (point)))))
2782 (+ arg (if (zerop wh) 0 (1- wh))))
2783 arg))
2784 killp))
2786 (defun zap-to-char (arg char)
2787 "Kill up to and including ARG'th occurrence of CHAR.
2788 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2789 Goes backward if ARG is negative; error if CHAR not found."
2790 (interactive "p\ncZap to char: ")
2791 (if (char-table-p translation-table-for-input)
2792 (setq char (or (aref translation-table-for-input char) char)))
2793 (kill-region (point) (progn
2794 (search-forward (char-to-string char) nil nil arg)
2795 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2796 (point))))
2798 ;; kill-line and its subroutines.
2800 (defcustom kill-whole-line nil
2801 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2802 :type 'boolean
2803 :group 'killing)
2805 (defun kill-line (&optional arg)
2806 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2807 With prefix argument, kill that many lines from point.
2808 Negative arguments kill lines backward.
2809 With zero argument, kills the text before point on the current line.
2811 When calling from a program, nil means \"no arg\",
2812 a number counts as a prefix arg.
2814 To kill a whole line, when point is not at the beginning, type \
2815 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2817 If `kill-whole-line' is non-nil, then this command kills the whole line
2818 including its terminating newline, when used at the beginning of a line
2819 with no argument. As a consequence, you can always kill a whole line
2820 by typing \\[beginning-of-line] \\[kill-line].
2822 If you want to append the killed line to the last killed text,
2823 use \\[append-next-kill] before \\[kill-line].
2825 If the buffer is read-only, Emacs will beep and refrain from deleting
2826 the line, but put the line in the kill ring anyway. This means that
2827 you can use this command to copy text from a read-only buffer.
2828 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2829 even beep.)"
2830 (interactive "P")
2831 (kill-region (point)
2832 ;; It is better to move point to the other end of the kill
2833 ;; before killing. That way, in a read-only buffer, point
2834 ;; moves across the text that is copied to the kill ring.
2835 ;; The choice has no effect on undo now that undo records
2836 ;; the value of point from before the command was run.
2837 (progn
2838 (if arg
2839 (forward-visible-line (prefix-numeric-value arg))
2840 (if (eobp)
2841 (signal 'end-of-buffer nil))
2842 (let ((end
2843 (save-excursion
2844 (end-of-visible-line) (point))))
2845 (if (or (save-excursion
2846 ;; If trailing whitespace is visible,
2847 ;; don't treat it as nothing.
2848 (unless show-trailing-whitespace
2849 (skip-chars-forward " \t" end))
2850 (= (point) end))
2851 (and kill-whole-line (bolp)))
2852 (forward-visible-line 1)
2853 (goto-char end))))
2854 (point))))
2856 (defun kill-whole-line (&optional arg)
2857 "Kill current line.
2858 With prefix arg, kill that many lines starting from the current line.
2859 If arg is negative, kill backward. Also kill the preceding newline.
2860 \(This is meant to make \\[repeat] work well with negative arguments.\)
2861 If arg is zero, kill current line but exclude the trailing newline."
2862 (interactive "p")
2863 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2864 (signal 'end-of-buffer nil))
2865 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2866 (signal 'beginning-of-buffer nil))
2867 (unless (eq last-command 'kill-region)
2868 (kill-new "")
2869 (setq last-command 'kill-region))
2870 (cond ((zerop arg)
2871 ;; We need to kill in two steps, because the previous command
2872 ;; could have been a kill command, in which case the text
2873 ;; before point needs to be prepended to the current kill
2874 ;; ring entry and the text after point appended. Also, we
2875 ;; need to use save-excursion to avoid copying the same text
2876 ;; twice to the kill ring in read-only buffers.
2877 (save-excursion
2878 (kill-region (point) (progn (forward-visible-line 0) (point))))
2879 (kill-region (point) (progn (end-of-visible-line) (point))))
2880 ((< arg 0)
2881 (save-excursion
2882 (kill-region (point) (progn (end-of-visible-line) (point))))
2883 (kill-region (point)
2884 (progn (forward-visible-line (1+ arg))
2885 (unless (bobp) (backward-char))
2886 (point))))
2888 (save-excursion
2889 (kill-region (point) (progn (forward-visible-line 0) (point))))
2890 (kill-region (point)
2891 (progn (forward-visible-line arg) (point))))))
2893 (defun forward-visible-line (arg)
2894 "Move forward by ARG lines, ignoring currently invisible newlines only.
2895 If ARG is negative, move backward -ARG lines.
2896 If ARG is zero, move to the beginning of the current line."
2897 (condition-case nil
2898 (if (> arg 0)
2899 (progn
2900 (while (> arg 0)
2901 (or (zerop (forward-line 1))
2902 (signal 'end-of-buffer nil))
2903 ;; If the newline we just skipped is invisible,
2904 ;; don't count it.
2905 (let ((prop
2906 (get-char-property (1- (point)) 'invisible)))
2907 (if (if (eq buffer-invisibility-spec t)
2908 prop
2909 (or (memq prop buffer-invisibility-spec)
2910 (assq prop buffer-invisibility-spec)))
2911 (setq arg (1+ arg))))
2912 (setq arg (1- arg)))
2913 ;; If invisible text follows, and it is a number of complete lines,
2914 ;; skip it.
2915 (let ((opoint (point)))
2916 (while (and (not (eobp))
2917 (let ((prop
2918 (get-char-property (point) 'invisible)))
2919 (if (eq buffer-invisibility-spec t)
2920 prop
2921 (or (memq prop buffer-invisibility-spec)
2922 (assq prop buffer-invisibility-spec)))))
2923 (goto-char
2924 (if (get-text-property (point) 'invisible)
2925 (or (next-single-property-change (point) 'invisible)
2926 (point-max))
2927 (next-overlay-change (point)))))
2928 (unless (bolp)
2929 (goto-char opoint))))
2930 (let ((first t))
2931 (while (or first (<= arg 0))
2932 (if first
2933 (beginning-of-line)
2934 (or (zerop (forward-line -1))
2935 (signal 'beginning-of-buffer nil)))
2936 ;; If the newline we just moved to is invisible,
2937 ;; don't count it.
2938 (unless (bobp)
2939 (let ((prop
2940 (get-char-property (1- (point)) 'invisible)))
2941 (unless (if (eq buffer-invisibility-spec t)
2942 prop
2943 (or (memq prop buffer-invisibility-spec)
2944 (assq prop buffer-invisibility-spec)))
2945 (setq arg (1+ arg)))))
2946 (setq first nil))
2947 ;; If invisible text follows, and it is a number of complete lines,
2948 ;; skip it.
2949 (let ((opoint (point)))
2950 (while (and (not (bobp))
2951 (let ((prop
2952 (get-char-property (1- (point)) 'invisible)))
2953 (if (eq buffer-invisibility-spec t)
2954 prop
2955 (or (memq prop buffer-invisibility-spec)
2956 (assq prop buffer-invisibility-spec)))))
2957 (goto-char
2958 (if (get-text-property (1- (point)) 'invisible)
2959 (or (previous-single-property-change (point) 'invisible)
2960 (point-min))
2961 (previous-overlay-change (point)))))
2962 (unless (bolp)
2963 (goto-char opoint)))))
2964 ((beginning-of-buffer end-of-buffer)
2965 nil)))
2967 (defun end-of-visible-line ()
2968 "Move to end of current visible line."
2969 (end-of-line)
2970 ;; If the following character is currently invisible,
2971 ;; skip all characters with that same `invisible' property value,
2972 ;; then find the next newline.
2973 (while (and (not (eobp))
2974 (save-excursion
2975 (skip-chars-forward "^\n")
2976 (let ((prop
2977 (get-char-property (point) 'invisible)))
2978 (if (eq buffer-invisibility-spec t)
2979 prop
2980 (or (memq prop buffer-invisibility-spec)
2981 (assq prop buffer-invisibility-spec))))))
2982 (skip-chars-forward "^\n")
2983 (if (get-text-property (point) 'invisible)
2984 (goto-char (next-single-property-change (point) 'invisible))
2985 (goto-char (next-overlay-change (point))))
2986 (end-of-line)))
2988 (defun insert-buffer (buffer)
2989 "Insert after point the contents of BUFFER.
2990 Puts mark after the inserted text.
2991 BUFFER may be a buffer or a buffer name.
2993 This function is meant for the user to run interactively.
2994 Don't call it from programs: use `insert-buffer-substring' instead!"
2995 (interactive
2996 (list
2997 (progn
2998 (barf-if-buffer-read-only)
2999 (read-buffer "Insert buffer: "
3000 (if (eq (selected-window) (next-window (selected-window)))
3001 (other-buffer (current-buffer))
3002 (window-buffer (next-window (selected-window))))
3003 t))))
3004 (push-mark
3005 (save-excursion
3006 (insert-buffer-substring (get-buffer buffer))
3007 (point)))
3008 nil)
3010 (defun append-to-buffer (buffer start end)
3011 "Append to specified buffer the text of the region.
3012 It is inserted into that buffer before its point.
3014 When calling from a program, give three arguments:
3015 BUFFER (or buffer name), START and END.
3016 START and END specify the portion of the current buffer to be copied."
3017 (interactive
3018 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3019 (region-beginning) (region-end)))
3020 (let ((oldbuf (current-buffer)))
3021 (save-excursion
3022 (let* ((append-to (get-buffer-create buffer))
3023 (windows (get-buffer-window-list append-to t t))
3024 point)
3025 (set-buffer append-to)
3026 (setq point (point))
3027 (barf-if-buffer-read-only)
3028 (insert-buffer-substring oldbuf start end)
3029 (dolist (window windows)
3030 (when (= (window-point window) point)
3031 (set-window-point window (point))))))))
3033 (defun prepend-to-buffer (buffer start end)
3034 "Prepend to specified buffer the text of the region.
3035 It is inserted into that buffer after its point.
3037 When calling from a program, give three arguments:
3038 BUFFER (or buffer name), START and END.
3039 START and END specify the portion of the current buffer to be copied."
3040 (interactive "BPrepend to buffer: \nr")
3041 (let ((oldbuf (current-buffer)))
3042 (save-excursion
3043 (set-buffer (get-buffer-create buffer))
3044 (barf-if-buffer-read-only)
3045 (save-excursion
3046 (insert-buffer-substring oldbuf start end)))))
3048 (defun copy-to-buffer (buffer start end)
3049 "Copy to specified buffer the text of the region.
3050 It is inserted into that buffer, replacing existing text there.
3052 When calling from a program, give three arguments:
3053 BUFFER (or buffer name), START and END.
3054 START and END specify the portion of the current buffer to be copied."
3055 (interactive "BCopy to buffer: \nr")
3056 (let ((oldbuf (current-buffer)))
3057 (with-current-buffer (get-buffer-create buffer)
3058 (barf-if-buffer-read-only)
3059 (erase-buffer)
3060 (save-excursion
3061 (insert-buffer-substring oldbuf start end)))))
3063 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3064 (put 'mark-inactive 'error-message "The mark is not active now")
3066 (defvar activate-mark-hook nil
3067 "Hook run when the mark becomes active.
3068 It is also run at the end of a command, if the mark is active and
3069 it is possible that the region may have changed")
3071 (defvar deactivate-mark-hook nil
3072 "Hook run when the mark becomes inactive.")
3074 (defun mark (&optional force)
3075 "Return this buffer's mark value as integer, or nil if never set.
3077 In Transient Mark mode, this function signals an error if
3078 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3079 or the argument FORCE is non-nil, it disregards whether the mark
3080 is active, and returns an integer or nil in the usual way.
3082 If you are using this in an editing command, you are most likely making
3083 a mistake; see the documentation of `set-mark'."
3084 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3085 (marker-position (mark-marker))
3086 (signal 'mark-inactive nil)))
3088 ;; Many places set mark-active directly, and several of them failed to also
3089 ;; run deactivate-mark-hook. This shorthand should simplify.
3090 (defsubst deactivate-mark ()
3091 "Deactivate the mark by setting `mark-active' to nil.
3092 \(That makes a difference only in Transient Mark mode.)
3093 Also runs the hook `deactivate-mark-hook'."
3094 (cond
3095 ((eq transient-mark-mode 'lambda)
3096 (setq transient-mark-mode nil))
3097 (transient-mark-mode
3098 (setq mark-active nil)
3099 (run-hooks 'deactivate-mark-hook))))
3101 (defun set-mark (pos)
3102 "Set this buffer's mark to POS. Don't use this function!
3103 That is to say, don't use this function unless you want
3104 the user to see that the mark has moved, and you want the previous
3105 mark position to be lost.
3107 Normally, when a new mark is set, the old one should go on the stack.
3108 This is why most applications should use `push-mark', not `set-mark'.
3110 Novice Emacs Lisp programmers often try to use the mark for the wrong
3111 purposes. The mark saves a location for the user's convenience.
3112 Most editing commands should not alter the mark.
3113 To remember a location for internal use in the Lisp program,
3114 store it in a Lisp variable. Example:
3116 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3118 (if pos
3119 (progn
3120 (setq mark-active t)
3121 (run-hooks 'activate-mark-hook)
3122 (set-marker (mark-marker) pos (current-buffer)))
3123 ;; Normally we never clear mark-active except in Transient Mark mode.
3124 ;; But when we actually clear out the mark value too,
3125 ;; we must clear mark-active in any mode.
3126 (setq mark-active nil)
3127 (run-hooks 'deactivate-mark-hook)
3128 (set-marker (mark-marker) nil)))
3130 (defvar mark-ring nil
3131 "The list of former marks of the current buffer, most recent first.")
3132 (make-variable-buffer-local 'mark-ring)
3133 (put 'mark-ring 'permanent-local t)
3135 (defcustom mark-ring-max 16
3136 "*Maximum size of mark ring. Start discarding off end if gets this big."
3137 :type 'integer
3138 :group 'editing-basics)
3140 (defvar global-mark-ring nil
3141 "The list of saved global marks, most recent first.")
3143 (defcustom global-mark-ring-max 16
3144 "*Maximum size of global mark ring. \
3145 Start discarding off end if gets this big."
3146 :type 'integer
3147 :group 'editing-basics)
3149 (defun pop-to-mark-command ()
3150 "Jump to mark, and pop a new position for mark off the ring
3151 \(does not affect global mark ring\)."
3152 (interactive)
3153 (if (null (mark t))
3154 (error "No mark set in this buffer")
3155 (goto-char (mark t))
3156 (pop-mark)))
3158 (defun push-mark-command (arg &optional nomsg)
3159 "Set mark at where point is.
3160 If no prefix arg and mark is already set there, just activate it.
3161 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3162 (interactive "P")
3163 (let ((mark (marker-position (mark-marker))))
3164 (if (or arg (null mark) (/= mark (point)))
3165 (push-mark nil nomsg t)
3166 (setq mark-active t)
3167 (run-hooks 'activate-mark-hook)
3168 (unless nomsg
3169 (message "Mark activated")))))
3171 (defcustom set-mark-command-repeat-pop nil
3172 "*Non-nil means that repeating \\[set-mark-command] after popping will pop.
3173 This means that if you type C-u \\[set-mark-command] \\[set-mark-command]
3174 will pop twice."
3175 :type 'boolean
3176 :group 'editing)
3178 (defun set-mark-command (arg)
3179 "Set mark at where point is, or jump to mark.
3180 With no prefix argument, set mark, and push old mark position on local
3181 mark ring; also push mark on global mark ring if last mark was set in
3182 another buffer. Immediately repeating the command activates
3183 `transient-mark-mode' temporarily.
3185 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
3186 jump to mark, and pop a new position
3187 for mark off the local mark ring \(this does not affect the global
3188 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
3189 mark ring \(see `pop-global-mark'\).
3191 If `set-mark-command-repeat-pop' is non-nil, repeating
3192 the \\[set-mark-command] command with no prefix pops the next position
3193 off the local (or global) mark ring and jumps there.
3195 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
3196 \\[universal-argument] \\[set-mark-command], unconditionally
3197 set mark where point is.
3199 Novice Emacs Lisp programmers often try to use the mark for the wrong
3200 purposes. See the documentation of `set-mark' for more information."
3201 (interactive "P")
3202 (if (eq transient-mark-mode 'lambda)
3203 (setq transient-mark-mode nil))
3204 (cond
3205 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3206 (push-mark-command nil))
3207 ((not (eq this-command 'set-mark-command))
3208 (if arg
3209 (pop-to-mark-command)
3210 (push-mark-command t)))
3211 ((and set-mark-command-repeat-pop
3212 (eq last-command 'pop-to-mark-command))
3213 (setq this-command 'pop-to-mark-command)
3214 (pop-to-mark-command))
3215 ((and set-mark-command-repeat-pop
3216 (eq last-command 'pop-global-mark)
3217 (not arg))
3218 (setq this-command 'pop-global-mark)
3219 (pop-global-mark))
3220 (arg
3221 (setq this-command 'pop-to-mark-command)
3222 (pop-to-mark-command))
3223 ((and (eq last-command 'set-mark-command)
3224 mark-active (null transient-mark-mode))
3225 (setq transient-mark-mode 'lambda)
3226 (message "Transient-mark-mode temporarily enabled"))
3228 (push-mark-command nil))))
3230 (defun push-mark (&optional location nomsg activate)
3231 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3232 If the last global mark pushed was not in the current buffer,
3233 also push LOCATION on the global mark ring.
3234 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3235 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
3237 Novice Emacs Lisp programmers often try to use the mark for the wrong
3238 purposes. See the documentation of `set-mark' for more information.
3240 In Transient Mark mode, this does not activate the mark."
3241 (unless (null (mark t))
3242 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3243 (when (> (length mark-ring) mark-ring-max)
3244 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3245 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3246 (set-marker (mark-marker) (or location (point)) (current-buffer))
3247 ;; Now push the mark on the global mark ring.
3248 (if (and global-mark-ring
3249 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3250 ;; The last global mark pushed was in this same buffer.
3251 ;; Don't push another one.
3253 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3254 (when (> (length global-mark-ring) global-mark-ring-max)
3255 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3256 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3257 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3258 (message "Mark set"))
3259 (if (or activate (not transient-mark-mode))
3260 (set-mark (mark t)))
3261 nil)
3263 (defun pop-mark ()
3264 "Pop off mark ring into the buffer's actual mark.
3265 Does not set point. Does nothing if mark ring is empty."
3266 (when mark-ring
3267 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3268 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3269 (move-marker (car mark-ring) nil)
3270 (if (null (mark t)) (ding))
3271 (setq mark-ring (cdr mark-ring)))
3272 (deactivate-mark))
3274 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3275 (defun exchange-point-and-mark (&optional arg)
3276 "Put the mark where point is now, and point where the mark is now.
3277 This command works even when the mark is not active,
3278 and it reactivates the mark.
3279 With prefix arg, `transient-mark-mode' is enabled temporarily."
3280 (interactive "P")
3281 (if arg
3282 (if mark-active
3283 (if (null transient-mark-mode)
3284 (setq transient-mark-mode 'lambda))
3285 (setq arg nil)))
3286 (unless arg
3287 (let ((omark (mark t)))
3288 (if (null omark)
3289 (error "No mark set in this buffer"))
3290 (set-mark (point))
3291 (goto-char omark)
3292 nil)))
3294 (define-minor-mode transient-mark-mode
3295 "Toggle Transient Mark mode.
3296 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
3298 In Transient Mark mode, when the mark is active, the region is highlighted.
3299 Changing the buffer \"deactivates\" the mark.
3300 So do certain other operations that set the mark
3301 but whose main purpose is something else--for example,
3302 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3304 You can also deactivate the mark by typing \\[keyboard-quit] or
3305 \\[keyboard-escape-quit].
3307 Many commands change their behavior when Transient Mark mode is in effect
3308 and the mark is active, by acting on the region instead of their usual
3309 default part of the buffer's text. Examples of such commands include
3310 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3311 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3312 Invoke \\[apropos-documentation] and type \"transient\" or
3313 \"mark.*active\" at the prompt, to see the documentation of
3314 commands which are sensitive to the Transient Mark mode."
3315 :global t :group 'editing-basics)
3317 (defvar widen-automatically t
3318 "Non-nil means it is ok for commands to call `widen' when they want to.
3319 Some commands will do this in order to go to positions outside
3320 the current accessible part of the buffer.
3322 If `widen-automatically' is nil, these commands will do something else
3323 as a fallback, and won't change the buffer bounds.")
3325 (defun pop-global-mark ()
3326 "Pop off global mark ring and jump to the top location."
3327 (interactive)
3328 ;; Pop entries which refer to non-existent buffers.
3329 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3330 (setq global-mark-ring (cdr global-mark-ring)))
3331 (or global-mark-ring
3332 (error "No global mark set"))
3333 (let* ((marker (car global-mark-ring))
3334 (buffer (marker-buffer marker))
3335 (position (marker-position marker)))
3336 (setq global-mark-ring (nconc (cdr global-mark-ring)
3337 (list (car global-mark-ring))))
3338 (set-buffer buffer)
3339 (or (and (>= position (point-min))
3340 (<= position (point-max)))
3341 (if widen-automatically
3342 (widen)
3343 (error "Global mark position is outside accessible part of buffer")))
3344 (goto-char position)
3345 (switch-to-buffer buffer)))
3347 (defcustom next-line-add-newlines nil
3348 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3349 :type 'boolean
3350 :version "21.1"
3351 :group 'editing-basics)
3353 (defun next-line (&optional arg try-vscroll)
3354 "Move cursor vertically down ARG lines.
3355 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3356 If there is no character in the target line exactly under the current column,
3357 the cursor is positioned after the character in that line which spans this
3358 column, or at the end of the line if it is not long enough.
3359 If there is no line in the buffer after this one, behavior depends on the
3360 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3361 to create a line, and moves the cursor to that line. Otherwise it moves the
3362 cursor to the end of the buffer.
3364 The command \\[set-goal-column] can be used to create
3365 a semipermanent goal column for this command.
3366 Then instead of trying to move exactly vertically (or as close as possible),
3367 this command moves to the specified goal column (or as close as possible).
3368 The goal column is stored in the variable `goal-column', which is nil
3369 when there is no goal column.
3371 If you are thinking of using this in a Lisp program, consider
3372 using `forward-line' instead. It is usually easier to use
3373 and more reliable (no dependence on goal column, etc.)."
3374 (interactive "p\np")
3375 (or arg (setq arg 1))
3376 (if (and next-line-add-newlines (= arg 1))
3377 (if (save-excursion (end-of-line) (eobp))
3378 ;; When adding a newline, don't expand an abbrev.
3379 (let ((abbrev-mode nil))
3380 (end-of-line)
3381 (insert (if use-hard-newlines hard-newline "\n")))
3382 (line-move arg nil nil try-vscroll))
3383 (if (interactive-p)
3384 (condition-case nil
3385 (line-move arg nil nil try-vscroll)
3386 ((beginning-of-buffer end-of-buffer) (ding)))
3387 (line-move arg nil nil try-vscroll)))
3388 nil)
3390 (defun previous-line (&optional arg try-vscroll)
3391 "Move cursor vertically up ARG lines.
3392 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3393 If there is no character in the target line exactly over the current column,
3394 the cursor is positioned after the character in that line which spans this
3395 column, or at the end of the line if it is not long enough.
3397 The command \\[set-goal-column] can be used to create
3398 a semipermanent goal column for this command.
3399 Then instead of trying to move exactly vertically (or as close as possible),
3400 this command moves to the specified goal column (or as close as possible).
3401 The goal column is stored in the variable `goal-column', which is nil
3402 when there is no goal column.
3404 If you are thinking of using this in a Lisp program, consider using
3405 `forward-line' with a negative argument instead. It is usually easier
3406 to use and more reliable (no dependence on goal column, etc.)."
3407 (interactive "p\np")
3408 (or arg (setq arg 1))
3409 (if (interactive-p)
3410 (condition-case nil
3411 (line-move (- arg) nil nil try-vscroll)
3412 ((beginning-of-buffer end-of-buffer) (ding)))
3413 (line-move (- arg) nil nil try-vscroll))
3414 nil)
3416 (defcustom track-eol nil
3417 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
3418 This means moving to the end of each line moved onto.
3419 The beginning of a blank line does not count as the end of a line."
3420 :type 'boolean
3421 :group 'editing-basics)
3423 (defcustom goal-column nil
3424 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3425 :type '(choice integer
3426 (const :tag "None" nil))
3427 :group 'editing-basics)
3428 (make-variable-buffer-local 'goal-column)
3430 (defvar temporary-goal-column 0
3431 "Current goal column for vertical motion.
3432 It is the column where point was
3433 at the start of current run of vertical motion commands.
3434 When the `track-eol' feature is doing its job, the value is 9999.")
3436 (defcustom line-move-ignore-invisible t
3437 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3438 Outline mode sets this."
3439 :type 'boolean
3440 :group 'editing-basics)
3442 (defun line-move-invisible-p (pos)
3443 "Return non-nil if the character after POS is currently invisible."
3444 (let ((prop
3445 (get-char-property pos 'invisible)))
3446 (if (eq buffer-invisibility-spec t)
3447 prop
3448 (or (memq prop buffer-invisibility-spec)
3449 (assq prop buffer-invisibility-spec)))))
3451 ;; This is like line-move-1 except that it also performs
3452 ;; vertical scrolling of tall images if appropriate.
3453 ;; That is not really a clean thing to do, since it mixes
3454 ;; scrolling with cursor motion. But so far we don't have
3455 ;; a cleaner solution to the problem of making C-n do something
3456 ;; useful given a tall image.
3457 (defun line-move (arg &optional noerror to-end try-vscroll)
3458 (if (and auto-window-vscroll try-vscroll
3459 ;; But don't vscroll in a keyboard macro.
3460 (not defining-kbd-macro)
3461 (not executing-kbd-macro))
3462 (let ((forward (> arg 0))
3463 (part (nth 2 (pos-visible-in-window-p (point) nil t))))
3464 (if (and (consp part)
3465 (> (if forward (cdr part) (car part)) 0))
3466 (set-window-vscroll nil
3467 (if forward
3468 (+ (window-vscroll nil t)
3469 (min (cdr part)
3470 (* (frame-char-height) arg)))
3471 (max 0
3472 (- (window-vscroll nil t)
3473 (min (car part)
3474 (* (frame-char-height) (- arg))))))
3476 (set-window-vscroll nil 0)
3477 (when (line-move-1 arg noerror to-end)
3478 (when (not forward)
3479 ;; Update display before calling pos-visible-in-window-p,
3480 ;; because it depends on window-start being up-to-date.
3481 (sit-for 0)
3482 ;; If the current line is partly hidden at the bottom,
3483 ;; scroll it partially up so as to unhide the bottom.
3484 (if (and (setq part (nth 2 (pos-visible-in-window-p
3485 (line-beginning-position) nil t)))
3486 (> (cdr part) 0))
3487 (set-window-vscroll nil (cdr part) t)))
3488 t)))
3489 (line-move-1 arg noerror to-end)))
3491 ;; This is the guts of next-line and previous-line.
3492 ;; Arg says how many lines to move.
3493 ;; The value is t if we can move the specified number of lines.
3494 (defun line-move-1 (arg &optional noerror to-end)
3495 ;; Don't run any point-motion hooks, and disregard intangibility,
3496 ;; for intermediate positions.
3497 (let ((inhibit-point-motion-hooks t)
3498 (opoint (point))
3499 (forward (> arg 0)))
3500 (unwind-protect
3501 (progn
3502 (if (not (memq last-command '(next-line previous-line)))
3503 (setq temporary-goal-column
3504 (if (and track-eol (eolp)
3505 ;; Don't count beg of empty line as end of line
3506 ;; unless we just did explicit end-of-line.
3507 (or (not (bolp)) (eq last-command 'end-of-line)))
3508 9999
3509 (current-column))))
3511 (if (and (not (integerp selective-display))
3512 (not line-move-ignore-invisible))
3513 ;; Use just newline characters.
3514 ;; Set ARG to 0 if we move as many lines as requested.
3515 (or (if (> arg 0)
3516 (progn (if (> arg 1) (forward-line (1- arg)))
3517 ;; This way of moving forward ARG lines
3518 ;; verifies that we have a newline after the last one.
3519 ;; It doesn't get confused by intangible text.
3520 (end-of-line)
3521 (if (zerop (forward-line 1))
3522 (setq arg 0)))
3523 (and (zerop (forward-line arg))
3524 (bolp)
3525 (setq arg 0)))
3526 (unless noerror
3527 (signal (if (< arg 0)
3528 'beginning-of-buffer
3529 'end-of-buffer)
3530 nil)))
3531 ;; Move by arg lines, but ignore invisible ones.
3532 (let (done)
3533 (while (and (> arg 0) (not done))
3534 ;; If the following character is currently invisible,
3535 ;; skip all characters with that same `invisible' property value.
3536 (while (and (not (eobp)) (line-move-invisible-p (point)))
3537 (goto-char (next-char-property-change (point))))
3538 ;; Now move a line.
3539 (end-of-line)
3540 ;; If there's no invisibility here, move over the newline.
3541 (cond
3542 ((eobp)
3543 (if (not noerror)
3544 (signal 'end-of-buffer nil)
3545 (setq done t)))
3546 ((and (> arg 1) ;; Use vertical-motion for last move
3547 (not (integerp selective-display))
3548 (not (line-move-invisible-p (point))))
3549 ;; We avoid vertical-motion when possible
3550 ;; because that has to fontify.
3551 (forward-line 1))
3552 ;; Otherwise move a more sophisticated way.
3553 ((zerop (vertical-motion 1))
3554 (if (not noerror)
3555 (signal 'end-of-buffer nil)
3556 (setq done t))))
3557 (unless done
3558 (setq arg (1- arg))))
3559 ;; The logic of this is the same as the loop above,
3560 ;; it just goes in the other direction.
3561 (while (and (< arg 0) (not done))
3562 (beginning-of-line)
3563 (cond
3564 ((bobp)
3565 (if (not noerror)
3566 (signal 'beginning-of-buffer nil)
3567 (setq done t)))
3568 ((and (< arg -1) ;; Use vertical-motion for last move
3569 (not (integerp selective-display))
3570 (not (line-move-invisible-p (1- (point)))))
3571 (forward-line -1))
3572 ((zerop (vertical-motion -1))
3573 (if (not noerror)
3574 (signal 'beginning-of-buffer nil)
3575 (setq done t))))
3576 (unless done
3577 (setq arg (1+ arg))
3578 (while (and ;; Don't move over previous invis lines
3579 ;; if our target is the middle of this line.
3580 (or (zerop (or goal-column temporary-goal-column))
3581 (< arg 0))
3582 (not (bobp)) (line-move-invisible-p (1- (point))))
3583 (goto-char (previous-char-property-change (point))))))))
3584 ;; This is the value the function returns.
3585 (= arg 0))
3587 (cond ((> arg 0)
3588 ;; If we did not move down as far as desired,
3589 ;; at least go to end of line.
3590 (end-of-line))
3591 ((< arg 0)
3592 ;; If we did not move up as far as desired,
3593 ;; at least go to beginning of line.
3594 (beginning-of-line))
3596 (line-move-finish (or goal-column temporary-goal-column)
3597 opoint forward))))))
3599 (defun line-move-finish (column opoint forward)
3600 (let ((repeat t))
3601 (while repeat
3602 ;; Set REPEAT to t to repeat the whole thing.
3603 (setq repeat nil)
3605 (let (new
3606 (line-beg (save-excursion (beginning-of-line) (point)))
3607 (line-end
3608 ;; Compute the end of the line
3609 ;; ignoring effectively invisible newlines.
3610 (save-excursion
3611 ;; Like end-of-line but ignores fields.
3612 (skip-chars-forward "^\n")
3613 (while (and (not (eobp)) (line-move-invisible-p (point)))
3614 (goto-char (next-char-property-change (point)))
3615 (skip-chars-forward "^\n"))
3616 (point))))
3618 ;; Move to the desired column.
3619 (line-move-to-column column)
3620 (setq new (point))
3622 ;; Process intangibility within a line.
3623 ;; Move to the chosen destination position from above,
3624 ;; with intangibility processing enabled.
3626 (goto-char (point-min))
3627 (let ((inhibit-point-motion-hooks nil))
3628 (goto-char new)
3630 ;; If intangibility moves us to a different (later) place
3631 ;; in the same line, use that as the destination.
3632 (if (<= (point) line-end)
3633 (setq new (point))
3634 ;; If that position is "too late",
3635 ;; try the previous allowable position.
3636 ;; See if it is ok.
3637 (backward-char)
3638 (if (if forward
3639 ;; If going forward, don't accept the previous
3640 ;; allowable position if it is before the target line.
3641 (< line-beg (point))
3642 ;; If going backward, don't accept the previous
3643 ;; allowable position if it is still after the target line.
3644 (<= (point) line-end))
3645 (setq new (point))
3646 ;; As a last resort, use the end of the line.
3647 (setq new line-end))))
3649 ;; Now move to the updated destination, processing fields
3650 ;; as well as intangibility.
3651 (goto-char opoint)
3652 (let ((inhibit-point-motion-hooks nil))
3653 (goto-char
3654 (constrain-to-field new opoint nil t
3655 'inhibit-line-move-field-capture)))
3657 ;; If all this moved us to a different line,
3658 ;; retry everything within that new line.
3659 (when (or (< (point) line-beg) (> (point) line-end))
3660 ;; Repeat the intangibility and field processing.
3661 (setq repeat t))))))
3663 (defun line-move-to-column (col)
3664 "Try to find column COL, considering invisibility.
3665 This function works only in certain cases,
3666 because what we really need is for `move-to-column'
3667 and `current-column' to be able to ignore invisible text."
3668 (if (zerop col)
3669 (beginning-of-line)
3670 (move-to-column col))
3672 (when (and line-move-ignore-invisible
3673 (not (bolp)) (line-move-invisible-p (1- (point))))
3674 (let ((normal-location (point))
3675 (normal-column (current-column)))
3676 ;; If the following character is currently invisible,
3677 ;; skip all characters with that same `invisible' property value.
3678 (while (and (not (eobp))
3679 (line-move-invisible-p (point)))
3680 (goto-char (next-char-property-change (point))))
3681 ;; Have we advanced to a larger column position?
3682 (if (> (current-column) normal-column)
3683 ;; We have made some progress towards the desired column.
3684 ;; See if we can make any further progress.
3685 (line-move-to-column (+ (current-column) (- col normal-column)))
3686 ;; Otherwise, go to the place we originally found
3687 ;; and move back over invisible text.
3688 ;; that will get us to the same place on the screen
3689 ;; but with a more reasonable buffer position.
3690 (goto-char normal-location)
3691 (let ((line-beg (save-excursion (beginning-of-line) (point))))
3692 (while (and (not (bolp)) (line-move-invisible-p (1- (point))))
3693 (goto-char (previous-char-property-change (point) line-beg))))))))
3695 (defun move-end-of-line (arg)
3696 "Move point to end of current line as displayed.
3697 \(If there's an image in the line, this disregards newlines
3698 which are part of the text that the image rests on.)
3700 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3701 If point reaches the beginning or end of buffer, it stops there.
3702 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
3703 (interactive "p")
3704 (or arg (setq arg 1))
3705 (let (done)
3706 (while (not done)
3707 (let ((newpos
3708 (save-excursion
3709 (let ((goal-column 0))
3710 (and (line-move arg t)
3711 (not (bobp))
3712 (progn
3713 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3714 (goto-char (previous-char-property-change (point))))
3715 (backward-char 1)))
3716 (point)))))
3717 (goto-char newpos)
3718 (if (and (> (point) newpos)
3719 (eq (preceding-char) ?\n))
3720 (backward-char 1)
3721 (if (and (> (point) newpos) (not (eobp))
3722 (not (eq (following-char) ?\n)))
3723 ;; If we skipped something intangible
3724 ;; and now we're not really at eol,
3725 ;; keep going.
3726 (setq arg 1)
3727 (setq done t)))))))
3729 (defun move-beginning-of-line (arg)
3730 "Move point to beginning of current line as displayed.
3731 \(If there's an image in the line, this disregards newlines
3732 which are part of the text that the image rests on.)
3734 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3735 If point reaches the beginning or end of buffer, it stops there.
3736 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
3737 (interactive "p")
3738 (or arg (setq arg 1))
3740 (let ((orig (point)))
3742 ;; Move by lines, if ARG is not 1 (the default).
3743 (if (/= arg 1)
3744 (line-move (1- arg) t))
3746 ;; Move to beginning-of-line, ignoring fields and invisibles.
3747 (skip-chars-backward "^\n")
3748 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3749 (goto-char (previous-char-property-change (point)))
3750 (skip-chars-backward "^\n"))
3752 ;; Take care of fields.
3753 (goto-char (constrain-to-field (point) orig
3754 (/= arg 1) t nil))))
3757 ;;; Many people have said they rarely use this feature, and often type
3758 ;;; it by accident. Maybe it shouldn't even be on a key.
3759 (put 'set-goal-column 'disabled t)
3761 (defun set-goal-column (arg)
3762 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3763 Those commands will move to this position in the line moved to
3764 rather than trying to keep the same horizontal position.
3765 With a non-nil argument, clears out the goal column
3766 so that \\[next-line] and \\[previous-line] resume vertical motion.
3767 The goal column is stored in the variable `goal-column'."
3768 (interactive "P")
3769 (if arg
3770 (progn
3771 (setq goal-column nil)
3772 (message "No goal column"))
3773 (setq goal-column (current-column))
3774 ;; The older method below can be erroneous if `set-goal-column' is bound
3775 ;; to a sequence containing %
3776 ;;(message (substitute-command-keys
3777 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3778 ;;goal-column)
3779 (message "%s"
3780 (concat
3781 (format "Goal column %d " goal-column)
3782 (substitute-command-keys
3783 "(use \\[set-goal-column] with an arg to unset it)")))
3786 nil)
3789 (defun scroll-other-window-down (lines)
3790 "Scroll the \"other window\" down.
3791 For more details, see the documentation for `scroll-other-window'."
3792 (interactive "P")
3793 (scroll-other-window
3794 ;; Just invert the argument's meaning.
3795 ;; We can do that without knowing which window it will be.
3796 (if (eq lines '-) nil
3797 (if (null lines) '-
3798 (- (prefix-numeric-value lines))))))
3800 (defun beginning-of-buffer-other-window (arg)
3801 "Move point to the beginning of the buffer in the other window.
3802 Leave mark at previous position.
3803 With arg N, put point N/10 of the way from the true beginning."
3804 (interactive "P")
3805 (let ((orig-window (selected-window))
3806 (window (other-window-for-scrolling)))
3807 ;; We use unwind-protect rather than save-window-excursion
3808 ;; because the latter would preserve the things we want to change.
3809 (unwind-protect
3810 (progn
3811 (select-window window)
3812 ;; Set point and mark in that window's buffer.
3813 (with-no-warnings
3814 (beginning-of-buffer arg))
3815 ;; Set point accordingly.
3816 (recenter '(t)))
3817 (select-window orig-window))))
3819 (defun end-of-buffer-other-window (arg)
3820 "Move point to the end of the buffer in the other window.
3821 Leave mark at previous position.
3822 With arg N, put point N/10 of the way from the true end."
3823 (interactive "P")
3824 ;; See beginning-of-buffer-other-window for comments.
3825 (let ((orig-window (selected-window))
3826 (window (other-window-for-scrolling)))
3827 (unwind-protect
3828 (progn
3829 (select-window window)
3830 (with-no-warnings
3831 (end-of-buffer arg))
3832 (recenter '(t)))
3833 (select-window orig-window))))
3835 (defun transpose-chars (arg)
3836 "Interchange characters around point, moving forward one character.
3837 With prefix arg ARG, effect is to take character before point
3838 and drag it forward past ARG other characters (backward if ARG negative).
3839 If no argument and at end of line, the previous two chars are exchanged."
3840 (interactive "*P")
3841 (and (null arg) (eolp) (forward-char -1))
3842 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3844 (defun transpose-words (arg)
3845 "Interchange words around point, leaving point at end of them.
3846 With prefix arg ARG, effect is to take word before or around point
3847 and drag it forward past ARG other words (backward if ARG negative).
3848 If ARG is zero, the words around or after point and around or after mark
3849 are interchanged."
3850 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3851 (interactive "*p")
3852 (transpose-subr 'forward-word arg))
3854 (defun transpose-sexps (arg)
3855 "Like \\[transpose-words] but applies to sexps.
3856 Does not work on a sexp that point is in the middle of
3857 if it is a list or string."
3858 (interactive "*p")
3859 (transpose-subr
3860 (lambda (arg)
3861 ;; Here we should try to simulate the behavior of
3862 ;; (cons (progn (forward-sexp x) (point))
3863 ;; (progn (forward-sexp (- x)) (point)))
3864 ;; Except that we don't want to rely on the second forward-sexp
3865 ;; putting us back to where we want to be, since forward-sexp-function
3866 ;; might do funny things like infix-precedence.
3867 (if (if (> arg 0)
3868 (looking-at "\\sw\\|\\s_")
3869 (and (not (bobp))
3870 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3871 ;; Jumping over a symbol. We might be inside it, mind you.
3872 (progn (funcall (if (> arg 0)
3873 'skip-syntax-backward 'skip-syntax-forward)
3874 "w_")
3875 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3876 ;; Otherwise, we're between sexps. Take a step back before jumping
3877 ;; to make sure we'll obey the same precedence no matter which direction
3878 ;; we're going.
3879 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3880 (cons (save-excursion (forward-sexp arg) (point))
3881 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3882 (not (zerop (funcall (if (> arg 0)
3883 'skip-syntax-forward
3884 'skip-syntax-backward)
3885 ".")))))
3886 (point)))))
3887 arg 'special))
3889 (defun transpose-lines (arg)
3890 "Exchange current line and previous line, leaving point after both.
3891 With argument ARG, takes previous line and moves it past ARG lines.
3892 With argument 0, interchanges line point is in with line mark is in."
3893 (interactive "*p")
3894 (transpose-subr (function
3895 (lambda (arg)
3896 (if (> arg 0)
3897 (progn
3898 ;; Move forward over ARG lines,
3899 ;; but create newlines if necessary.
3900 (setq arg (forward-line arg))
3901 (if (/= (preceding-char) ?\n)
3902 (setq arg (1+ arg)))
3903 (if (> arg 0)
3904 (newline arg)))
3905 (forward-line arg))))
3906 arg))
3908 (defun transpose-subr (mover arg &optional special)
3909 (let ((aux (if special mover
3910 (lambda (x)
3911 (cons (progn (funcall mover x) (point))
3912 (progn (funcall mover (- x)) (point))))))
3913 pos1 pos2)
3914 (cond
3915 ((= arg 0)
3916 (save-excursion
3917 (setq pos1 (funcall aux 1))
3918 (goto-char (mark))
3919 (setq pos2 (funcall aux 1))
3920 (transpose-subr-1 pos1 pos2))
3921 (exchange-point-and-mark))
3922 ((> arg 0)
3923 (setq pos1 (funcall aux -1))
3924 (setq pos2 (funcall aux arg))
3925 (transpose-subr-1 pos1 pos2)
3926 (goto-char (car pos2)))
3928 (setq pos1 (funcall aux -1))
3929 (goto-char (car pos1))
3930 (setq pos2 (funcall aux arg))
3931 (transpose-subr-1 pos1 pos2)))))
3933 (defun transpose-subr-1 (pos1 pos2)
3934 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3935 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3936 (when (> (car pos1) (car pos2))
3937 (let ((swap pos1))
3938 (setq pos1 pos2 pos2 swap)))
3939 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3940 (atomic-change-group
3941 (let (word2)
3942 ;; FIXME: We first delete the two pieces of text, so markers that
3943 ;; used to point to after the text end up pointing to before it :-(
3944 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3945 (goto-char (car pos2))
3946 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3947 (goto-char (car pos1))
3948 (insert word2))))
3950 (defun backward-word (&optional arg)
3951 "Move backward until encountering the beginning of a word.
3952 With argument, do this that many times."
3953 (interactive "p")
3954 (forward-word (- (or arg 1))))
3956 (defun mark-word (&optional arg allow-extend)
3957 "Set mark ARG words away from point.
3958 The place mark goes is the same place \\[forward-word] would
3959 move to with the same argument.
3960 Interactively, if this command is repeated
3961 or (in Transient Mark mode) if the mark is active,
3962 it marks the next ARG words after the ones already marked."
3963 (interactive "P\np")
3964 (cond ((and allow-extend
3965 (or (and (eq last-command this-command) (mark t))
3966 (and transient-mark-mode mark-active)))
3967 (setq arg (if arg (prefix-numeric-value arg)
3968 (if (< (mark) (point)) -1 1)))
3969 (set-mark
3970 (save-excursion
3971 (goto-char (mark))
3972 (forward-word arg)
3973 (point))))
3975 (push-mark
3976 (save-excursion
3977 (forward-word (prefix-numeric-value arg))
3978 (point))
3979 nil t))))
3981 (defun kill-word (arg)
3982 "Kill characters forward until encountering the end of a word.
3983 With argument, do this that many times."
3984 (interactive "p")
3985 (kill-region (point) (progn (forward-word arg) (point))))
3987 (defun backward-kill-word (arg)
3988 "Kill characters backward until encountering the end of a word.
3989 With argument, do this that many times."
3990 (interactive "p")
3991 (kill-word (- arg)))
3993 (defun current-word (&optional strict really-word)
3994 "Return the symbol or word that point is on (or a nearby one) as a string.
3995 The return value includes no text properties.
3996 If optional arg STRICT is non-nil, return nil unless point is within
3997 or adjacent to a symbol or word. In all cases the value can be nil
3998 if there is no word nearby.
3999 The function, belying its name, normally finds a symbol.
4000 If optional arg REALLY-WORD is non-nil, it finds just a word."
4001 (save-excursion
4002 (let* ((oldpoint (point)) (start (point)) (end (point))
4003 (syntaxes (if really-word "w" "w_"))
4004 (not-syntaxes (concat "^" syntaxes)))
4005 (skip-syntax-backward syntaxes) (setq start (point))
4006 (goto-char oldpoint)
4007 (skip-syntax-forward syntaxes) (setq end (point))
4008 (when (and (eq start oldpoint) (eq end oldpoint)
4009 ;; Point is neither within nor adjacent to a word.
4010 (not strict))
4011 ;; Look for preceding word in same line.
4012 (skip-syntax-backward not-syntaxes
4013 (save-excursion (beginning-of-line)
4014 (point)))
4015 (if (bolp)
4016 ;; No preceding word in same line.
4017 ;; Look for following word in same line.
4018 (progn
4019 (skip-syntax-forward not-syntaxes
4020 (save-excursion (end-of-line)
4021 (point)))
4022 (setq start (point))
4023 (skip-syntax-forward syntaxes)
4024 (setq end (point)))
4025 (setq end (point))
4026 (skip-syntax-backward syntaxes)
4027 (setq start (point))))
4028 ;; If we found something nonempty, return it as a string.
4029 (unless (= start end)
4030 (buffer-substring-no-properties start end)))))
4032 (defcustom fill-prefix nil
4033 "*String for filling to insert at front of new line, or nil for none."
4034 :type '(choice (const :tag "None" nil)
4035 string)
4036 :group 'fill)
4037 (make-variable-buffer-local 'fill-prefix)
4039 (defcustom auto-fill-inhibit-regexp nil
4040 "*Regexp to match lines which should not be auto-filled."
4041 :type '(choice (const :tag "None" nil)
4042 regexp)
4043 :group 'fill)
4045 (defvar comment-line-break-function 'comment-indent-new-line
4046 "*Mode-specific function which line breaks and continues a comment.
4048 This function is only called during auto-filling of a comment section.
4049 The function should take a single optional argument, which is a flag
4050 indicating whether it should use soft newlines.")
4052 ;; This function is used as the auto-fill-function of a buffer
4053 ;; when Auto-Fill mode is enabled.
4054 ;; It returns t if it really did any work.
4055 ;; (Actually some major modes use a different auto-fill function,
4056 ;; but this one is the default one.)
4057 (defun do-auto-fill ()
4058 (let (fc justify give-up
4059 (fill-prefix fill-prefix))
4060 (if (or (not (setq justify (current-justification)))
4061 (null (setq fc (current-fill-column)))
4062 (and (eq justify 'left)
4063 (<= (current-column) fc))
4064 (and auto-fill-inhibit-regexp
4065 (save-excursion (beginning-of-line)
4066 (looking-at auto-fill-inhibit-regexp))))
4067 nil ;; Auto-filling not required
4068 (if (memq justify '(full center right))
4069 (save-excursion (unjustify-current-line)))
4071 ;; Choose a fill-prefix automatically.
4072 (when (and adaptive-fill-mode
4073 (or (null fill-prefix) (string= fill-prefix "")))
4074 (let ((prefix
4075 (fill-context-prefix
4076 (save-excursion (backward-paragraph 1) (point))
4077 (save-excursion (forward-paragraph 1) (point)))))
4078 (and prefix (not (equal prefix ""))
4079 ;; Use auto-indentation rather than a guessed empty prefix.
4080 (not (and fill-indent-according-to-mode
4081 (string-match "\\`[ \t]*\\'" prefix)))
4082 (setq fill-prefix prefix))))
4084 (while (and (not give-up) (> (current-column) fc))
4085 ;; Determine where to split the line.
4086 (let* (after-prefix
4087 (fill-point
4088 (save-excursion
4089 (beginning-of-line)
4090 (setq after-prefix (point))
4091 (and fill-prefix
4092 (looking-at (regexp-quote fill-prefix))
4093 (setq after-prefix (match-end 0)))
4094 (move-to-column (1+ fc))
4095 (fill-move-to-break-point after-prefix)
4096 (point))))
4098 ;; See whether the place we found is any good.
4099 (if (save-excursion
4100 (goto-char fill-point)
4101 (or (bolp)
4102 ;; There is no use breaking at end of line.
4103 (save-excursion (skip-chars-forward " ") (eolp))
4104 ;; It is futile to split at the end of the prefix
4105 ;; since we would just insert the prefix again.
4106 (and after-prefix (<= (point) after-prefix))
4107 ;; Don't split right after a comment starter
4108 ;; since we would just make another comment starter.
4109 (and comment-start-skip
4110 (let ((limit (point)))
4111 (beginning-of-line)
4112 (and (re-search-forward comment-start-skip
4113 limit t)
4114 (eq (point) limit))))))
4115 ;; No good place to break => stop trying.
4116 (setq give-up t)
4117 ;; Ok, we have a useful place to break the line. Do it.
4118 (let ((prev-column (current-column)))
4119 ;; If point is at the fill-point, do not `save-excursion'.
4120 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4121 ;; point will end up before it rather than after it.
4122 (if (save-excursion
4123 (skip-chars-backward " \t")
4124 (= (point) fill-point))
4125 (funcall comment-line-break-function t)
4126 (save-excursion
4127 (goto-char fill-point)
4128 (funcall comment-line-break-function t)))
4129 ;; Now do justification, if required
4130 (if (not (eq justify 'left))
4131 (save-excursion
4132 (end-of-line 0)
4133 (justify-current-line justify nil t)))
4134 ;; If making the new line didn't reduce the hpos of
4135 ;; the end of the line, then give up now;
4136 ;; trying again will not help.
4137 (if (>= (current-column) prev-column)
4138 (setq give-up t))))))
4139 ;; Justify last line.
4140 (justify-current-line justify t t)
4141 t)))
4143 (defvar normal-auto-fill-function 'do-auto-fill
4144 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4145 Some major modes set this.")
4147 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
4148 ;; FIXME: turn into a proper minor mode.
4149 ;; Add a global minor mode version of it.
4150 (defun auto-fill-mode (&optional arg)
4151 "Toggle Auto Fill mode.
4152 With arg, turn Auto Fill mode on if and only if arg is positive.
4153 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4154 automatically breaks the line at a previous space.
4156 The value of `normal-auto-fill-function' specifies the function to use
4157 for `auto-fill-function' when turning Auto Fill mode on."
4158 (interactive "P")
4159 (prog1 (setq auto-fill-function
4160 (if (if (null arg)
4161 (not auto-fill-function)
4162 (> (prefix-numeric-value arg) 0))
4163 normal-auto-fill-function
4164 nil))
4165 (force-mode-line-update)))
4167 ;; This holds a document string used to document auto-fill-mode.
4168 (defun auto-fill-function ()
4169 "Automatically break line at a previous space, in insertion of text."
4170 nil)
4172 (defun turn-on-auto-fill ()
4173 "Unconditionally turn on Auto Fill mode."
4174 (auto-fill-mode 1))
4176 (defun turn-off-auto-fill ()
4177 "Unconditionally turn off Auto Fill mode."
4178 (auto-fill-mode -1))
4180 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
4182 (defun set-fill-column (arg)
4183 "Set `fill-column' to specified argument.
4184 Use \\[universal-argument] followed by a number to specify a column.
4185 Just \\[universal-argument] as argument means to use the current column."
4186 (interactive "P")
4187 (if (consp arg)
4188 (setq arg (current-column)))
4189 (if (not (integerp arg))
4190 ;; Disallow missing argument; it's probably a typo for C-x C-f.
4191 (error "set-fill-column requires an explicit argument")
4192 (message "Fill column set to %d (was %d)" arg fill-column)
4193 (setq fill-column arg)))
4195 (defun set-selective-display (arg)
4196 "Set `selective-display' to ARG; clear it if no arg.
4197 When the value of `selective-display' is a number > 0,
4198 lines whose indentation is >= that value are not displayed.
4199 The variable `selective-display' has a separate value for each buffer."
4200 (interactive "P")
4201 (if (eq selective-display t)
4202 (error "selective-display already in use for marked lines"))
4203 (let ((current-vpos
4204 (save-restriction
4205 (narrow-to-region (point-min) (point))
4206 (goto-char (window-start))
4207 (vertical-motion (window-height)))))
4208 (setq selective-display
4209 (and arg (prefix-numeric-value arg)))
4210 (recenter current-vpos))
4211 (set-window-start (selected-window) (window-start (selected-window)))
4212 (princ "selective-display set to " t)
4213 (prin1 selective-display t)
4214 (princ "." t))
4216 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
4217 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
4219 (defun toggle-truncate-lines (arg)
4220 "Toggle whether to fold or truncate long lines on the screen.
4221 With arg, truncate long lines iff arg is positive.
4222 Note that in side-by-side windows, truncation is always enabled."
4223 (interactive "P")
4224 (setq truncate-lines
4225 (if (null arg)
4226 (not truncate-lines)
4227 (> (prefix-numeric-value arg) 0)))
4228 (force-mode-line-update)
4229 (unless truncate-lines
4230 (let ((buffer (current-buffer)))
4231 (walk-windows (lambda (window)
4232 (if (eq buffer (window-buffer window))
4233 (set-window-hscroll window 0)))
4234 nil t)))
4235 (message "Truncate long lines %s"
4236 (if truncate-lines "enabled" "disabled")))
4238 (defvar overwrite-mode-textual " Ovwrt"
4239 "The string displayed in the mode line when in overwrite mode.")
4240 (defvar overwrite-mode-binary " Bin Ovwrt"
4241 "The string displayed in the mode line when in binary overwrite mode.")
4243 (defun overwrite-mode (arg)
4244 "Toggle overwrite mode.
4245 With arg, turn overwrite mode on iff arg is positive.
4246 In overwrite mode, printing characters typed in replace existing text
4247 on a one-for-one basis, rather than pushing it to the right. At the
4248 end of a line, such characters extend the line. Before a tab,
4249 such characters insert until the tab is filled in.
4250 \\[quoted-insert] still inserts characters in overwrite mode; this
4251 is supposed to make it easier to insert characters when necessary."
4252 (interactive "P")
4253 (setq overwrite-mode
4254 (if (if (null arg) (not overwrite-mode)
4255 (> (prefix-numeric-value arg) 0))
4256 'overwrite-mode-textual))
4257 (force-mode-line-update))
4259 (defun binary-overwrite-mode (arg)
4260 "Toggle binary overwrite mode.
4261 With arg, turn binary overwrite mode on iff arg is positive.
4262 In binary overwrite mode, printing characters typed in replace
4263 existing text. Newlines are not treated specially, so typing at the
4264 end of a line joins the line to the next, with the typed character
4265 between them. Typing before a tab character simply replaces the tab
4266 with the character typed.
4267 \\[quoted-insert] replaces the text at the cursor, just as ordinary
4268 typing characters do.
4270 Note that binary overwrite mode is not its own minor mode; it is a
4271 specialization of overwrite mode, entered by setting the
4272 `overwrite-mode' variable to `overwrite-mode-binary'."
4273 (interactive "P")
4274 (setq overwrite-mode
4275 (if (if (null arg)
4276 (not (eq overwrite-mode 'overwrite-mode-binary))
4277 (> (prefix-numeric-value arg) 0))
4278 'overwrite-mode-binary))
4279 (force-mode-line-update))
4281 (define-minor-mode line-number-mode
4282 "Toggle Line Number mode.
4283 With arg, turn Line Number mode on iff arg is positive.
4284 When Line Number mode is enabled, the line number appears
4285 in the mode line.
4287 Line numbers do not appear for very large buffers and buffers
4288 with very long lines; see variables `line-number-display-limit'
4289 and `line-number-display-limit-width'."
4290 :init-value t :global t :group 'editing-basics)
4292 (define-minor-mode column-number-mode
4293 "Toggle Column Number mode.
4294 With arg, turn Column Number mode on iff arg is positive.
4295 When Column Number mode is enabled, the column number appears
4296 in the mode line."
4297 :global t :group 'editing-basics)
4299 (define-minor-mode size-indication-mode
4300 "Toggle Size Indication mode.
4301 With arg, turn Size Indication mode on iff arg is positive. When
4302 Size Indication mode is enabled, the size of the accessible part
4303 of the buffer appears in the mode line."
4304 :global t :group 'editing-basics)
4306 (defgroup paren-blinking nil
4307 "Blinking matching of parens and expressions."
4308 :prefix "blink-matching-"
4309 :group 'paren-matching)
4311 (defcustom blink-matching-paren t
4312 "*Non-nil means show matching open-paren when close-paren is inserted."
4313 :type 'boolean
4314 :group 'paren-blinking)
4316 (defcustom blink-matching-paren-on-screen t
4317 "*Non-nil means show matching open-paren when it is on screen.
4318 If nil, means don't show it (but the open-paren can still be shown
4319 when it is off screen).
4321 This variable has no effect if `blink-matching-paren' is nil.
4322 \(In that case, the open-paren is never shown.)
4323 It is also ignored if `show-paren-mode' is enabled."
4324 :type 'boolean
4325 :group 'paren-blinking)
4327 (defcustom blink-matching-paren-distance (* 25 1024)
4328 "*If non-nil, maximum distance to search backwards for matching open-paren.
4329 If nil, search stops at the beginning of the accessible portion of the buffer."
4330 :type '(choice (const nil) integer)
4331 :group 'paren-blinking)
4333 (defcustom blink-matching-delay 1
4334 "*Time in seconds to delay after showing a matching paren."
4335 :type 'number
4336 :group 'paren-blinking)
4338 (defcustom blink-matching-paren-dont-ignore-comments nil
4339 "*Non-nil means `blink-matching-paren' will not ignore comments."
4340 :type 'boolean
4341 :group 'paren-blinking)
4343 (defun blink-matching-open ()
4344 "Move cursor momentarily to the beginning of the sexp before point."
4345 (interactive)
4346 (when (and (> (point) (point-min))
4347 blink-matching-paren
4348 ;; Verify an even number of quoting characters precede the close.
4349 (= 1 (logand 1 (- (point)
4350 (save-excursion
4351 (forward-char -1)
4352 (skip-syntax-backward "/\\")
4353 (point))))))
4354 (let* ((oldpos (point))
4355 blinkpos
4356 message-log-max ; Don't log messages about paren matching.
4357 matching-paren
4358 open-paren-line-string)
4359 (save-excursion
4360 (save-restriction
4361 (if blink-matching-paren-distance
4362 (narrow-to-region (max (point-min)
4363 (- (point) blink-matching-paren-distance))
4364 oldpos))
4365 (condition-case ()
4366 (let ((parse-sexp-ignore-comments
4367 (and parse-sexp-ignore-comments
4368 (not blink-matching-paren-dont-ignore-comments))))
4369 (setq blinkpos (scan-sexps oldpos -1)))
4370 (error nil)))
4371 (and blinkpos
4372 ;; Not syntax '$'.
4373 (not (eq (syntax-class (syntax-after blinkpos)) 8))
4374 (setq matching-paren
4375 (let ((syntax (syntax-after blinkpos)))
4376 (and (consp syntax)
4377 (eq (syntax-class syntax) 4)
4378 (cdr syntax)))))
4379 (cond
4380 ((not (or (eq matching-paren (char-before oldpos))
4381 ;; The cdr might hold a new paren-class info rather than
4382 ;; a matching-char info, in which case the two CDRs
4383 ;; should match.
4384 (eq matching-paren (cdr (syntax-after (1- oldpos))))))
4385 (message "Mismatched parentheses"))
4386 ((not blinkpos)
4387 (if (not blink-matching-paren-distance)
4388 (message "Unmatched parenthesis")))
4389 ((pos-visible-in-window-p blinkpos)
4390 ;; Matching open within window, temporarily move to blinkpos but only
4391 ;; if `blink-matching-paren-on-screen' is non-nil.
4392 (and blink-matching-paren-on-screen
4393 (not show-paren-mode)
4394 (save-excursion
4395 (goto-char blinkpos)
4396 (sit-for blink-matching-delay))))
4398 (save-excursion
4399 (goto-char blinkpos)
4400 (setq open-paren-line-string
4401 ;; Show what precedes the open in its line, if anything.
4402 (if (save-excursion
4403 (skip-chars-backward " \t")
4404 (not (bolp)))
4405 (buffer-substring (line-beginning-position)
4406 (1+ blinkpos))
4407 ;; Show what follows the open in its line, if anything.
4408 (if (save-excursion
4409 (forward-char 1)
4410 (skip-chars-forward " \t")
4411 (not (eolp)))
4412 (buffer-substring blinkpos
4413 (line-end-position))
4414 ;; Otherwise show the previous nonblank line,
4415 ;; if there is one.
4416 (if (save-excursion
4417 (skip-chars-backward "\n \t")
4418 (not (bobp)))
4419 (concat
4420 (buffer-substring (progn
4421 (skip-chars-backward "\n \t")
4422 (line-beginning-position))
4423 (progn (end-of-line)
4424 (skip-chars-backward " \t")
4425 (point)))
4426 ;; Replace the newline and other whitespace with `...'.
4427 "..."
4428 (buffer-substring blinkpos (1+ blinkpos)))
4429 ;; There is nothing to show except the char itself.
4430 (buffer-substring blinkpos (1+ blinkpos)))))))
4431 (message "Matches %s"
4432 (substring-no-properties open-paren-line-string))))))))
4434 ;Turned off because it makes dbx bomb out.
4435 (setq blink-paren-function 'blink-matching-open)
4437 ;; This executes C-g typed while Emacs is waiting for a command.
4438 ;; Quitting out of a program does not go through here;
4439 ;; that happens in the QUIT macro at the C code level.
4440 (defun keyboard-quit ()
4441 "Signal a `quit' condition.
4442 During execution of Lisp code, this character causes a quit directly.
4443 At top-level, as an editor command, this simply beeps."
4444 (interactive)
4445 (deactivate-mark)
4446 (if (fboundp 'kmacro-keyboard-quit)
4447 (kmacro-keyboard-quit))
4448 (setq defining-kbd-macro nil)
4449 (signal 'quit nil))
4451 (defvar buffer-quit-function nil
4452 "Function to call to \"quit\" the current buffer, or nil if none.
4453 \\[keyboard-escape-quit] calls this function when its more local actions
4454 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4456 (defun keyboard-escape-quit ()
4457 "Exit the current \"mode\" (in a generalized sense of the word).
4458 This command can exit an interactive command such as `query-replace',
4459 can clear out a prefix argument or a region,
4460 can get out of the minibuffer or other recursive edit,
4461 cancel the use of the current buffer (for special-purpose buffers),
4462 or go back to just one window (by deleting all but the selected window)."
4463 (interactive)
4464 (cond ((eq last-command 'mode-exited) nil)
4465 ((> (minibuffer-depth) 0)
4466 (abort-recursive-edit))
4467 (current-prefix-arg
4468 nil)
4469 ((and transient-mark-mode mark-active)
4470 (deactivate-mark))
4471 ((> (recursion-depth) 0)
4472 (exit-recursive-edit))
4473 (buffer-quit-function
4474 (funcall buffer-quit-function))
4475 ((not (one-window-p t))
4476 (delete-other-windows))
4477 ((string-match "^ \\*" (buffer-name (current-buffer)))
4478 (bury-buffer))))
4480 (defun play-sound-file (file &optional volume device)
4481 "Play sound stored in FILE.
4482 VOLUME and DEVICE correspond to the keywords of the sound
4483 specification for `play-sound'."
4484 (interactive "fPlay sound file: ")
4485 (let ((sound (list :file file)))
4486 (if volume
4487 (plist-put sound :volume volume))
4488 (if device
4489 (plist-put sound :device device))
4490 (push 'sound sound)
4491 (play-sound sound)))
4494 (defcustom read-mail-command 'rmail
4495 "*Your preference for a mail reading package.
4496 This is used by some keybindings which support reading mail.
4497 See also `mail-user-agent' concerning sending mail."
4498 :type '(choice (function-item rmail)
4499 (function-item gnus)
4500 (function-item mh-rmail)
4501 (function :tag "Other"))
4502 :version "21.1"
4503 :group 'mail)
4505 (defcustom mail-user-agent 'sendmail-user-agent
4506 "*Your preference for a mail composition package.
4507 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
4508 outgoing email message. This variable lets you specify which
4509 mail-sending package you prefer.
4511 Valid values include:
4513 `sendmail-user-agent' -- use the default Emacs Mail package.
4514 See Info node `(emacs)Sending Mail'.
4515 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
4516 See Info node `(mh-e)'.
4517 `message-user-agent' -- use the Gnus Message package.
4518 See Info node `(message)'.
4519 `gnus-user-agent' -- like `message-user-agent', but with Gnus
4520 paraphernalia, particularly the Gcc: header for
4521 archiving.
4523 Additional valid symbols may be available; check with the author of
4524 your package for details. The function should return non-nil if it
4525 succeeds.
4527 See also `read-mail-command' concerning reading mail."
4528 :type '(radio (function-item :tag "Default Emacs mail"
4529 :format "%t\n"
4530 sendmail-user-agent)
4531 (function-item :tag "Emacs interface to MH"
4532 :format "%t\n"
4533 mh-e-user-agent)
4534 (function-item :tag "Gnus Message package"
4535 :format "%t\n"
4536 message-user-agent)
4537 (function-item :tag "Gnus Message with full Gnus features"
4538 :format "%t\n"
4539 gnus-user-agent)
4540 (function :tag "Other"))
4541 :group 'mail)
4543 (define-mail-user-agent 'sendmail-user-agent
4544 'sendmail-user-agent-compose
4545 'mail-send-and-exit)
4547 (defun rfc822-goto-eoh ()
4548 ;; Go to header delimiter line in a mail message, following RFC822 rules
4549 (goto-char (point-min))
4550 (when (re-search-forward
4551 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
4552 (goto-char (match-beginning 0))))
4554 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
4555 switch-function yank-action
4556 send-actions)
4557 (if switch-function
4558 (let ((special-display-buffer-names nil)
4559 (special-display-regexps nil)
4560 (same-window-buffer-names nil)
4561 (same-window-regexps nil))
4562 (funcall switch-function "*mail*")))
4563 (let ((cc (cdr (assoc-string "cc" other-headers t)))
4564 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
4565 (body (cdr (assoc-string "body" other-headers t))))
4566 (or (mail continue to subject in-reply-to cc yank-action send-actions)
4567 continue
4568 (error "Message aborted"))
4569 (save-excursion
4570 (rfc822-goto-eoh)
4571 (while other-headers
4572 (unless (member-ignore-case (car (car other-headers))
4573 '("in-reply-to" "cc" "body"))
4574 (insert (car (car other-headers)) ": "
4575 (cdr (car other-headers))
4576 (if use-hard-newlines hard-newline "\n")))
4577 (setq other-headers (cdr other-headers)))
4578 (when body
4579 (forward-line 1)
4580 (insert body))
4581 t)))
4583 (defun compose-mail (&optional to subject other-headers continue
4584 switch-function yank-action send-actions)
4585 "Start composing a mail message to send.
4586 This uses the user's chosen mail composition package
4587 as selected with the variable `mail-user-agent'.
4588 The optional arguments TO and SUBJECT specify recipients
4589 and the initial Subject field, respectively.
4591 OTHER-HEADERS is an alist specifying additional
4592 header fields. Elements look like (HEADER . VALUE) where both
4593 HEADER and VALUE are strings.
4595 CONTINUE, if non-nil, says to continue editing a message already
4596 being composed.
4598 SWITCH-FUNCTION, if non-nil, is a function to use to
4599 switch to and display the buffer used for mail composition.
4601 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
4602 to insert the raw text of the message being replied to.
4603 It has the form (FUNCTION . ARGS). The user agent will apply
4604 FUNCTION to ARGS, to insert the raw text of the original message.
4605 \(The user agent will also run `mail-citation-hook', *after* the
4606 original text has been inserted in this way.)
4608 SEND-ACTIONS is a list of actions to call when the message is sent.
4609 Each action has the form (FUNCTION . ARGS)."
4610 (interactive
4611 (list nil nil nil current-prefix-arg))
4612 (let ((function (get mail-user-agent 'composefunc)))
4613 (funcall function to subject other-headers continue
4614 switch-function yank-action send-actions)))
4616 (defun compose-mail-other-window (&optional to subject other-headers continue
4617 yank-action send-actions)
4618 "Like \\[compose-mail], but edit the outgoing message in another window."
4619 (interactive
4620 (list nil nil nil current-prefix-arg))
4621 (compose-mail to subject other-headers continue
4622 'switch-to-buffer-other-window yank-action send-actions))
4625 (defun compose-mail-other-frame (&optional to subject other-headers continue
4626 yank-action send-actions)
4627 "Like \\[compose-mail], but edit the outgoing message in another frame."
4628 (interactive
4629 (list nil nil nil current-prefix-arg))
4630 (compose-mail to subject other-headers continue
4631 'switch-to-buffer-other-frame yank-action send-actions))
4633 (defvar set-variable-value-history nil
4634 "History of values entered with `set-variable'.")
4636 (defun set-variable (variable value &optional make-local)
4637 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4638 VARIABLE should be a user option variable name, a Lisp variable
4639 meant to be customized by users. You should enter VALUE in Lisp syntax,
4640 so if you want VALUE to be a string, you must surround it with doublequotes.
4641 VALUE is used literally, not evaluated.
4643 If VARIABLE has a `variable-interactive' property, that is used as if
4644 it were the arg to `interactive' (which see) to interactively read VALUE.
4646 If VARIABLE has been defined with `defcustom', then the type information
4647 in the definition is used to check that VALUE is valid.
4649 With a prefix argument, set VARIABLE to VALUE buffer-locally."
4650 (interactive
4651 (let* ((default-var (variable-at-point))
4652 (var (if (user-variable-p default-var)
4653 (read-variable (format "Set variable (default %s): " default-var)
4654 default-var)
4655 (read-variable "Set variable: ")))
4656 (minibuffer-help-form '(describe-variable var))
4657 (prop (get var 'variable-interactive))
4658 (obsolete (car (get var 'byte-obsolete-variable)))
4659 (prompt (format "Set %s %s to value: " var
4660 (cond ((local-variable-p var)
4661 "(buffer-local)")
4662 ((or current-prefix-arg
4663 (local-variable-if-set-p var))
4664 "buffer-locally")
4665 (t "globally"))))
4666 (val (progn
4667 (when obsolete
4668 (message (concat "`%S' is obsolete; "
4669 (if (symbolp obsolete) "use `%S' instead" "%s"))
4670 var obsolete)
4671 (sit-for 3))
4672 (if prop
4673 ;; Use VAR's `variable-interactive' property
4674 ;; as an interactive spec for prompting.
4675 (call-interactively `(lambda (arg)
4676 (interactive ,prop)
4677 arg))
4678 (read
4679 (read-string prompt nil
4680 'set-variable-value-history
4681 (format "%S" (symbol-value var))))))))
4682 (list var val current-prefix-arg)))
4684 (and (custom-variable-p variable)
4685 (not (get variable 'custom-type))
4686 (custom-load-symbol variable))
4687 (let ((type (get variable 'custom-type)))
4688 (when type
4689 ;; Match with custom type.
4690 (require 'cus-edit)
4691 (setq type (widget-convert type))
4692 (unless (widget-apply type :match value)
4693 (error "Value `%S' does not match type %S of %S"
4694 value (car type) variable))))
4696 (if make-local
4697 (make-local-variable variable))
4699 (set variable value)
4701 ;; Force a thorough redisplay for the case that the variable
4702 ;; has an effect on the display, like `tab-width' has.
4703 (force-mode-line-update))
4705 ;; Define the major mode for lists of completions.
4707 (defvar completion-list-mode-map nil
4708 "Local map for completion list buffers.")
4709 (or completion-list-mode-map
4710 (let ((map (make-sparse-keymap)))
4711 (define-key map [mouse-2] 'mouse-choose-completion)
4712 (define-key map [follow-link] 'mouse-face)
4713 (define-key map [down-mouse-2] nil)
4714 (define-key map "\C-m" 'choose-completion)
4715 (define-key map "\e\e\e" 'delete-completion-window)
4716 (define-key map [left] 'previous-completion)
4717 (define-key map [right] 'next-completion)
4718 (setq completion-list-mode-map map)))
4720 ;; Completion mode is suitable only for specially formatted data.
4721 (put 'completion-list-mode 'mode-class 'special)
4723 (defvar completion-reference-buffer nil
4724 "Record the buffer that was current when the completion list was requested.
4725 This is a local variable in the completion list buffer.
4726 Initial value is nil to avoid some compiler warnings.")
4728 (defvar completion-no-auto-exit nil
4729 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4730 This also applies to other functions such as `choose-completion'
4731 and `mouse-choose-completion'.")
4733 (defvar completion-base-size nil
4734 "Number of chars at beginning of minibuffer not involved in completion.
4735 This is a local variable in the completion list buffer
4736 but it talks about the buffer in `completion-reference-buffer'.
4737 If this is nil, it means to compare text to determine which part
4738 of the tail end of the buffer's text is involved in completion.")
4740 (defun delete-completion-window ()
4741 "Delete the completion list window.
4742 Go to the window from which completion was requested."
4743 (interactive)
4744 (let ((buf completion-reference-buffer))
4745 (if (one-window-p t)
4746 (if (window-dedicated-p (selected-window))
4747 (delete-frame (selected-frame)))
4748 (delete-window (selected-window))
4749 (if (get-buffer-window buf)
4750 (select-window (get-buffer-window buf))))))
4752 (defun previous-completion (n)
4753 "Move to the previous item in the completion list."
4754 (interactive "p")
4755 (next-completion (- n)))
4757 (defun next-completion (n)
4758 "Move to the next item in the completion list.
4759 With prefix argument N, move N items (negative N means move backward)."
4760 (interactive "p")
4761 (let ((beg (point-min)) (end (point-max)))
4762 (while (and (> n 0) (not (eobp)))
4763 ;; If in a completion, move to the end of it.
4764 (when (get-text-property (point) 'mouse-face)
4765 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4766 ;; Move to start of next one.
4767 (unless (get-text-property (point) 'mouse-face)
4768 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4769 (setq n (1- n)))
4770 (while (and (< n 0) (not (bobp)))
4771 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4772 ;; If in a completion, move to the start of it.
4773 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
4774 (goto-char (previous-single-property-change
4775 (point) 'mouse-face nil beg)))
4776 ;; Move to end of the previous completion.
4777 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4778 (goto-char (previous-single-property-change
4779 (point) 'mouse-face nil beg)))
4780 ;; Move to the start of that one.
4781 (goto-char (previous-single-property-change
4782 (point) 'mouse-face nil beg))
4783 (setq n (1+ n))))))
4785 (defun choose-completion ()
4786 "Choose the completion that point is in or next to."
4787 (interactive)
4788 (let (beg end completion (buffer completion-reference-buffer)
4789 (base-size completion-base-size))
4790 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4791 (setq end (point) beg (1+ (point))))
4792 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
4793 (setq end (1- (point)) beg (point)))
4794 (if (null beg)
4795 (error "No completion here"))
4796 (setq beg (previous-single-property-change beg 'mouse-face))
4797 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
4798 (setq completion (buffer-substring-no-properties beg end))
4799 (let ((owindow (selected-window)))
4800 (if (and (one-window-p t 'selected-frame)
4801 (window-dedicated-p (selected-window)))
4802 ;; This is a special buffer's frame
4803 (iconify-frame (selected-frame))
4804 (or (window-dedicated-p (selected-window))
4805 (bury-buffer)))
4806 (select-window owindow))
4807 (choose-completion-string completion buffer base-size)))
4809 ;; Delete the longest partial match for STRING
4810 ;; that can be found before POINT.
4811 (defun choose-completion-delete-max-match (string)
4812 (let ((opoint (point))
4813 len)
4814 ;; Try moving back by the length of the string.
4815 (goto-char (max (- (point) (length string))
4816 (minibuffer-prompt-end)))
4817 ;; See how far back we were actually able to move. That is the
4818 ;; upper bound on how much we can match and delete.
4819 (setq len (- opoint (point)))
4820 (if completion-ignore-case
4821 (setq string (downcase string)))
4822 (while (and (> len 0)
4823 (let ((tail (buffer-substring (point) opoint)))
4824 (if completion-ignore-case
4825 (setq tail (downcase tail)))
4826 (not (string= tail (substring string 0 len)))))
4827 (setq len (1- len))
4828 (forward-char 1))
4829 (delete-char len)))
4831 (defvar choose-completion-string-functions nil
4832 "Functions that may override the normal insertion of a completion choice.
4833 These functions are called in order with four arguments:
4834 CHOICE - the string to insert in the buffer,
4835 BUFFER - the buffer in which the choice should be inserted,
4836 MINI-P - non-nil iff BUFFER is a minibuffer, and
4837 BASE-SIZE - the number of characters in BUFFER before
4838 the string being completed.
4840 If a function in the list returns non-nil, that function is supposed
4841 to have inserted the CHOICE in the BUFFER, and possibly exited
4842 the minibuffer; no further functions will be called.
4844 If all functions in the list return nil, that means to use
4845 the default method of inserting the completion in BUFFER.")
4847 (defun choose-completion-string (choice &optional buffer base-size)
4848 "Switch to BUFFER and insert the completion choice CHOICE.
4849 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
4850 to keep. If it is nil, we call `choose-completion-delete-max-match'
4851 to decide what to delete."
4853 ;; If BUFFER is the minibuffer, exit the minibuffer
4854 ;; unless it is reading a file name and CHOICE is a directory,
4855 ;; or completion-no-auto-exit is non-nil.
4857 (let* ((buffer (or buffer completion-reference-buffer))
4858 (mini-p (minibufferp buffer)))
4859 ;; If BUFFER is a minibuffer, barf unless it's the currently
4860 ;; active minibuffer.
4861 (if (and mini-p
4862 (or (not (active-minibuffer-window))
4863 (not (equal buffer
4864 (window-buffer (active-minibuffer-window))))))
4865 (error "Minibuffer is not active for completion")
4866 ;; Set buffer so buffer-local choose-completion-string-functions works.
4867 (set-buffer buffer)
4868 (unless (run-hook-with-args-until-success
4869 'choose-completion-string-functions
4870 choice buffer mini-p base-size)
4871 ;; Insert the completion into the buffer where it was requested.
4872 (if base-size
4873 (delete-region (+ base-size (if mini-p
4874 (minibuffer-prompt-end)
4875 (point-min)))
4876 (point))
4877 (choose-completion-delete-max-match choice))
4878 (insert choice)
4879 (remove-text-properties (- (point) (length choice)) (point)
4880 '(mouse-face nil))
4881 ;; Update point in the window that BUFFER is showing in.
4882 (let ((window (get-buffer-window buffer t)))
4883 (set-window-point window (point)))
4884 ;; If completing for the minibuffer, exit it with this choice.
4885 (and (not completion-no-auto-exit)
4886 (equal buffer (window-buffer (minibuffer-window)))
4887 minibuffer-completion-table
4888 ;; If this is reading a file name, and the file name chosen
4889 ;; is a directory, don't exit the minibuffer.
4890 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4891 (file-directory-p (field-string (point-max))))
4892 (let ((mini (active-minibuffer-window)))
4893 (select-window mini)
4894 (when minibuffer-auto-raise
4895 (raise-frame (window-frame mini))))
4896 (exit-minibuffer)))))))
4898 (defun completion-list-mode ()
4899 "Major mode for buffers showing lists of possible completions.
4900 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4901 to select the completion near point.
4902 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4903 with the mouse."
4904 (interactive)
4905 (kill-all-local-variables)
4906 (use-local-map completion-list-mode-map)
4907 (setq mode-name "Completion List")
4908 (setq major-mode 'completion-list-mode)
4909 (make-local-variable 'completion-base-size)
4910 (setq completion-base-size nil)
4911 (run-mode-hooks 'completion-list-mode-hook))
4913 (defun completion-list-mode-finish ()
4914 "Finish setup of the completions buffer.
4915 Called from `temp-buffer-show-hook'."
4916 (when (eq major-mode 'completion-list-mode)
4917 (toggle-read-only 1)))
4919 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4921 (defvar completion-setup-hook nil
4922 "Normal hook run at the end of setting up a completion list buffer.
4923 When this hook is run, the current buffer is the one in which the
4924 command to display the completion list buffer was run.
4925 The completion list buffer is available as the value of `standard-output'.
4926 The common prefix substring for completion may be available as the
4927 value of `completion-common-substring'. See also `display-completion-list'.")
4930 ;; Variables and faces used in `completion-setup-function'.
4932 (defface completions-first-difference
4933 '((t (:inherit bold)))
4934 "Face put on the first uncommon character in completions in *Completions* buffer."
4935 :group 'completion)
4937 (defface completions-common-part
4938 '((t (:inherit default)))
4939 "Face put on the common prefix substring in completions in *Completions* buffer.
4940 The idea of `completions-common-part' is that you can use it to
4941 make the common parts less visible than normal, so that the rest
4942 of the differing parts is, by contrast, slightly highlighted."
4943 :group 'completion)
4945 ;; This is for packages that need to bind it to a non-default regexp
4946 ;; in order to make the first-differing character highlight work
4947 ;; to their liking
4948 (defvar completion-root-regexp "^/"
4949 "Regexp to use in `completion-setup-function' to find the root directory.")
4951 (defvar completion-common-substring nil
4952 "Common prefix substring to use in `completion-setup-function' to put faces.
4953 The value is set by `display-completion-list' during running `completion-setup-hook'.
4955 To put faces `completions-first-difference' and `completions-common-part'
4956 in the `*Completions*' buffer, the common prefix substring in completions
4957 is needed as a hint. (The minibuffer is a special case. The content
4958 of the minibuffer before point is always the common substring.)")
4960 ;; This function goes in completion-setup-hook, so that it is called
4961 ;; after the text of the completion list buffer is written.
4962 (defun completion-setup-function ()
4963 (let* ((mainbuf (current-buffer))
4964 (mbuf-contents (minibuffer-completion-contents))
4965 common-string-length)
4966 ;; When reading a file name in the minibuffer,
4967 ;; set default-directory in the minibuffer
4968 ;; so it will get copied into the completion list buffer.
4969 (if minibuffer-completing-file-name
4970 (with-current-buffer mainbuf
4971 (setq default-directory (file-name-directory mbuf-contents))))
4972 (with-current-buffer standard-output
4973 (completion-list-mode)
4974 (set (make-local-variable 'completion-reference-buffer) mainbuf)
4975 (setq completion-base-size
4976 (cond
4977 ((and (symbolp minibuffer-completion-table)
4978 (get minibuffer-completion-table 'completion-base-size-function))
4979 ;; To compute base size, a function can use the global value of
4980 ;; completion-common-substring or minibuffer-completion-contents.
4981 (with-current-buffer mainbuf
4982 (funcall (get minibuffer-completion-table
4983 'completion-base-size-function))))
4984 (minibuffer-completing-file-name
4985 ;; For file name completion, use the number of chars before
4986 ;; the start of the file name component at point.
4987 (with-current-buffer mainbuf
4988 (save-excursion
4989 (skip-chars-backward completion-root-regexp)
4990 (- (point) (minibuffer-prompt-end)))))
4991 ;; Otherwise, in minibuffer, the base size is 0.
4992 ((minibufferp mainbuf) 0)))
4993 (setq common-string-length
4994 (cond
4995 (completion-common-substring
4996 (length completion-common-substring))
4997 (completion-base-size
4998 (- (length mbuf-contents) completion-base-size))))
4999 ;; Put faces on first uncommon characters and common parts.
5000 (when (and (integerp common-string-length) (>= common-string-length 0))
5001 (let ((element-start (point-min))
5002 (maxp (point-max))
5003 element-common-end)
5004 (while (and (setq element-start
5005 (next-single-property-change
5006 element-start 'mouse-face))
5007 (< (setq element-common-end
5008 (+ element-start common-string-length))
5009 maxp))
5010 (when (get-char-property element-start 'mouse-face)
5011 (if (and (> common-string-length 0)
5012 (get-char-property (1- element-common-end) 'mouse-face))
5013 (put-text-property element-start element-common-end
5014 'font-lock-face 'completions-common-part))
5015 (if (get-char-property element-common-end 'mouse-face)
5016 (put-text-property element-common-end (1+ element-common-end)
5017 'font-lock-face 'completions-first-difference))))))
5018 ;; Insert help string.
5019 (goto-char (point-min))
5020 (if (display-mouse-p)
5021 (insert (substitute-command-keys
5022 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
5023 (insert (substitute-command-keys
5024 "In this buffer, type \\[choose-completion] to \
5025 select the completion near point.\n\n")))))
5027 (add-hook 'completion-setup-hook 'completion-setup-function)
5029 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
5030 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
5032 (defun switch-to-completions ()
5033 "Select the completion list window."
5034 (interactive)
5035 ;; Make sure we have a completions window.
5036 (or (get-buffer-window "*Completions*")
5037 (minibuffer-completion-help))
5038 (let ((window (get-buffer-window "*Completions*")))
5039 (when window
5040 (select-window window)
5041 (goto-char (point-min))
5042 (search-forward "\n\n")
5043 (forward-line 1))))
5045 ;;; Support keyboard commands to turn on various modifiers.
5047 ;; These functions -- which are not commands -- each add one modifier
5048 ;; to the following event.
5050 (defun event-apply-alt-modifier (ignore-prompt)
5051 "\\<function-key-map>Add the Alt modifier to the following event.
5052 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
5053 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
5054 (defun event-apply-super-modifier (ignore-prompt)
5055 "\\<function-key-map>Add the Super modifier to the following event.
5056 For example, type \\[event-apply-super-modifier] & to enter Super-&."
5057 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
5058 (defun event-apply-hyper-modifier (ignore-prompt)
5059 "\\<function-key-map>Add the Hyper modifier to the following event.
5060 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
5061 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
5062 (defun event-apply-shift-modifier (ignore-prompt)
5063 "\\<function-key-map>Add the Shift modifier to the following event.
5064 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
5065 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
5066 (defun event-apply-control-modifier (ignore-prompt)
5067 "\\<function-key-map>Add the Ctrl modifier to the following event.
5068 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
5069 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
5070 (defun event-apply-meta-modifier (ignore-prompt)
5071 "\\<function-key-map>Add the Meta modifier to the following event.
5072 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
5073 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
5075 (defun event-apply-modifier (event symbol lshiftby prefix)
5076 "Apply a modifier flag to event EVENT.
5077 SYMBOL is the name of this modifier, as a symbol.
5078 LSHIFTBY is the numeric value of this modifier, in keyboard events.
5079 PREFIX is the string that represents this modifier in an event type symbol."
5080 (if (numberp event)
5081 (cond ((eq symbol 'control)
5082 (if (and (<= (downcase event) ?z)
5083 (>= (downcase event) ?a))
5084 (- (downcase event) ?a -1)
5085 (if (and (<= (downcase event) ?Z)
5086 (>= (downcase event) ?A))
5087 (- (downcase event) ?A -1)
5088 (logior (lsh 1 lshiftby) event))))
5089 ((eq symbol 'shift)
5090 (if (and (<= (downcase event) ?z)
5091 (>= (downcase event) ?a))
5092 (upcase event)
5093 (logior (lsh 1 lshiftby) event)))
5095 (logior (lsh 1 lshiftby) event)))
5096 (if (memq symbol (event-modifiers event))
5097 event
5098 (let ((event-type (if (symbolp event) event (car event))))
5099 (setq event-type (intern (concat prefix (symbol-name event-type))))
5100 (if (symbolp event)
5101 event-type
5102 (cons event-type (cdr event)))))))
5104 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
5105 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
5106 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
5107 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
5108 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
5109 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
5111 ;;;; Keypad support.
5113 ;;; Make the keypad keys act like ordinary typing keys. If people add
5114 ;;; bindings for the function key symbols, then those bindings will
5115 ;;; override these, so this shouldn't interfere with any existing
5116 ;;; bindings.
5118 ;; Also tell read-char how to handle these keys.
5119 (mapc
5120 (lambda (keypad-normal)
5121 (let ((keypad (nth 0 keypad-normal))
5122 (normal (nth 1 keypad-normal)))
5123 (put keypad 'ascii-character normal)
5124 (define-key function-key-map (vector keypad) (vector normal))))
5125 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
5126 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
5127 (kp-space ?\s)
5128 (kp-tab ?\t)
5129 (kp-enter ?\r)
5130 (kp-multiply ?*)
5131 (kp-add ?+)
5132 (kp-separator ?,)
5133 (kp-subtract ?-)
5134 (kp-decimal ?.)
5135 (kp-divide ?/)
5136 (kp-equal ?=)))
5138 ;;;;
5139 ;;;; forking a twin copy of a buffer.
5140 ;;;;
5142 (defvar clone-buffer-hook nil
5143 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5145 (defun clone-process (process &optional newname)
5146 "Create a twin copy of PROCESS.
5147 If NEWNAME is nil, it defaults to PROCESS' name;
5148 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5149 If PROCESS is associated with a buffer, the new process will be associated
5150 with the current buffer instead.
5151 Returns nil if PROCESS has already terminated."
5152 (setq newname (or newname (process-name process)))
5153 (if (string-match "<[0-9]+>\\'" newname)
5154 (setq newname (substring newname 0 (match-beginning 0))))
5155 (when (memq (process-status process) '(run stop open))
5156 (let* ((process-connection-type (process-tty-name process))
5157 (new-process
5158 (if (memq (process-status process) '(open))
5159 (let ((args (process-contact process t)))
5160 (setq args (plist-put args :name newname))
5161 (setq args (plist-put args :buffer
5162 (if (process-buffer process)
5163 (current-buffer))))
5164 (apply 'make-network-process args))
5165 (apply 'start-process newname
5166 (if (process-buffer process) (current-buffer))
5167 (process-command process)))))
5168 (set-process-query-on-exit-flag
5169 new-process (process-query-on-exit-flag process))
5170 (set-process-inherit-coding-system-flag
5171 new-process (process-inherit-coding-system-flag process))
5172 (set-process-filter new-process (process-filter process))
5173 (set-process-sentinel new-process (process-sentinel process))
5174 (set-process-plist new-process (copy-sequence (process-plist process)))
5175 new-process)))
5177 ;; things to maybe add (currently partly covered by `funcall mode'):
5178 ;; - syntax-table
5179 ;; - overlays
5180 (defun clone-buffer (&optional newname display-flag)
5181 "Create and return a twin copy of the current buffer.
5182 Unlike an indirect buffer, the new buffer can be edited
5183 independently of the old one (if it is not read-only).
5184 NEWNAME is the name of the new buffer. It may be modified by
5185 adding or incrementing <N> at the end as necessary to create a
5186 unique buffer name. If nil, it defaults to the name of the
5187 current buffer, with the proper suffix. If DISPLAY-FLAG is
5188 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
5189 clone a file-visiting buffer, or a buffer whose major mode symbol
5190 has a non-nil `no-clone' property, results in an error.
5192 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
5193 current buffer with appropriate suffix. However, if a prefix
5194 argument is given, then the command prompts for NEWNAME in the
5195 minibuffer.
5197 This runs the normal hook `clone-buffer-hook' in the new buffer
5198 after it has been set up properly in other respects."
5199 (interactive
5200 (progn
5201 (if buffer-file-name
5202 (error "Cannot clone a file-visiting buffer"))
5203 (if (get major-mode 'no-clone)
5204 (error "Cannot clone a buffer in %s mode" mode-name))
5205 (list (if current-prefix-arg
5206 (read-buffer "Name of new cloned buffer: " (current-buffer)))
5207 t)))
5208 (if buffer-file-name
5209 (error "Cannot clone a file-visiting buffer"))
5210 (if (get major-mode 'no-clone)
5211 (error "Cannot clone a buffer in %s mode" mode-name))
5212 (setq newname (or newname (buffer-name)))
5213 (if (string-match "<[0-9]+>\\'" newname)
5214 (setq newname (substring newname 0 (match-beginning 0))))
5215 (let ((buf (current-buffer))
5216 (ptmin (point-min))
5217 (ptmax (point-max))
5218 (pt (point))
5219 (mk (if mark-active (mark t)))
5220 (modified (buffer-modified-p))
5221 (mode major-mode)
5222 (lvars (buffer-local-variables))
5223 (process (get-buffer-process (current-buffer)))
5224 (new (generate-new-buffer (or newname (buffer-name)))))
5225 (save-restriction
5226 (widen)
5227 (with-current-buffer new
5228 (insert-buffer-substring buf)))
5229 (with-current-buffer new
5230 (narrow-to-region ptmin ptmax)
5231 (goto-char pt)
5232 (if mk (set-mark mk))
5233 (set-buffer-modified-p modified)
5235 ;; Clone the old buffer's process, if any.
5236 (when process (clone-process process))
5238 ;; Now set up the major mode.
5239 (funcall mode)
5241 ;; Set up other local variables.
5242 (mapcar (lambda (v)
5243 (condition-case () ;in case var is read-only
5244 (if (symbolp v)
5245 (makunbound v)
5246 (set (make-local-variable (car v)) (cdr v)))
5247 (error nil)))
5248 lvars)
5250 ;; Run any hooks (typically set up by the major mode
5251 ;; for cloning to work properly).
5252 (run-hooks 'clone-buffer-hook))
5253 (if display-flag
5254 ;; Presumably the current buffer is shown in the selected frame, so
5255 ;; we want to display the clone elsewhere.
5256 (let ((same-window-regexps nil)
5257 (same-window-buffer-names))
5258 (pop-to-buffer new)))
5259 new))
5262 (defun clone-indirect-buffer (newname display-flag &optional norecord)
5263 "Create an indirect buffer that is a twin copy of the current buffer.
5265 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
5266 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
5267 or if not called with a prefix arg, NEWNAME defaults to the current
5268 buffer's name. The name is modified by adding a `<N>' suffix to it
5269 or by incrementing the N in an existing suffix.
5271 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
5272 This is always done when called interactively.
5274 Optional third arg NORECORD non-nil means do not put this buffer at the
5275 front of the list of recently selected ones."
5276 (interactive
5277 (progn
5278 (if (get major-mode 'no-clone-indirect)
5279 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5280 (list (if current-prefix-arg
5281 (read-buffer "Name of indirect buffer: " (current-buffer)))
5282 t)))
5283 (if (get major-mode 'no-clone-indirect)
5284 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5285 (setq newname (or newname (buffer-name)))
5286 (if (string-match "<[0-9]+>\\'" newname)
5287 (setq newname (substring newname 0 (match-beginning 0))))
5288 (let* ((name (generate-new-buffer-name newname))
5289 (buffer (make-indirect-buffer (current-buffer) name t)))
5290 (when display-flag
5291 (pop-to-buffer buffer norecord))
5292 buffer))
5295 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
5296 "Like `clone-indirect-buffer' but display in another window."
5297 (interactive
5298 (progn
5299 (if (get major-mode 'no-clone-indirect)
5300 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5301 (list (if current-prefix-arg
5302 (read-buffer "Name of indirect buffer: " (current-buffer)))
5303 t)))
5304 (let ((pop-up-windows t))
5305 (clone-indirect-buffer newname display-flag norecord)))
5308 ;;; Handling of Backspace and Delete keys.
5310 (defcustom normal-erase-is-backspace
5311 (and (not noninteractive)
5312 (or (memq system-type '(ms-dos windows-nt))
5313 (eq window-system 'mac)
5314 (and (memq window-system '(x))
5315 (fboundp 'x-backspace-delete-keys-p)
5316 (x-backspace-delete-keys-p))
5317 ;; If the terminal Emacs is running on has erase char
5318 ;; set to ^H, use the Backspace key for deleting
5319 ;; backward and, and the Delete key for deleting forward.
5320 (and (null window-system)
5321 (eq tty-erase-char ?\^H))))
5322 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
5324 On window systems, the default value of this option is chosen
5325 according to the keyboard used. If the keyboard has both a Backspace
5326 key and a Delete key, and both are mapped to their usual meanings, the
5327 option's default value is set to t, so that Backspace can be used to
5328 delete backward, and Delete can be used to delete forward.
5330 If not running under a window system, customizing this option accomplishes
5331 a similar effect by mapping C-h, which is usually generated by the
5332 Backspace key, to DEL, and by mapping DEL to C-d via
5333 `keyboard-translate'. The former functionality of C-h is available on
5334 the F1 key. You should probably not use this setting if you don't
5335 have both Backspace, Delete and F1 keys.
5337 Setting this variable with setq doesn't take effect. Programmatically,
5338 call `normal-erase-is-backspace-mode' (which see) instead."
5339 :type 'boolean
5340 :group 'editing-basics
5341 :version "21.1"
5342 :set (lambda (symbol value)
5343 ;; The fboundp is because of a problem with :set when
5344 ;; dumping Emacs. It doesn't really matter.
5345 (if (fboundp 'normal-erase-is-backspace-mode)
5346 (normal-erase-is-backspace-mode (or value 0))
5347 (set-default symbol value))))
5350 (defun normal-erase-is-backspace-mode (&optional arg)
5351 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5353 With numeric arg, turn the mode on if and only if ARG is positive.
5355 On window systems, when this mode is on, Delete is mapped to C-d and
5356 Backspace is mapped to DEL; when this mode is off, both Delete and
5357 Backspace are mapped to DEL. (The remapping goes via
5358 `function-key-map', so binding Delete or Backspace in the global or
5359 local keymap will override that.)
5361 In addition, on window systems, the bindings of C-Delete, M-Delete,
5362 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5363 the global keymap in accordance with the functionality of Delete and
5364 Backspace. For example, if Delete is remapped to C-d, which deletes
5365 forward, C-Delete is bound to `kill-word', but if Delete is remapped
5366 to DEL, which deletes backward, C-Delete is bound to
5367 `backward-kill-word'.
5369 If not running on a window system, a similar effect is accomplished by
5370 remapping C-h (normally produced by the Backspace key) and DEL via
5371 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5372 to C-d; if it's off, the keys are not remapped.
5374 When not running on a window system, and this mode is turned on, the
5375 former functionality of C-h is available on the F1 key. You should
5376 probably not turn on this mode on a text-only terminal if you don't
5377 have both Backspace, Delete and F1 keys.
5379 See also `normal-erase-is-backspace'."
5380 (interactive "P")
5381 (setq normal-erase-is-backspace
5382 (if arg
5383 (> (prefix-numeric-value arg) 0)
5384 (not normal-erase-is-backspace)))
5386 (cond ((or (memq window-system '(x w32 mac pc))
5387 (memq system-type '(ms-dos windows-nt)))
5388 (let ((bindings
5389 `(([C-delete] [C-backspace])
5390 ([M-delete] [M-backspace])
5391 ([C-M-delete] [C-M-backspace])
5392 (,esc-map
5393 [C-delete] [C-backspace])))
5394 (old-state (lookup-key function-key-map [delete])))
5396 (if normal-erase-is-backspace
5397 (progn
5398 (define-key function-key-map [delete] [?\C-d])
5399 (define-key function-key-map [kp-delete] [?\C-d])
5400 (define-key function-key-map [backspace] [?\C-?]))
5401 (define-key function-key-map [delete] [?\C-?])
5402 (define-key function-key-map [kp-delete] [?\C-?])
5403 (define-key function-key-map [backspace] [?\C-?]))
5405 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5406 (unless (equal old-state (lookup-key function-key-map [delete]))
5407 (dolist (binding bindings)
5408 (let ((map global-map))
5409 (when (keymapp (car binding))
5410 (setq map (car binding) binding (cdr binding)))
5411 (let* ((key1 (nth 0 binding))
5412 (key2 (nth 1 binding))
5413 (binding1 (lookup-key map key1))
5414 (binding2 (lookup-key map key2)))
5415 (define-key map key1 binding2)
5416 (define-key map key2 binding1)))))))
5418 (if normal-erase-is-backspace
5419 (progn
5420 (keyboard-translate ?\C-h ?\C-?)
5421 (keyboard-translate ?\C-? ?\C-d))
5422 (keyboard-translate ?\C-h ?\C-h)
5423 (keyboard-translate ?\C-? ?\C-?))))
5425 (run-hooks 'normal-erase-is-backspace-hook)
5426 (if (interactive-p)
5427 (message "Delete key deletes %s"
5428 (if normal-erase-is-backspace "forward" "backward"))))
5430 (defvar vis-mode-saved-buffer-invisibility-spec nil
5431 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
5433 (define-minor-mode visible-mode
5434 "Toggle Visible mode.
5435 With argument ARG turn Visible mode on iff ARG is positive.
5437 Enabling Visible mode makes all invisible text temporarily visible.
5438 Disabling Visible mode turns off that effect. Visible mode
5439 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
5440 :lighter " Vis"
5441 :group 'editing-basics
5442 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
5443 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
5444 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
5445 (when visible-mode
5446 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
5447 buffer-invisibility-spec)
5448 (setq buffer-invisibility-spec nil)))
5450 ;; Minibuffer prompt stuff.
5452 ;(defun minibuffer-prompt-modification (start end)
5453 ; (error "You cannot modify the prompt"))
5456 ;(defun minibuffer-prompt-insertion (start end)
5457 ; (let ((inhibit-modification-hooks t))
5458 ; (delete-region start end)
5459 ; ;; Discard undo information for the text insertion itself
5460 ; ;; and for the text deletion.above.
5461 ; (when (consp buffer-undo-list)
5462 ; (setq buffer-undo-list (cddr buffer-undo-list)))
5463 ; (message "You cannot modify the prompt")))
5466 ;(setq minibuffer-prompt-properties
5467 ; (list 'modification-hooks '(minibuffer-prompt-modification)
5468 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
5471 (provide 'simple)
5473 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
5474 ;;; simple.el ends here