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