Merge from trunk
[emacs.git] / lisp / simple.el
blobdc025fffc2bc3135c8afb3ffe4c2cd901b572fd5
1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985-1987, 1993-2011 Free Software Foundation, Inc.
5 ;; Maintainer: FSF
6 ;; Keywords: internal
7 ;; Package: emacs
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 3 of the License, or
14 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
29 ;;; Code:
31 (eval-when-compile (require 'cl)) ;For define-minor-mode.
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
36 ;;; From compile.el
37 (defvar compilation-current-error)
38 (defvar compilation-context-lines)
40 (defcustom idle-update-delay 0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
44 :type 'number
45 :group 'display
46 :version "22.1")
48 (defgroup killing nil
49 "Killing and yanking commands."
50 :group 'editing)
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
54 :group 'matching)
56 ;;; next-error support framework
58 (defgroup next-error nil
59 "`next-error' support framework."
60 :group 'compilation
61 :version "22.1")
63 (defface next-error
64 '((t (:inherit region)))
65 "Face used to highlight next error locus."
66 :group 'next-error
67 :version "22.1")
69 (defcustom next-error-highlight 0.5
70 "Highlighting of locations in selected source buffers.
71 If a number, highlight the locus in `next-error' face for the given time
72 in seconds, or until the next command is executed.
73 If t, highlight the locus until the next command is executed, or until
74 some other locus replaces it.
75 If nil, don't highlight the locus in the source buffer.
76 If `fringe-arrow', indicate the locus by the fringe arrow."
77 :type '(choice (number :tag "Highlight for specified time")
78 (const :tag "Semipermanent highlighting" t)
79 (const :tag "No highlighting" nil)
80 (const :tag "Fringe arrow" fringe-arrow))
81 :group 'next-error
82 :version "22.1")
84 (defcustom next-error-highlight-no-select 0.5
85 "Highlighting of locations in `next-error-no-select'.
86 If number, highlight the locus in `next-error' face for given time in seconds.
87 If t, highlight the locus indefinitely until some other locus replaces it.
88 If nil, don't highlight the locus in the source buffer.
89 If `fringe-arrow', indicate the locus by the fringe arrow."
90 :type '(choice (number :tag "Highlight for specified time")
91 (const :tag "Semipermanent highlighting" t)
92 (const :tag "No highlighting" nil)
93 (const :tag "Fringe arrow" fringe-arrow))
94 :group 'next-error
95 :version "22.1")
97 (defcustom next-error-recenter nil
98 "Display the line in the visited source file recentered as specified.
99 If non-nil, the value is passed directly to `recenter'."
100 :type '(choice (integer :tag "Line to recenter to")
101 (const :tag "Center of window" (4))
102 (const :tag "No recentering" nil))
103 :group 'next-error
104 :version "23.1")
106 (defcustom next-error-hook nil
107 "List of hook functions run by `next-error' after visiting source file."
108 :type 'hook
109 :group 'next-error)
111 (defvar next-error-highlight-timer nil)
113 (defvar next-error-overlay-arrow-position nil)
114 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
115 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
117 (defvar next-error-last-buffer nil
118 "The most recent `next-error' buffer.
119 A buffer becomes most recent when its compilation, grep, or
120 similar mode is started, or when it is used with \\[next-error]
121 or \\[compile-goto-error].")
123 (defvar next-error-function nil
124 "Function to use to find the next error in the current buffer.
125 The function is called with 2 parameters:
126 ARG is an integer specifying by how many errors to move.
127 RESET is a boolean which, if non-nil, says to go back to the beginning
128 of the errors before moving.
129 Major modes providing compile-like functionality should set this variable
130 to indicate to `next-error' that this is a candidate buffer and how
131 to navigate in it.")
132 (make-variable-buffer-local 'next-error-function)
134 (defvar next-error-move-function nil
135 "Function to use to move to an error locus.
136 It takes two arguments, a buffer position in the error buffer
137 and a buffer position in the error locus buffer.
138 The buffer for the error locus should already be current.
139 nil means use goto-char using the second argument position.")
140 (make-variable-buffer-local 'next-error-move-function)
142 (defsubst next-error-buffer-p (buffer
143 &optional avoid-current
144 extra-test-inclusive
145 extra-test-exclusive)
146 "Test if BUFFER is a `next-error' capable buffer.
148 If AVOID-CURRENT is non-nil, treat the current buffer
149 as an absolute last resort only.
151 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
152 that normally would not qualify. If it returns t, the buffer
153 in question is treated as usable.
155 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
156 that would normally be considered usable. If it returns nil,
157 that buffer is rejected."
158 (and (buffer-name buffer) ;First make sure it's live.
159 (not (and avoid-current (eq buffer (current-buffer))))
160 (with-current-buffer buffer
161 (if next-error-function ; This is the normal test.
162 ;; Optionally reject some buffers.
163 (if extra-test-exclusive
164 (funcall extra-test-exclusive)
166 ;; Optionally accept some other buffers.
167 (and extra-test-inclusive
168 (funcall extra-test-inclusive))))))
170 (defun next-error-find-buffer (&optional avoid-current
171 extra-test-inclusive
172 extra-test-exclusive)
173 "Return a `next-error' capable buffer.
175 If AVOID-CURRENT is non-nil, treat the current buffer
176 as an absolute last resort only.
178 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
179 that normally would not qualify. If it returns t, the buffer
180 in question is treated as usable.
182 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
183 that would normally be considered usable. If it returns nil,
184 that buffer is rejected."
186 ;; 1. If one window on the selected frame displays such buffer, return it.
187 (let ((window-buffers
188 (delete-dups
189 (delq nil (mapcar (lambda (w)
190 (if (next-error-buffer-p
191 (window-buffer w)
192 avoid-current
193 extra-test-inclusive extra-test-exclusive)
194 (window-buffer w)))
195 (window-list))))))
196 (if (eq (length window-buffers) 1)
197 (car window-buffers)))
198 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
199 (if (and next-error-last-buffer
200 (next-error-buffer-p next-error-last-buffer avoid-current
201 extra-test-inclusive extra-test-exclusive))
202 next-error-last-buffer)
203 ;; 3. If the current buffer is acceptable, choose it.
204 (if (next-error-buffer-p (current-buffer) avoid-current
205 extra-test-inclusive extra-test-exclusive)
206 (current-buffer))
207 ;; 4. Look for any acceptable buffer.
208 (let ((buffers (buffer-list)))
209 (while (and buffers
210 (not (next-error-buffer-p
211 (car buffers) avoid-current
212 extra-test-inclusive extra-test-exclusive)))
213 (setq buffers (cdr buffers)))
214 (car buffers))
215 ;; 5. Use the current buffer as a last resort if it qualifies,
216 ;; even despite AVOID-CURRENT.
217 (and avoid-current
218 (next-error-buffer-p (current-buffer) nil
219 extra-test-inclusive extra-test-exclusive)
220 (progn
221 (message "This is the only buffer with error message locations")
222 (current-buffer)))
223 ;; 6. Give up.
224 (error "No buffers contain error message locations")))
226 (defun next-error (&optional arg reset)
227 "Visit next `next-error' message and corresponding source code.
229 If all the error messages parsed so far have been processed already,
230 the message buffer is checked for new ones.
232 A prefix ARG specifies how many error messages to move;
233 negative means move back to previous error messages.
234 Just \\[universal-argument] as a prefix means reparse the error message buffer
235 and start at the first error.
237 The RESET argument specifies that we should restart from the beginning.
239 \\[next-error] normally uses the most recently started
240 compilation, grep, or occur buffer. It can also operate on any
241 buffer with output from the \\[compile], \\[grep] commands, or,
242 more generally, on any buffer in Compilation mode or with
243 Compilation Minor mode enabled, or any buffer in which
244 `next-error-function' is bound to an appropriate function.
245 To specify use of a particular buffer for error messages, type
246 \\[next-error] in that buffer when it is the only one displayed
247 in the current frame.
249 Once \\[next-error] has chosen the buffer for error messages, it
250 runs `next-error-hook' with `run-hooks', and stays with that buffer
251 until you use it in some other buffer which uses Compilation mode
252 or Compilation Minor mode.
254 To control which errors are matched, customize the variable
255 `compilation-error-regexp-alist'."
256 (interactive "P")
257 (if (consp arg) (setq reset t arg nil))
258 (when (setq next-error-last-buffer (next-error-find-buffer))
259 ;; we know here that next-error-function is a valid symbol we can funcall
260 (with-current-buffer next-error-last-buffer
261 (funcall next-error-function (prefix-numeric-value arg) reset)
262 (when next-error-recenter
263 (recenter next-error-recenter))
264 (run-hooks 'next-error-hook))))
266 (defun next-error-internal ()
267 "Visit the source code corresponding to the `next-error' message at point."
268 (setq next-error-last-buffer (current-buffer))
269 ;; we know here that next-error-function is a valid symbol we can funcall
270 (with-current-buffer next-error-last-buffer
271 (funcall next-error-function 0 nil)
272 (when next-error-recenter
273 (recenter next-error-recenter))
274 (run-hooks 'next-error-hook)))
276 (defalias 'goto-next-locus 'next-error)
277 (defalias 'next-match 'next-error)
279 (defun previous-error (&optional n)
280 "Visit previous `next-error' message and corresponding source code.
282 Prefix arg N says how many error messages to move backwards (or
283 forwards, if negative).
285 This operates on the output from the \\[compile] and \\[grep] commands."
286 (interactive "p")
287 (next-error (- (or n 1))))
289 (defun first-error (&optional n)
290 "Restart at the first error.
291 Visit corresponding source code.
292 With prefix arg N, visit the source code of the Nth error.
293 This operates on the output from the \\[compile] command, for instance."
294 (interactive "p")
295 (next-error n t))
297 (defun next-error-no-select (&optional n)
298 "Move point to the next error in the `next-error' buffer and highlight match.
299 Prefix arg N says how many error messages to move forwards (or
300 backwards, if negative).
301 Finds and highlights the source line like \\[next-error], but does not
302 select the source buffer."
303 (interactive "p")
304 (let ((next-error-highlight next-error-highlight-no-select))
305 (next-error n))
306 (pop-to-buffer next-error-last-buffer))
308 (defun previous-error-no-select (&optional n)
309 "Move point to the previous error in the `next-error' buffer and highlight match.
310 Prefix arg N says how many error messages to move backwards (or
311 forwards, if negative).
312 Finds and highlights the source line like \\[previous-error], but does not
313 select the source buffer."
314 (interactive "p")
315 (next-error-no-select (- (or n 1))))
317 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
318 (defvar next-error-follow-last-line nil)
320 (define-minor-mode next-error-follow-minor-mode
321 "Minor mode for compilation, occur and diff modes.
322 When turned on, cursor motion in the compilation, grep, occur or diff
323 buffer causes automatic display of the corresponding source code
324 location."
325 :group 'next-error :init-value nil :lighter " Fol"
326 (if (not next-error-follow-minor-mode)
327 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
328 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
329 (make-local-variable 'next-error-follow-last-line)))
331 ;; Used as a `post-command-hook' by `next-error-follow-mode'
332 ;; for the *Compilation* *grep* and *Occur* buffers.
333 (defun next-error-follow-mode-post-command-hook ()
334 (unless (equal next-error-follow-last-line (line-number-at-pos))
335 (setq next-error-follow-last-line (line-number-at-pos))
336 (condition-case nil
337 (let ((compilation-context-lines nil))
338 (setq compilation-current-error (point))
339 (next-error-no-select 0))
340 (error t))))
345 (defun fundamental-mode ()
346 "Major mode not specialized for anything in particular.
347 Other major modes are defined by comparison with this one."
348 (interactive)
349 (kill-all-local-variables)
350 (run-mode-hooks 'fundamental-mode-hook))
352 ;; Special major modes to view specially formatted data rather than files.
354 (defvar special-mode-map
355 (let ((map (make-sparse-keymap)))
356 (suppress-keymap map)
357 (define-key map "q" 'quit-restore-window)
358 (define-key map " " 'scroll-up)
359 (define-key map "\C-?" 'scroll-down)
360 (define-key map "?" 'describe-mode)
361 (define-key map "h" 'describe-mode)
362 (define-key map ">" 'end-of-buffer)
363 (define-key map "<" 'beginning-of-buffer)
364 (define-key map "g" 'revert-buffer)
365 (define-key map "z" 'kill-this-buffer)
366 map))
368 (put 'special-mode 'mode-class 'special)
369 (define-derived-mode special-mode nil "Special"
370 "Parent major mode from which special major modes should inherit."
371 (setq buffer-read-only t))
373 ;; Major mode meant to be the parent of programming modes.
375 (defvar prog-mode-map
376 (let ((map (make-sparse-keymap)))
377 (define-key map [?\C-\M-q] 'prog-indent-sexp)
378 map)
379 "Keymap used for programming modes.")
381 (defun prog-indent-sexp ()
382 "Indent the expression after point."
383 (interactive)
384 (let ((start (point))
385 (end (save-excursion (forward-sexp 1) (point))))
386 (indent-region start end nil)))
388 (define-derived-mode prog-mode fundamental-mode "Prog"
389 "Major mode for editing programming language source code."
390 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
391 (set (make-local-variable 'parse-sexp-ignore-comments) t)
392 ;; Any programming language is always written left to right.
393 (setq bidi-paragraph-direction 'left-to-right))
395 ;; Making and deleting lines.
397 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
398 "Propertized string representing a hard newline character.")
400 (defun newline (&optional arg)
401 "Insert a newline, and move to left margin of the new line if it's blank.
402 If `use-hard-newlines' is non-nil, the newline is marked with the
403 text-property `hard'.
404 With ARG, insert that many newlines.
405 Call `auto-fill-function' if the current column number is greater
406 than the value of `fill-column' and ARG is nil."
407 (interactive "*P")
408 (barf-if-buffer-read-only)
409 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
410 ;; Set last-command-event to tell self-insert what to insert.
411 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
412 (beforepos (point))
413 (last-command-event ?\n)
414 ;; Don't auto-fill if we have a numeric argument.
415 (auto-fill-function (if arg nil auto-fill-function))
416 (postproc
417 ;; Do the rest in post-self-insert-hook, because we want to do it
418 ;; *before* other functions on that hook.
419 (lambda ()
420 ;; Mark the newline(s) `hard'.
421 (if use-hard-newlines
422 (set-hard-newline-properties
423 (- (point) (prefix-numeric-value arg)) (point)))
424 ;; If the newline leaves the previous line blank, and we
425 ;; have a left margin, delete that from the blank line.
426 (save-excursion
427 (goto-char beforepos)
428 (beginning-of-line)
429 (and (looking-at "[ \t]$")
430 (> (current-left-margin) 0)
431 (delete-region (point)
432 (line-end-position))))
433 ;; Indent the line after the newline, except in one case:
434 ;; when we added the newline at the beginning of a line which
435 ;; starts a page.
436 (or was-page-start
437 (move-to-left-margin nil t)))))
438 (unwind-protect
439 (progn
440 (add-hook 'post-self-insert-hook postproc)
441 (self-insert-command (prefix-numeric-value arg)))
442 ;; We first used let-binding to protect the hook, but that was naive
443 ;; since add-hook affects the symbol-default value of the variable,
444 ;; whereas the let-binding might only protect the buffer-local value.
445 (remove-hook 'post-self-insert-hook postproc)))
446 nil)
448 (defun set-hard-newline-properties (from to)
449 (let ((sticky (get-text-property from 'rear-nonsticky)))
450 (put-text-property from to 'hard 't)
451 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
452 (if (and (listp sticky) (not (memq 'hard sticky)))
453 (put-text-property from (point) 'rear-nonsticky
454 (cons 'hard sticky)))))
456 (defun open-line (n)
457 "Insert a newline and leave point before it.
458 If there is a fill prefix and/or a `left-margin', insert them
459 on the new line if the line would have been blank.
460 With arg N, insert N newlines."
461 (interactive "*p")
462 (let* ((do-fill-prefix (and fill-prefix (bolp)))
463 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
464 (loc (point-marker))
465 ;; Don't expand an abbrev before point.
466 (abbrev-mode nil))
467 (newline n)
468 (goto-char loc)
469 (while (> n 0)
470 (cond ((bolp)
471 (if do-left-margin (indent-to (current-left-margin)))
472 (if do-fill-prefix (insert-and-inherit fill-prefix))))
473 (forward-line 1)
474 (setq n (1- n)))
475 (goto-char loc)
476 (end-of-line)))
478 (defun split-line (&optional arg)
479 "Split current line, moving portion beyond point vertically down.
480 If the current line starts with `fill-prefix', insert it on the new
481 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
483 When called from Lisp code, ARG may be a prefix string to copy."
484 (interactive "*P")
485 (skip-chars-forward " \t")
486 (let* ((col (current-column))
487 (pos (point))
488 ;; What prefix should we check for (nil means don't).
489 (prefix (cond ((stringp arg) arg)
490 (arg nil)
491 (t fill-prefix)))
492 ;; Does this line start with it?
493 (have-prfx (and prefix
494 (save-excursion
495 (beginning-of-line)
496 (looking-at (regexp-quote prefix))))))
497 (newline 1)
498 (if have-prfx (insert-and-inherit prefix))
499 (indent-to col 0)
500 (goto-char pos)))
502 (defun delete-indentation (&optional arg)
503 "Join this line to previous and fix up whitespace at join.
504 If there is a fill prefix, delete it from the beginning of this line.
505 With argument, join this line to following line."
506 (interactive "*P")
507 (beginning-of-line)
508 (if arg (forward-line 1))
509 (if (eq (preceding-char) ?\n)
510 (progn
511 (delete-region (point) (1- (point)))
512 ;; If the second line started with the fill prefix,
513 ;; delete the prefix.
514 (if (and fill-prefix
515 (<= (+ (point) (length fill-prefix)) (point-max))
516 (string= fill-prefix
517 (buffer-substring (point)
518 (+ (point) (length fill-prefix)))))
519 (delete-region (point) (+ (point) (length fill-prefix))))
520 (fixup-whitespace))))
522 (defalias 'join-line #'delete-indentation) ; easier to find
524 (defun delete-blank-lines ()
525 "On blank line, delete all surrounding blank lines, leaving just one.
526 On isolated blank line, delete that one.
527 On nonblank line, delete any immediately following blank lines."
528 (interactive "*")
529 (let (thisblank singleblank)
530 (save-excursion
531 (beginning-of-line)
532 (setq thisblank (looking-at "[ \t]*$"))
533 ;; Set singleblank if there is just one blank line here.
534 (setq singleblank
535 (and thisblank
536 (not (looking-at "[ \t]*\n[ \t]*$"))
537 (or (bobp)
538 (progn (forward-line -1)
539 (not (looking-at "[ \t]*$")))))))
540 ;; Delete preceding blank lines, and this one too if it's the only one.
541 (if thisblank
542 (progn
543 (beginning-of-line)
544 (if singleblank (forward-line 1))
545 (delete-region (point)
546 (if (re-search-backward "[^ \t\n]" nil t)
547 (progn (forward-line 1) (point))
548 (point-min)))))
549 ;; Delete following blank lines, unless the current line is blank
550 ;; and there are no following blank lines.
551 (if (not (and thisblank singleblank))
552 (save-excursion
553 (end-of-line)
554 (forward-line 1)
555 (delete-region (point)
556 (if (re-search-forward "[^ \t\n]" nil t)
557 (progn (beginning-of-line) (point))
558 (point-max)))))
559 ;; Handle the special case where point is followed by newline and eob.
560 ;; Delete the line, leaving point at eob.
561 (if (looking-at "^[ \t]*\n\\'")
562 (delete-region (point) (point-max)))))
564 (defun delete-trailing-whitespace (&optional start end)
565 "Delete all the trailing whitespace across the current buffer.
566 All whitespace after the last non-whitespace character in a line is deleted.
567 This respects narrowing, created by \\[narrow-to-region] and friends.
568 A formfeed is not considered whitespace by this function.
569 If the region is active, only delete whitespace within the region."
570 (interactive (progn
571 (barf-if-buffer-read-only)
572 (if (use-region-p)
573 (list (region-beginning) (region-end))
574 (list nil nil))))
575 (save-match-data
576 (save-excursion
577 (let ((end-marker (copy-marker (or end (point-max))))
578 (start (or start (point-min))))
579 (goto-char start)
580 (while (re-search-forward "\\s-$" end-marker t)
581 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
582 ;; Don't delete formfeeds, even if they are considered whitespace.
583 (save-match-data
584 (if (looking-at ".*\f")
585 (goto-char (match-end 0))))
586 (delete-region (point) (match-end 0)))
587 (set-marker end-marker nil))))
588 ;; Return nil for the benefit of `write-file-functions'.
589 nil)
591 (defun newline-and-indent ()
592 "Insert a newline, then indent according to major mode.
593 Indentation is done using the value of `indent-line-function'.
594 In programming language modes, this is the same as TAB.
595 In some text modes, where TAB inserts a tab, this command indents to the
596 column specified by the function `current-left-margin'."
597 (interactive "*")
598 (delete-horizontal-space t)
599 (newline)
600 (indent-according-to-mode))
602 (defun reindent-then-newline-and-indent ()
603 "Reindent current line, insert newline, then indent the new line.
604 Indentation of both lines is done according to the current major mode,
605 which means calling the current value of `indent-line-function'.
606 In programming language modes, this is the same as TAB.
607 In some text modes, where TAB inserts a tab, this indents to the
608 column specified by the function `current-left-margin'."
609 (interactive "*")
610 (let ((pos (point)))
611 ;; Be careful to insert the newline before indenting the line.
612 ;; Otherwise, the indentation might be wrong.
613 (newline)
614 (save-excursion
615 (goto-char pos)
616 ;; We are at EOL before the call to indent-according-to-mode, and
617 ;; after it we usually are as well, but not always. We tried to
618 ;; address it with `save-excursion' but that uses a normal marker
619 ;; whereas we need `move after insertion', so we do the save/restore
620 ;; by hand.
621 (setq pos (copy-marker pos t))
622 (indent-according-to-mode)
623 (goto-char pos)
624 ;; Remove the trailing white-space after indentation because
625 ;; indentation may introduce the whitespace.
626 (delete-horizontal-space t))
627 (indent-according-to-mode)))
629 (defun quoted-insert (arg)
630 "Read next input character and insert it.
631 This is useful for inserting control characters.
632 With argument, insert ARG copies of the character.
634 If the first character you type after this command is an octal digit,
635 you should type a sequence of octal digits which specify a character code.
636 Any nondigit terminates the sequence. If the terminator is a RET,
637 it is discarded; any other terminator is used itself as input.
638 The variable `read-quoted-char-radix' specifies the radix for this feature;
639 set it to 10 or 16 to use decimal or hex instead of octal.
641 In overwrite mode, this function inserts the character anyway, and
642 does not handle octal digits specially. This means that if you use
643 overwrite as your normal editing mode, you can use this function to
644 insert characters when necessary.
646 In binary overwrite mode, this function does overwrite, and octal
647 digits are interpreted as a character code. This is intended to be
648 useful for editing binary files."
649 (interactive "*p")
650 (let* ((char
651 ;; Avoid "obsolete" warnings for translation-table-for-input.
652 (with-no-warnings
653 (let (translation-table-for-input input-method-function)
654 (if (or (not overwrite-mode)
655 (eq overwrite-mode 'overwrite-mode-binary))
656 (read-quoted-char)
657 (read-char))))))
658 ;; This used to assume character codes 0240 - 0377 stand for
659 ;; characters in some single-byte character set, and converted them
660 ;; to Emacs characters. But in 23.1 this feature is deprecated
661 ;; in favor of inserting the corresponding Unicode characters.
662 ;; (if (and enable-multibyte-characters
663 ;; (>= char ?\240)
664 ;; (<= char ?\377))
665 ;; (setq char (unibyte-char-to-multibyte char)))
666 (if (> arg 0)
667 (if (eq overwrite-mode 'overwrite-mode-binary)
668 (delete-char arg)))
669 (while (> arg 0)
670 (insert-and-inherit char)
671 (setq arg (1- arg)))))
673 (defun forward-to-indentation (&optional arg)
674 "Move forward ARG lines and position at first nonblank character."
675 (interactive "^p")
676 (forward-line (or arg 1))
677 (skip-chars-forward " \t"))
679 (defun backward-to-indentation (&optional arg)
680 "Move backward ARG lines and position at first nonblank character."
681 (interactive "^p")
682 (forward-line (- (or arg 1)))
683 (skip-chars-forward " \t"))
685 (defun back-to-indentation ()
686 "Move point to the first non-whitespace character on this line."
687 (interactive "^")
688 (beginning-of-line 1)
689 (skip-syntax-forward " " (line-end-position))
690 ;; Move back over chars that have whitespace syntax but have the p flag.
691 (backward-prefix-chars))
693 (defun fixup-whitespace ()
694 "Fixup white space between objects around point.
695 Leave one space or none, according to the context."
696 (interactive "*")
697 (save-excursion
698 (delete-horizontal-space)
699 (if (or (looking-at "^\\|\\s)")
700 (save-excursion (forward-char -1)
701 (looking-at "$\\|\\s(\\|\\s'")))
703 (insert ?\s))))
705 (defun delete-horizontal-space (&optional backward-only)
706 "Delete all spaces and tabs around point.
707 If BACKWARD-ONLY is non-nil, only delete them before point."
708 (interactive "*P")
709 (let ((orig-pos (point)))
710 (delete-region
711 (if backward-only
712 orig-pos
713 (progn
714 (skip-chars-forward " \t")
715 (constrain-to-field nil orig-pos t)))
716 (progn
717 (skip-chars-backward " \t")
718 (constrain-to-field nil orig-pos)))))
720 (defun just-one-space (&optional n)
721 "Delete all spaces and tabs around point, leaving one space (or N spaces).
722 If N is negative, delete newlines as well."
723 (interactive "*p")
724 (unless n (setq n 1))
725 (let ((orig-pos (point))
726 (skip-characters (if (< n 0) " \t\n\r" " \t"))
727 (n (abs n)))
728 (skip-chars-backward skip-characters)
729 (constrain-to-field nil orig-pos)
730 (dotimes (i n)
731 (if (= (following-char) ?\s)
732 (forward-char 1)
733 (insert ?\s)))
734 (delete-region
735 (point)
736 (progn
737 (skip-chars-forward skip-characters)
738 (constrain-to-field nil orig-pos t)))))
740 (defun beginning-of-buffer (&optional arg)
741 "Move point to the beginning of the buffer.
742 With numeric arg N, put point N/10 of the way from the beginning.
743 If the buffer is narrowed, this command uses the beginning of the
744 accessible part of the buffer.
746 If Transient Mark mode is disabled, leave mark at previous
747 position, unless a \\[universal-argument] prefix is supplied.
749 Don't use this command in Lisp programs!
750 \(goto-char (point-min)) is faster."
751 (interactive "^P")
752 (or (consp arg)
753 (region-active-p)
754 (push-mark))
755 (let ((size (- (point-max) (point-min))))
756 (goto-char (if (and arg (not (consp arg)))
757 (+ (point-min)
758 (if (> size 10000)
759 ;; Avoid overflow for large buffer sizes!
760 (* (prefix-numeric-value arg)
761 (/ size 10))
762 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
763 (point-min))))
764 (if (and arg (not (consp arg))) (forward-line 1)))
766 (defun end-of-buffer (&optional arg)
767 "Move point to the end of the buffer.
768 With numeric arg N, put point N/10 of the way from the end.
769 If the buffer is narrowed, this command uses the end of the
770 accessible part of the buffer.
772 If Transient Mark mode is disabled, leave mark at previous
773 position, unless a \\[universal-argument] prefix is supplied.
775 Don't use this command in Lisp programs!
776 \(goto-char (point-max)) is faster."
777 (interactive "^P")
778 (or (consp arg) (region-active-p) (push-mark))
779 (let ((size (- (point-max) (point-min))))
780 (goto-char (if (and arg (not (consp arg)))
781 (- (point-max)
782 (if (> size 10000)
783 ;; Avoid overflow for large buffer sizes!
784 (* (prefix-numeric-value arg)
785 (/ size 10))
786 (/ (* size (prefix-numeric-value arg)) 10)))
787 (point-max))))
788 ;; If we went to a place in the middle of the buffer,
789 ;; adjust it to the beginning of a line.
790 (cond ((and arg (not (consp arg))) (forward-line 1))
791 ((> (point) (window-end nil t))
792 ;; If the end of the buffer is not already on the screen,
793 ;; then scroll specially to put it near, but not at, the bottom.
794 (overlay-recenter (point))
795 (recenter -3))))
797 (defcustom delete-active-region t
798 "Whether single-char deletion commands delete an active region.
799 This has an effect only if Transient Mark mode is enabled, and
800 affects `delete-forward-char' and `delete-backward-char', though
801 not `delete-char'.
803 If the value is the symbol `kill', the active region is killed
804 instead of deleted."
805 :type '(choice (const :tag "Delete active region" t)
806 (const :tag "Kill active region" kill)
807 (const :tag "Do ordinary deletion" nil))
808 :group 'editing
809 :version "24.1")
811 (defun delete-backward-char (n &optional killflag)
812 "Delete the previous N characters (following if N is negative).
813 If Transient Mark mode is enabled, the mark is active, and N is 1,
814 delete the text in the region and deactivate the mark instead.
815 To disable this, set `delete-active-region' to nil.
817 Optional second arg KILLFLAG, if non-nil, means to kill (save in
818 kill ring) instead of delete. Interactively, N is the prefix
819 arg, and KILLFLAG is set if N is explicitly specified.
821 In Overwrite mode, single character backward deletion may replace
822 tabs with spaces so as to back over columns, unless point is at
823 the end of the line."
824 (interactive "p\nP")
825 (unless (integerp n)
826 (signal 'wrong-type-argument (list 'integerp n)))
827 (cond ((and (use-region-p)
828 delete-active-region
829 (= n 1))
830 ;; If a region is active, kill or delete it.
831 (if (eq delete-active-region 'kill)
832 (kill-region (region-beginning) (region-end))
833 (delete-region (region-beginning) (region-end))))
834 ;; In Overwrite mode, maybe untabify while deleting
835 ((null (or (null overwrite-mode)
836 (<= n 0)
837 (memq (char-before) '(?\t ?\n))
838 (eobp)
839 (eq (char-after) ?\n)))
840 (let ((ocol (current-column)))
841 (delete-char (- n) killflag)
842 (save-excursion
843 (insert-char ?\s (- ocol (current-column)) nil))))
844 ;; Otherwise, do simple deletion.
845 (t (delete-char (- n) killflag))))
847 (defun delete-forward-char (n &optional killflag)
848 "Delete the following N characters (previous if N is negative).
849 If Transient Mark mode is enabled, the mark is active, and N is 1,
850 delete the text in the region and deactivate the mark instead.
851 To disable this, set `delete-active-region' to nil.
853 Optional second arg KILLFLAG non-nil means to kill (save in kill
854 ring) instead of delete. Interactively, N is the prefix arg, and
855 KILLFLAG is set if N was explicitly specified."
856 (interactive "p\nP")
857 (unless (integerp n)
858 (signal 'wrong-type-argument (list 'integerp n)))
859 (cond ((and (use-region-p)
860 delete-active-region
861 (= n 1))
862 ;; If a region is active, kill or delete it.
863 (if (eq delete-active-region 'kill)
864 (kill-region (region-beginning) (region-end))
865 (delete-region (region-beginning) (region-end))))
866 ;; Otherwise, do simple deletion.
867 (t (delete-char n killflag))))
869 (defun mark-whole-buffer ()
870 "Put point at beginning and mark at end of buffer.
871 You probably should not use this function in Lisp programs;
872 it is usually a mistake for a Lisp function to use any subroutine
873 that uses or sets the mark."
874 (interactive)
875 (push-mark (point))
876 (push-mark (point-max) nil t)
877 (goto-char (point-min)))
880 ;; Counting lines, one way or another.
882 (defun goto-line (line &optional buffer)
883 "Goto LINE, counting from line 1 at beginning of buffer.
884 Normally, move point in the current buffer, and leave mark at the
885 previous position. With just \\[universal-argument] as argument,
886 move point in the most recently selected other buffer, and switch to it.
888 If there's a number in the buffer at point, it is the default for LINE.
890 This function is usually the wrong thing to use in a Lisp program.
891 What you probably want instead is something like:
892 (goto-char (point-min)) (forward-line (1- N))
893 If at all possible, an even better solution is to use char counts
894 rather than line counts."
895 (interactive
896 (if (and current-prefix-arg (not (consp current-prefix-arg)))
897 (list (prefix-numeric-value current-prefix-arg))
898 ;; Look for a default, a number in the buffer at point.
899 (let* ((default
900 (save-excursion
901 (skip-chars-backward "0-9")
902 (if (looking-at "[0-9]")
903 (buffer-substring-no-properties
904 (point)
905 (progn (skip-chars-forward "0-9")
906 (point))))))
907 ;; Decide if we're switching buffers.
908 (buffer
909 (if (consp current-prefix-arg)
910 (other-buffer (current-buffer) t)))
911 (buffer-prompt
912 (if buffer
913 (concat " in " (buffer-name buffer))
914 "")))
915 ;; Read the argument, offering that number (if any) as default.
916 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
917 "Goto line%s: ")
918 buffer-prompt
919 default)
920 nil nil t
921 'minibuffer-history
922 default)
923 buffer))))
924 ;; Switch to the desired buffer, one way or another.
925 (if buffer
926 (let ((window (get-buffer-window buffer)))
927 (if window
928 (select-window window)
929 (pop-to-buffer-other-window buffer))))
930 ;; Leave mark at previous position
931 (or (region-active-p) (push-mark))
932 ;; Move to the specified line number in that buffer.
933 (save-restriction
934 (widen)
935 (goto-char (point-min))
936 (if (eq selective-display t)
937 (re-search-forward "[\n\C-m]" nil 'end (1- line))
938 (forward-line (1- line)))))
940 (defun count-words-region (start end)
941 "Print the number of words in the region.
942 When called interactively, the word count is printed in echo area."
943 (interactive "r")
944 (let ((count 0))
945 (save-excursion
946 (save-restriction
947 (narrow-to-region start end)
948 (goto-char (point-min))
949 (while (forward-word 1)
950 (setq count (1+ count)))))
951 (if (called-interactively-p 'interactive)
952 (message "Region has %d words" count))
953 count))
955 (defun count-lines-region (start end)
956 "Print number of lines and characters in the region."
957 (interactive "r")
958 (message "Region has %d lines, %d characters"
959 (count-lines start end) (- end start)))
961 (defun what-line ()
962 "Print the current buffer line number and narrowed line number of point."
963 (interactive)
964 (let ((start (point-min))
965 (n (line-number-at-pos)))
966 (if (= start 1)
967 (message "Line %d" n)
968 (save-excursion
969 (save-restriction
970 (widen)
971 (message "line %d (narrowed line %d)"
972 (+ n (line-number-at-pos start) -1) n))))))
974 (defun count-lines (start end)
975 "Return number of lines between START and END.
976 This is usually the number of newlines between them,
977 but can be one more if START is not equal to END
978 and the greater of them is not at the start of a line."
979 (save-excursion
980 (save-restriction
981 (narrow-to-region start end)
982 (goto-char (point-min))
983 (if (eq selective-display t)
984 (save-match-data
985 (let ((done 0))
986 (while (re-search-forward "[\n\C-m]" nil t 40)
987 (setq done (+ 40 done)))
988 (while (re-search-forward "[\n\C-m]" nil t 1)
989 (setq done (+ 1 done)))
990 (goto-char (point-max))
991 (if (and (/= start end)
992 (not (bolp)))
993 (1+ done)
994 done)))
995 (- (buffer-size) (forward-line (buffer-size)))))))
997 (defun line-number-at-pos (&optional pos)
998 "Return (narrowed) buffer line number at position POS.
999 If POS is nil, use current buffer location.
1000 Counting starts at (point-min), so the value refers
1001 to the contents of the accessible portion of the buffer."
1002 (let ((opoint (or pos (point))) start)
1003 (save-excursion
1004 (goto-char (point-min))
1005 (setq start (point))
1006 (goto-char opoint)
1007 (forward-line 0)
1008 (1+ (count-lines start (point))))))
1010 (defun what-cursor-position (&optional detail)
1011 "Print info on cursor position (on screen and within buffer).
1012 Also describe the character after point, and give its character code
1013 in octal, decimal and hex.
1015 For a non-ASCII multibyte character, also give its encoding in the
1016 buffer's selected coding system if the coding system encodes the
1017 character safely. If the character is encoded into one byte, that
1018 code is shown in hex. If the character is encoded into more than one
1019 byte, just \"...\" is shown.
1021 In addition, with prefix argument, show details about that character
1022 in *Help* buffer. See also the command `describe-char'."
1023 (interactive "P")
1024 (let* ((char (following-char))
1025 (beg (point-min))
1026 (end (point-max))
1027 (pos (point))
1028 (total (buffer-size))
1029 (percent (if (> total 50000)
1030 ;; Avoid overflow from multiplying by 100!
1031 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
1032 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
1033 (hscroll (if (= (window-hscroll) 0)
1035 (format " Hscroll=%d" (window-hscroll))))
1036 (col (current-column)))
1037 (if (= pos end)
1038 (if (or (/= beg 1) (/= end (1+ total)))
1039 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1040 pos total percent beg end col hscroll)
1041 (message "point=%d of %d (EOB) column=%d%s"
1042 pos total col hscroll))
1043 (let ((coding buffer-file-coding-system)
1044 encoded encoding-msg display-prop under-display)
1045 (if (or (not coding)
1046 (eq (coding-system-type coding) t))
1047 (setq coding (default-value 'buffer-file-coding-system)))
1048 (if (eq (char-charset char) 'eight-bit)
1049 (setq encoding-msg
1050 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1051 ;; Check if the character is displayed with some `display'
1052 ;; text property. In that case, set under-display to the
1053 ;; buffer substring covered by that property.
1054 (setq display-prop (get-text-property pos 'display))
1055 (if display-prop
1056 (let ((to (or (next-single-property-change pos 'display)
1057 (point-max))))
1058 (if (< to (+ pos 4))
1059 (setq under-display "")
1060 (setq under-display "..."
1061 to (+ pos 4)))
1062 (setq under-display
1063 (concat (buffer-substring-no-properties pos to)
1064 under-display)))
1065 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1066 (setq encoding-msg
1067 (if display-prop
1068 (if (not (stringp display-prop))
1069 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1070 char char char under-display)
1071 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1072 char char char under-display display-prop))
1073 (if encoded
1074 (format "(%d, #o%o, #x%x, file %s)"
1075 char char char
1076 (if (> (length encoded) 1)
1077 "..."
1078 (encoded-string-description encoded coding)))
1079 (format "(%d, #o%o, #x%x)" char char char)))))
1080 (if detail
1081 ;; We show the detailed information about CHAR.
1082 (describe-char (point)))
1083 (if (or (/= beg 1) (/= end (1+ total)))
1084 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1085 (if (< char 256)
1086 (single-key-description char)
1087 (buffer-substring-no-properties (point) (1+ (point))))
1088 encoding-msg pos total percent beg end col hscroll)
1089 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
1090 (if enable-multibyte-characters
1091 (if (< char 128)
1092 (single-key-description char)
1093 (buffer-substring-no-properties (point) (1+ (point))))
1094 (single-key-description char))
1095 encoding-msg pos total percent col hscroll))))))
1097 ;; Initialize read-expression-map. It is defined at C level.
1098 (let ((m (make-sparse-keymap)))
1099 (define-key m "\M-\t" 'lisp-complete-symbol)
1100 ;; Might as well bind TAB to completion, since inserting a TAB char is much
1101 ;; too rarely useful.
1102 (define-key m "\t" 'lisp-complete-symbol)
1103 (set-keymap-parent m minibuffer-local-map)
1104 (setq read-expression-map m))
1106 (defvar minibuffer-completing-symbol nil
1107 "Non-nil means completing a Lisp symbol in the minibuffer.")
1109 (defvar minibuffer-default nil
1110 "The current default value or list of default values in the minibuffer.
1111 The functions `read-from-minibuffer' and `completing-read' bind
1112 this variable locally.")
1114 (defcustom eval-expression-print-level 4
1115 "Value for `print-level' while printing value in `eval-expression'.
1116 A value of nil means no limit."
1117 :group 'lisp
1118 :type '(choice (const :tag "No Limit" nil) integer)
1119 :version "21.1")
1121 (defcustom eval-expression-print-length 12
1122 "Value for `print-length' while printing value in `eval-expression'.
1123 A value of nil means no limit."
1124 :group 'lisp
1125 :type '(choice (const :tag "No Limit" nil) integer)
1126 :version "21.1")
1128 (defcustom eval-expression-debug-on-error t
1129 "If non-nil set `debug-on-error' to t in `eval-expression'.
1130 If nil, don't change the value of `debug-on-error'."
1131 :group 'lisp
1132 :type 'boolean
1133 :version "21.1")
1135 (defun eval-expression-print-format (value)
1136 "Format VALUE as a result of evaluated expression.
1137 Return a formatted string which is displayed in the echo area
1138 in addition to the value printed by prin1 in functions which
1139 display the result of expression evaluation."
1140 (if (and (integerp value)
1141 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1142 (eq this-command last-command)
1143 (if (boundp 'edebug-active) edebug-active)))
1144 (let ((char-string
1145 (if (or (if (boundp 'edebug-active) edebug-active)
1146 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1147 (prin1-char value))))
1148 (if char-string
1149 (format " (#o%o, #x%x, %s)" value value char-string)
1150 (format " (#o%o, #x%x)" value value)))))
1152 ;; We define this, rather than making `eval' interactive,
1153 ;; for the sake of completion of names like eval-region, eval-buffer.
1154 (defun eval-expression (eval-expression-arg
1155 &optional eval-expression-insert-value)
1156 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1157 Value is also consed on to front of the variable `values'.
1158 Optional argument EVAL-EXPRESSION-INSERT-VALUE non-nil (interactively,
1159 with prefix argument) means insert the result into the current buffer
1160 instead of printing it in the echo area. Truncates long output
1161 according to the value of the variables `eval-expression-print-length'
1162 and `eval-expression-print-level'.
1164 If `eval-expression-debug-on-error' is non-nil, which is the default,
1165 this command arranges for all errors to enter the debugger."
1166 (interactive
1167 (list (let ((minibuffer-completing-symbol t))
1168 (read-from-minibuffer "Eval: "
1169 nil read-expression-map t
1170 'read-expression-history))
1171 current-prefix-arg))
1173 (if (null eval-expression-debug-on-error)
1174 (push (eval eval-expression-arg lexical-binding) values)
1175 (let ((old-value (make-symbol "t")) new-value)
1176 ;; Bind debug-on-error to something unique so that we can
1177 ;; detect when evaled code changes it.
1178 (let ((debug-on-error old-value))
1179 (push (eval eval-expression-arg lexical-binding) values)
1180 (setq new-value debug-on-error))
1181 ;; If evaled code has changed the value of debug-on-error,
1182 ;; propagate that change to the global binding.
1183 (unless (eq old-value new-value)
1184 (setq debug-on-error new-value))))
1186 (let ((print-length eval-expression-print-length)
1187 (print-level eval-expression-print-level))
1188 (if eval-expression-insert-value
1189 (with-no-warnings
1190 (let ((standard-output (current-buffer)))
1191 (prin1 (car values))))
1192 (prog1
1193 (prin1 (car values) t)
1194 (let ((str (eval-expression-print-format (car values))))
1195 (if str (princ str t)))))))
1197 (defun edit-and-eval-command (prompt command)
1198 "Prompting with PROMPT, let user edit COMMAND and eval result.
1199 COMMAND is a Lisp expression. Let user edit that expression in
1200 the minibuffer, then read and evaluate the result."
1201 (let ((command
1202 (let ((print-level nil)
1203 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1204 (unwind-protect
1205 (read-from-minibuffer prompt
1206 (prin1-to-string command)
1207 read-expression-map t
1208 'command-history)
1209 ;; If command was added to command-history as a string,
1210 ;; get rid of that. We want only evaluable expressions there.
1211 (if (stringp (car command-history))
1212 (setq command-history (cdr command-history)))))))
1214 ;; If command to be redone does not match front of history,
1215 ;; add it to the history.
1216 (or (equal command (car command-history))
1217 (setq command-history (cons command command-history)))
1218 (eval command)))
1220 (defun repeat-complex-command (arg)
1221 "Edit and re-evaluate last complex command, or ARGth from last.
1222 A complex command is one which used the minibuffer.
1223 The command is placed in the minibuffer as a Lisp form for editing.
1224 The result is executed, repeating the command as changed.
1225 If the command has been changed or is not the most recent previous
1226 command it is added to the front of the command history.
1227 You can use the minibuffer history commands \
1228 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1229 to get different commands to edit and resubmit."
1230 (interactive "p")
1231 (let ((elt (nth (1- arg) command-history))
1232 newcmd)
1233 (if elt
1234 (progn
1235 (setq newcmd
1236 (let ((print-level nil)
1237 (minibuffer-history-position arg)
1238 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1239 (unwind-protect
1240 (read-from-minibuffer
1241 "Redo: " (prin1-to-string elt) read-expression-map t
1242 (cons 'command-history arg))
1244 ;; If command was added to command-history as a
1245 ;; string, get rid of that. We want only
1246 ;; evaluable expressions there.
1247 (if (stringp (car command-history))
1248 (setq command-history (cdr command-history))))))
1250 ;; If command to be redone does not match front of history,
1251 ;; add it to the history.
1252 (or (equal newcmd (car command-history))
1253 (setq command-history (cons newcmd command-history)))
1254 (eval newcmd))
1255 (if command-history
1256 (error "Argument %d is beyond length of command history" arg)
1257 (error "There are no previous complex commands to repeat")))))
1259 (defun read-extended-command ()
1260 "Read command name to invoke in `execute-extended-command'."
1261 (minibuffer-with-setup-hook
1262 (lambda ()
1263 (set (make-local-variable 'minibuffer-default-add-function)
1264 (lambda ()
1265 ;; Get a command name at point in the original buffer
1266 ;; to propose it after M-n.
1267 (with-current-buffer (window-buffer (minibuffer-selected-window))
1268 (and (commandp (function-called-at-point))
1269 (format "%S" (function-called-at-point)))))))
1270 ;; Read a string, completing from and restricting to the set of
1271 ;; all defined commands. Don't provide any initial input.
1272 ;; Save the command read on the extended-command history list.
1273 (completing-read
1274 (concat (cond
1275 ((eq current-prefix-arg '-) "- ")
1276 ((and (consp current-prefix-arg)
1277 (eq (car current-prefix-arg) 4)) "C-u ")
1278 ((and (consp current-prefix-arg)
1279 (integerp (car current-prefix-arg)))
1280 (format "%d " (car current-prefix-arg)))
1281 ((integerp current-prefix-arg)
1282 (format "%d " current-prefix-arg)))
1283 ;; This isn't strictly correct if `execute-extended-command'
1284 ;; is bound to anything else (e.g. [menu]).
1285 ;; It could use (key-description (this-single-command-keys)),
1286 ;; but actually a prompt other than "M-x" would be confusing,
1287 ;; because "M-x" is a well-known prompt to read a command
1288 ;; and it serves as a shorthand for "Extended command: ".
1289 "M-x ")
1290 obarray 'commandp t nil 'extended-command-history)))
1293 (defvar minibuffer-history nil
1294 "Default minibuffer history list.
1295 This is used for all minibuffer input
1296 except when an alternate history list is specified.
1298 Maximum length of the history list is determined by the value
1299 of `history-length', which see.")
1300 (defvar minibuffer-history-sexp-flag nil
1301 "Control whether history list elements are expressions or strings.
1302 If the value of this variable equals current minibuffer depth,
1303 they are expressions; otherwise they are strings.
1304 \(That convention is designed to do the right thing for
1305 recursive uses of the minibuffer.)")
1306 (setq minibuffer-history-variable 'minibuffer-history)
1307 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1308 (defvar minibuffer-history-search-history nil)
1310 (defvar minibuffer-text-before-history nil
1311 "Text that was in this minibuffer before any history commands.
1312 This is nil if there have not yet been any history commands
1313 in this use of the minibuffer.")
1315 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1317 (defun minibuffer-history-initialize ()
1318 (setq minibuffer-text-before-history nil))
1320 (defun minibuffer-avoid-prompt (_new _old)
1321 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1322 (constrain-to-field nil (point-max)))
1324 (defcustom minibuffer-history-case-insensitive-variables nil
1325 "Minibuffer history variables for which matching should ignore case.
1326 If a history variable is a member of this list, then the
1327 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1328 commands ignore case when searching it, regardless of `case-fold-search'."
1329 :type '(repeat variable)
1330 :group 'minibuffer)
1332 (defun previous-matching-history-element (regexp n)
1333 "Find the previous history element that matches REGEXP.
1334 \(Previous history elements refer to earlier actions.)
1335 With prefix argument N, search for Nth previous match.
1336 If N is negative, find the next or Nth next match.
1337 Normally, history elements are matched case-insensitively if
1338 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1339 makes the search case-sensitive.
1340 See also `minibuffer-history-case-insensitive-variables'."
1341 (interactive
1342 (let* ((enable-recursive-minibuffers t)
1343 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1345 minibuffer-local-map
1347 'minibuffer-history-search-history
1348 (car minibuffer-history-search-history))))
1349 ;; Use the last regexp specified, by default, if input is empty.
1350 (list (if (string= regexp "")
1351 (if minibuffer-history-search-history
1352 (car minibuffer-history-search-history)
1353 (error "No previous history search regexp"))
1354 regexp)
1355 (prefix-numeric-value current-prefix-arg))))
1356 (unless (zerop n)
1357 (if (and (zerop minibuffer-history-position)
1358 (null minibuffer-text-before-history))
1359 (setq minibuffer-text-before-history
1360 (minibuffer-contents-no-properties)))
1361 (let ((history (symbol-value minibuffer-history-variable))
1362 (case-fold-search
1363 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1364 ;; On some systems, ignore case for file names.
1365 (if (memq minibuffer-history-variable
1366 minibuffer-history-case-insensitive-variables)
1368 ;; Respect the user's setting for case-fold-search:
1369 case-fold-search)
1370 nil))
1371 prevpos
1372 match-string
1373 match-offset
1374 (pos minibuffer-history-position))
1375 (while (/= n 0)
1376 (setq prevpos pos)
1377 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1378 (when (= pos prevpos)
1379 (error (if (= pos 1)
1380 "No later matching history item"
1381 "No earlier matching history item")))
1382 (setq match-string
1383 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1384 (let ((print-level nil))
1385 (prin1-to-string (nth (1- pos) history)))
1386 (nth (1- pos) history)))
1387 (setq match-offset
1388 (if (< n 0)
1389 (and (string-match regexp match-string)
1390 (match-end 0))
1391 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1392 (match-beginning 1))))
1393 (when match-offset
1394 (setq n (+ n (if (< n 0) 1 -1)))))
1395 (setq minibuffer-history-position pos)
1396 (goto-char (point-max))
1397 (delete-minibuffer-contents)
1398 (insert match-string)
1399 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1400 (if (memq (car (car command-history)) '(previous-matching-history-element
1401 next-matching-history-element))
1402 (setq command-history (cdr command-history))))
1404 (defun next-matching-history-element (regexp n)
1405 "Find the next history element that matches REGEXP.
1406 \(The next history element refers to a more recent action.)
1407 With prefix argument N, search for Nth next match.
1408 If N is negative, find the previous or Nth previous match.
1409 Normally, history elements are matched case-insensitively if
1410 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1411 makes the search case-sensitive."
1412 (interactive
1413 (let* ((enable-recursive-minibuffers t)
1414 (regexp (read-from-minibuffer "Next element matching (regexp): "
1416 minibuffer-local-map
1418 'minibuffer-history-search-history
1419 (car minibuffer-history-search-history))))
1420 ;; Use the last regexp specified, by default, if input is empty.
1421 (list (if (string= regexp "")
1422 (if minibuffer-history-search-history
1423 (car minibuffer-history-search-history)
1424 (error "No previous history search regexp"))
1425 regexp)
1426 (prefix-numeric-value current-prefix-arg))))
1427 (previous-matching-history-element regexp (- n)))
1429 (defvar minibuffer-temporary-goal-position nil)
1431 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1432 "Function run by `goto-history-element' before consuming default values.
1433 This is useful to dynamically add more elements to the list of default values
1434 when `goto-history-element' reaches the end of this list.
1435 Before calling this function `goto-history-element' sets the variable
1436 `minibuffer-default-add-done' to t, so it will call this function only
1437 once. In special cases, when this function needs to be called more
1438 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1439 overriding the setting of this variable to t in `goto-history-element'.")
1441 (defvar minibuffer-default-add-done nil
1442 "When nil, add more elements to the end of the list of default values.
1443 The value nil causes `goto-history-element' to add more elements to
1444 the list of defaults when it reaches the end of this list. It does
1445 this by calling a function defined by `minibuffer-default-add-function'.")
1447 (make-variable-buffer-local 'minibuffer-default-add-done)
1449 (defun minibuffer-default-add-completions ()
1450 "Return a list of all completions without the default value.
1451 This function is used to add all elements of the completion table to
1452 the end of the list of defaults just after the default value."
1453 (let ((def minibuffer-default)
1454 (all (all-completions ""
1455 minibuffer-completion-table
1456 minibuffer-completion-predicate)))
1457 (if (listp def)
1458 (append def all)
1459 (cons def (delete def all)))))
1461 (defun goto-history-element (nabs)
1462 "Puts element of the minibuffer history in the minibuffer.
1463 The argument NABS specifies the absolute history position."
1464 (interactive "p")
1465 (when (and (not minibuffer-default-add-done)
1466 (functionp minibuffer-default-add-function)
1467 (< nabs (- (if (listp minibuffer-default)
1468 (length minibuffer-default)
1469 1))))
1470 (setq minibuffer-default-add-done t
1471 minibuffer-default (funcall minibuffer-default-add-function)))
1472 (let ((minimum (if minibuffer-default
1473 (- (if (listp minibuffer-default)
1474 (length minibuffer-default)
1477 elt minibuffer-returned-to-present)
1478 (if (and (zerop minibuffer-history-position)
1479 (null minibuffer-text-before-history))
1480 (setq minibuffer-text-before-history
1481 (minibuffer-contents-no-properties)))
1482 (if (< nabs minimum)
1483 (if minibuffer-default
1484 (error "End of defaults; no next item")
1485 (error "End of history; no default available")))
1486 (if (> nabs (length (symbol-value minibuffer-history-variable)))
1487 (error "Beginning of history; no preceding item"))
1488 (unless (memq last-command '(next-history-element
1489 previous-history-element))
1490 (let ((prompt-end (minibuffer-prompt-end)))
1491 (set (make-local-variable 'minibuffer-temporary-goal-position)
1492 (cond ((<= (point) prompt-end) prompt-end)
1493 ((eobp) nil)
1494 (t (point))))))
1495 (goto-char (point-max))
1496 (delete-minibuffer-contents)
1497 (setq minibuffer-history-position nabs)
1498 (cond ((< nabs 0)
1499 (setq elt (if (listp minibuffer-default)
1500 (nth (1- (abs nabs)) minibuffer-default)
1501 minibuffer-default)))
1502 ((= nabs 0)
1503 (setq elt (or minibuffer-text-before-history ""))
1504 (setq minibuffer-returned-to-present t)
1505 (setq minibuffer-text-before-history nil))
1506 (t (setq elt (nth (1- minibuffer-history-position)
1507 (symbol-value minibuffer-history-variable)))))
1508 (insert
1509 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1510 (not minibuffer-returned-to-present))
1511 (let ((print-level nil))
1512 (prin1-to-string elt))
1513 elt))
1514 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
1516 (defun next-history-element (n)
1517 "Puts next element of the minibuffer history in the minibuffer.
1518 With argument N, it uses the Nth following element."
1519 (interactive "p")
1520 (or (zerop n)
1521 (goto-history-element (- minibuffer-history-position n))))
1523 (defun previous-history-element (n)
1524 "Puts previous element of the minibuffer history in the minibuffer.
1525 With argument N, it uses the Nth previous element."
1526 (interactive "p")
1527 (or (zerop n)
1528 (goto-history-element (+ minibuffer-history-position n))))
1530 (defun next-complete-history-element (n)
1531 "Get next history element which completes the minibuffer before the point.
1532 The contents of the minibuffer after the point are deleted, and replaced
1533 by the new completion."
1534 (interactive "p")
1535 (let ((point-at-start (point)))
1536 (next-matching-history-element
1537 (concat
1538 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1540 ;; next-matching-history-element always puts us at (point-min).
1541 ;; Move to the position we were at before changing the buffer contents.
1542 ;; This is still sensical, because the text before point has not changed.
1543 (goto-char point-at-start)))
1545 (defun previous-complete-history-element (n)
1547 Get previous history element which completes the minibuffer before the point.
1548 The contents of the minibuffer after the point are deleted, and replaced
1549 by the new completion."
1550 (interactive "p")
1551 (next-complete-history-element (- n)))
1553 ;; For compatibility with the old subr of the same name.
1554 (defun minibuffer-prompt-width ()
1555 "Return the display width of the minibuffer prompt.
1556 Return 0 if current buffer is not a minibuffer."
1557 ;; Return the width of everything before the field at the end of
1558 ;; the buffer; this should be 0 for normal buffers.
1559 (1- (minibuffer-prompt-end)))
1561 ;; isearch minibuffer history
1562 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
1564 (defvar minibuffer-history-isearch-message-overlay)
1565 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
1567 (defun minibuffer-history-isearch-setup ()
1568 "Set up a minibuffer for using isearch to search the minibuffer history.
1569 Intended to be added to `minibuffer-setup-hook'."
1570 (set (make-local-variable 'isearch-search-fun-function)
1571 'minibuffer-history-isearch-search)
1572 (set (make-local-variable 'isearch-message-function)
1573 'minibuffer-history-isearch-message)
1574 (set (make-local-variable 'isearch-wrap-function)
1575 'minibuffer-history-isearch-wrap)
1576 (set (make-local-variable 'isearch-push-state-function)
1577 'minibuffer-history-isearch-push-state)
1578 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
1580 (defun minibuffer-history-isearch-end ()
1581 "Clean up the minibuffer after terminating isearch in the minibuffer."
1582 (if minibuffer-history-isearch-message-overlay
1583 (delete-overlay minibuffer-history-isearch-message-overlay)))
1585 (defun minibuffer-history-isearch-search ()
1586 "Return the proper search function, for isearch in minibuffer history."
1587 (cond
1588 (isearch-word
1589 (if isearch-forward 'word-search-forward 'word-search-backward))
1591 (lambda (string bound noerror)
1592 (let ((search-fun
1593 ;; Use standard functions to search within minibuffer text
1594 (cond
1595 (isearch-regexp
1596 (if isearch-forward 're-search-forward 're-search-backward))
1598 (if isearch-forward 'search-forward 'search-backward))))
1599 found)
1600 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1601 ;; searching forward. Lazy-highlight calls this lambda with the
1602 ;; bound arg, so skip the minibuffer prompt.
1603 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
1604 (goto-char (minibuffer-prompt-end)))
1606 ;; 1. First try searching in the initial minibuffer text
1607 (funcall search-fun string
1608 (if isearch-forward bound (minibuffer-prompt-end))
1609 noerror)
1610 ;; 2. If the above search fails, start putting next/prev history
1611 ;; elements in the minibuffer successively, and search the string
1612 ;; in them. Do this only when bound is nil (i.e. not while
1613 ;; lazy-highlighting search strings in the current minibuffer text).
1614 (unless bound
1615 (condition-case nil
1616 (progn
1617 (while (not found)
1618 (cond (isearch-forward
1619 (next-history-element 1)
1620 (goto-char (minibuffer-prompt-end)))
1622 (previous-history-element 1)
1623 (goto-char (point-max))))
1624 (setq isearch-barrier (point) isearch-opoint (point))
1625 ;; After putting the next/prev history element, search
1626 ;; the string in them again, until next-history-element
1627 ;; or previous-history-element raises an error at the
1628 ;; beginning/end of history.
1629 (setq found (funcall search-fun string
1630 (unless isearch-forward
1631 ;; For backward search, don't search
1632 ;; in the minibuffer prompt
1633 (minibuffer-prompt-end))
1634 noerror)))
1635 ;; Return point of the new search result
1636 (point))
1637 ;; Return nil when next(prev)-history-element fails
1638 (error nil)))))))))
1640 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
1641 "Display the minibuffer history search prompt.
1642 If there are no search errors, this function displays an overlay with
1643 the isearch prompt which replaces the original minibuffer prompt.
1644 Otherwise, it displays the standard isearch message returned from
1645 `isearch-message'."
1646 (if (not (and (minibufferp) isearch-success (not isearch-error)))
1647 ;; Use standard function `isearch-message' when not in the minibuffer,
1648 ;; or search fails, or has an error (like incomplete regexp).
1649 ;; This function overwrites minibuffer text with isearch message,
1650 ;; so it's possible to see what is wrong in the search string.
1651 (isearch-message c-q-hack ellipsis)
1652 ;; Otherwise, put the overlay with the standard isearch prompt over
1653 ;; the initial minibuffer prompt.
1654 (if (overlayp minibuffer-history-isearch-message-overlay)
1655 (move-overlay minibuffer-history-isearch-message-overlay
1656 (point-min) (minibuffer-prompt-end))
1657 (setq minibuffer-history-isearch-message-overlay
1658 (make-overlay (point-min) (minibuffer-prompt-end)))
1659 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
1660 (overlay-put minibuffer-history-isearch-message-overlay
1661 'display (isearch-message-prefix c-q-hack ellipsis))
1662 ;; And clear any previous isearch message.
1663 (message "")))
1665 (defun minibuffer-history-isearch-wrap ()
1666 "Wrap the minibuffer history search when search fails.
1667 Move point to the first history element for a forward search,
1668 or to the last history element for a backward search."
1669 (unless isearch-word
1670 ;; When `minibuffer-history-isearch-search' fails on reaching the
1671 ;; beginning/end of the history, wrap the search to the first/last
1672 ;; minibuffer history element.
1673 (if isearch-forward
1674 (goto-history-element (length (symbol-value minibuffer-history-variable)))
1675 (goto-history-element 0))
1676 (setq isearch-success t))
1677 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
1679 (defun minibuffer-history-isearch-push-state ()
1680 "Save a function restoring the state of minibuffer history search.
1681 Save `minibuffer-history-position' to the additional state parameter
1682 in the search status stack."
1683 `(lambda (cmd)
1684 (minibuffer-history-isearch-pop-state cmd ,minibuffer-history-position)))
1686 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
1687 "Restore the minibuffer history search state.
1688 Go to the history element by the absolute history position HIST-POS."
1689 (goto-history-element hist-pos))
1692 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1693 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
1695 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1696 "Table mapping redo records to the corresponding undo one.
1697 A redo record for undo-in-region maps to t.
1698 A redo record for ordinary undo maps to the following (earlier) undo.")
1700 (defvar undo-in-region nil
1701 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1703 (defvar undo-no-redo nil
1704 "If t, `undo' doesn't go through redo entries.")
1706 (defvar pending-undo-list nil
1707 "Within a run of consecutive undo commands, list remaining to be undone.
1708 If t, we undid all the way to the end of it.")
1710 (defun undo (&optional arg)
1711 "Undo some previous changes.
1712 Repeat this command to undo more changes.
1713 A numeric ARG serves as a repeat count.
1715 In Transient Mark mode when the mark is active, only undo changes within
1716 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1717 as an argument limits undo to changes within the current region."
1718 (interactive "*P")
1719 ;; Make last-command indicate for the next command that this was an undo.
1720 ;; That way, another undo will undo more.
1721 ;; If we get to the end of the undo history and get an error,
1722 ;; another undo command will find the undo history empty
1723 ;; and will get another error. To begin undoing the undos,
1724 ;; you must type some other command.
1725 (let ((modified (buffer-modified-p))
1726 (recent-save (recent-auto-save-p))
1727 message)
1728 ;; If we get an error in undo-start,
1729 ;; the next command should not be a "consecutive undo".
1730 ;; So set `this-command' to something other than `undo'.
1731 (setq this-command 'undo-start)
1733 (unless (and (eq last-command 'undo)
1734 (or (eq pending-undo-list t)
1735 ;; If something (a timer or filter?) changed the buffer
1736 ;; since the previous command, don't continue the undo seq.
1737 (let ((list buffer-undo-list))
1738 (while (eq (car list) nil)
1739 (setq list (cdr list)))
1740 ;; If the last undo record made was made by undo
1741 ;; it shows nothing else happened in between.
1742 (gethash list undo-equiv-table))))
1743 (setq undo-in-region
1744 (or (region-active-p) (and arg (not (numberp arg)))))
1745 (if undo-in-region
1746 (undo-start (region-beginning) (region-end))
1747 (undo-start))
1748 ;; get rid of initial undo boundary
1749 (undo-more 1))
1750 ;; If we got this far, the next command should be a consecutive undo.
1751 (setq this-command 'undo)
1752 ;; Check to see whether we're hitting a redo record, and if
1753 ;; so, ask the user whether she wants to skip the redo/undo pair.
1754 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1755 (or (eq (selected-window) (minibuffer-window))
1756 (setq message (if undo-in-region
1757 (if equiv "Redo in region!" "Undo in region!")
1758 (if equiv "Redo!" "Undo!"))))
1759 (when (and (consp equiv) undo-no-redo)
1760 ;; The equiv entry might point to another redo record if we have done
1761 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1762 (while (let ((next (gethash equiv undo-equiv-table)))
1763 (if next (setq equiv next))))
1764 (setq pending-undo-list equiv)))
1765 (undo-more
1766 (if (numberp arg)
1767 (prefix-numeric-value arg)
1769 ;; Record the fact that the just-generated undo records come from an
1770 ;; undo operation--that is, they are redo records.
1771 ;; In the ordinary case (not within a region), map the redo
1772 ;; record to the following undos.
1773 ;; I don't know how to do that in the undo-in-region case.
1774 (let ((list buffer-undo-list))
1775 ;; Strip any leading undo boundaries there might be, like we do
1776 ;; above when checking.
1777 (while (eq (car list) nil)
1778 (setq list (cdr list)))
1779 (puthash list (if undo-in-region t pending-undo-list)
1780 undo-equiv-table))
1781 ;; Don't specify a position in the undo record for the undo command.
1782 ;; Instead, undoing this should move point to where the change is.
1783 (let ((tail buffer-undo-list)
1784 (prev nil))
1785 (while (car tail)
1786 (when (integerp (car tail))
1787 (let ((pos (car tail)))
1788 (if prev
1789 (setcdr prev (cdr tail))
1790 (setq buffer-undo-list (cdr tail)))
1791 (setq tail (cdr tail))
1792 (while (car tail)
1793 (if (eq pos (car tail))
1794 (if prev
1795 (setcdr prev (cdr tail))
1796 (setq buffer-undo-list (cdr tail)))
1797 (setq prev tail))
1798 (setq tail (cdr tail)))
1799 (setq tail nil)))
1800 (setq prev tail tail (cdr tail))))
1801 ;; Record what the current undo list says,
1802 ;; so the next command can tell if the buffer was modified in between.
1803 (and modified (not (buffer-modified-p))
1804 (delete-auto-save-file-if-necessary recent-save))
1805 ;; Display a message announcing success.
1806 (if message
1807 (message "%s" message))))
1809 (defun buffer-disable-undo (&optional buffer)
1810 "Make BUFFER stop keeping undo information.
1811 No argument or nil as argument means do this for the current buffer."
1812 (interactive)
1813 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
1814 (setq buffer-undo-list t)))
1816 (defun undo-only (&optional arg)
1817 "Undo some previous changes.
1818 Repeat this command to undo more changes.
1819 A numeric ARG serves as a repeat count.
1820 Contrary to `undo', this will not redo a previous undo."
1821 (interactive "*p")
1822 (let ((undo-no-redo t)) (undo arg)))
1824 (defvar undo-in-progress nil
1825 "Non-nil while performing an undo.
1826 Some change-hooks test this variable to do something different.")
1828 (defun undo-more (n)
1829 "Undo back N undo-boundaries beyond what was already undone recently.
1830 Call `undo-start' to get ready to undo recent changes,
1831 then call `undo-more' one or more times to undo them."
1832 (or (listp pending-undo-list)
1833 (error (concat "No further undo information"
1834 (and undo-in-region " for region"))))
1835 (let ((undo-in-progress t))
1836 ;; Note: The following, while pulling elements off
1837 ;; `pending-undo-list' will call primitive change functions which
1838 ;; will push more elements onto `buffer-undo-list'.
1839 (setq pending-undo-list (primitive-undo n pending-undo-list))
1840 (if (null pending-undo-list)
1841 (setq pending-undo-list t))))
1843 ;; Deep copy of a list
1844 (defun undo-copy-list (list)
1845 "Make a copy of undo list LIST."
1846 (mapcar 'undo-copy-list-1 list))
1848 (defun undo-copy-list-1 (elt)
1849 (if (consp elt)
1850 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1851 elt))
1853 (defun undo-start (&optional beg end)
1854 "Set `pending-undo-list' to the front of the undo list.
1855 The next call to `undo-more' will undo the most recently made change.
1856 If BEG and END are specified, then only undo elements
1857 that apply to text between BEG and END are used; other undo elements
1858 are ignored. If BEG and END are nil, all undo elements are used."
1859 (if (eq buffer-undo-list t)
1860 (error "No undo information in this buffer"))
1861 (setq pending-undo-list
1862 (if (and beg end (not (= beg end)))
1863 (undo-make-selective-list (min beg end) (max beg end))
1864 buffer-undo-list)))
1866 (defvar undo-adjusted-markers)
1868 (defun undo-make-selective-list (start end)
1869 "Return a list of undo elements for the region START to END.
1870 The elements come from `buffer-undo-list', but we keep only
1871 the elements inside this region, and discard those outside this region.
1872 If we find an element that crosses an edge of this region,
1873 we stop and ignore all further elements."
1874 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1875 (undo-list (list nil))
1876 undo-adjusted-markers
1877 some-rejected
1878 undo-elt temp-undo-list delta)
1879 (while undo-list-copy
1880 (setq undo-elt (car undo-list-copy))
1881 (let ((keep-this
1882 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1883 ;; This is a "was unmodified" element.
1884 ;; Keep it if we have kept everything thus far.
1885 (not some-rejected))
1887 (undo-elt-in-region undo-elt start end)))))
1888 (if keep-this
1889 (progn
1890 (setq end (+ end (cdr (undo-delta undo-elt))))
1891 ;; Don't put two nils together in the list
1892 (if (not (and (eq (car undo-list) nil)
1893 (eq undo-elt nil)))
1894 (setq undo-list (cons undo-elt undo-list))))
1895 (if (undo-elt-crosses-region undo-elt start end)
1896 (setq undo-list-copy nil)
1897 (setq some-rejected t)
1898 (setq temp-undo-list (cdr undo-list-copy))
1899 (setq delta (undo-delta undo-elt))
1901 (when (/= (cdr delta) 0)
1902 (let ((position (car delta))
1903 (offset (cdr delta)))
1905 ;; Loop down the earlier events adjusting their buffer
1906 ;; positions to reflect the fact that a change to the buffer
1907 ;; isn't being undone. We only need to process those element
1908 ;; types which undo-elt-in-region will return as being in
1909 ;; the region since only those types can ever get into the
1910 ;; output
1912 (while temp-undo-list
1913 (setq undo-elt (car temp-undo-list))
1914 (cond ((integerp undo-elt)
1915 (if (>= undo-elt position)
1916 (setcar temp-undo-list (- undo-elt offset))))
1917 ((atom undo-elt) nil)
1918 ((stringp (car undo-elt))
1919 ;; (TEXT . POSITION)
1920 (let ((text-pos (abs (cdr undo-elt)))
1921 (point-at-end (< (cdr undo-elt) 0 )))
1922 (if (>= text-pos position)
1923 (setcdr undo-elt (* (if point-at-end -1 1)
1924 (- text-pos offset))))))
1925 ((integerp (car undo-elt))
1926 ;; (BEGIN . END)
1927 (when (>= (car undo-elt) position)
1928 (setcar undo-elt (- (car undo-elt) offset))
1929 (setcdr undo-elt (- (cdr undo-elt) offset))))
1930 ((null (car undo-elt))
1931 ;; (nil PROPERTY VALUE BEG . END)
1932 (let ((tail (nthcdr 3 undo-elt)))
1933 (when (>= (car tail) position)
1934 (setcar tail (- (car tail) offset))
1935 (setcdr tail (- (cdr tail) offset))))))
1936 (setq temp-undo-list (cdr temp-undo-list))))))))
1937 (setq undo-list-copy (cdr undo-list-copy)))
1938 (nreverse undo-list)))
1940 (defun undo-elt-in-region (undo-elt start end)
1941 "Determine whether UNDO-ELT falls inside the region START ... END.
1942 If it crosses the edge, we return nil."
1943 (cond ((integerp undo-elt)
1944 (and (>= undo-elt start)
1945 (<= undo-elt end)))
1946 ((eq undo-elt nil)
1948 ((atom undo-elt)
1949 nil)
1950 ((stringp (car undo-elt))
1951 ;; (TEXT . POSITION)
1952 (and (>= (abs (cdr undo-elt)) start)
1953 (< (abs (cdr undo-elt)) end)))
1954 ((and (consp undo-elt) (markerp (car undo-elt)))
1955 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1956 ;; See if MARKER is inside the region.
1957 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1958 (unless alist-elt
1959 (setq alist-elt (cons (car undo-elt)
1960 (marker-position (car undo-elt))))
1961 (setq undo-adjusted-markers
1962 (cons alist-elt undo-adjusted-markers)))
1963 (and (cdr alist-elt)
1964 (>= (cdr alist-elt) start)
1965 (<= (cdr alist-elt) end))))
1966 ((null (car undo-elt))
1967 ;; (nil PROPERTY VALUE BEG . END)
1968 (let ((tail (nthcdr 3 undo-elt)))
1969 (and (>= (car tail) start)
1970 (<= (cdr tail) end))))
1971 ((integerp (car undo-elt))
1972 ;; (BEGIN . END)
1973 (and (>= (car undo-elt) start)
1974 (<= (cdr undo-elt) end)))))
1976 (defun undo-elt-crosses-region (undo-elt start end)
1977 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1978 This assumes we have already decided that UNDO-ELT
1979 is not *inside* the region START...END."
1980 (cond ((atom undo-elt) nil)
1981 ((null (car undo-elt))
1982 ;; (nil PROPERTY VALUE BEG . END)
1983 (let ((tail (nthcdr 3 undo-elt)))
1984 (and (< (car tail) end)
1985 (> (cdr tail) start))))
1986 ((integerp (car undo-elt))
1987 ;; (BEGIN . END)
1988 (and (< (car undo-elt) end)
1989 (> (cdr undo-elt) start)))))
1991 ;; Return the first affected buffer position and the delta for an undo element
1992 ;; delta is defined as the change in subsequent buffer positions if we *did*
1993 ;; the undo.
1994 (defun undo-delta (undo-elt)
1995 (if (consp undo-elt)
1996 (cond ((stringp (car undo-elt))
1997 ;; (TEXT . POSITION)
1998 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1999 ((integerp (car undo-elt))
2000 ;; (BEGIN . END)
2001 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2003 '(0 . 0)))
2004 '(0 . 0)))
2006 (defcustom undo-ask-before-discard nil
2007 "If non-nil ask about discarding undo info for the current command.
2008 Normally, Emacs discards the undo info for the current command if
2009 it exceeds `undo-outer-limit'. But if you set this option
2010 non-nil, it asks in the echo area whether to discard the info.
2011 If you answer no, there is a slight risk that Emacs might crash, so
2012 only do it if you really want to undo the command.
2014 This option is mainly intended for debugging. You have to be
2015 careful if you use it for other purposes. Garbage collection is
2016 inhibited while the question is asked, meaning that Emacs might
2017 leak memory. So you should make sure that you do not wait
2018 excessively long before answering the question."
2019 :type 'boolean
2020 :group 'undo
2021 :version "22.1")
2023 (defvar undo-extra-outer-limit nil
2024 "If non-nil, an extra level of size that's ok in an undo item.
2025 We don't ask the user about truncating the undo list until the
2026 current item gets bigger than this amount.
2028 This variable only matters if `undo-ask-before-discard' is non-nil.")
2029 (make-variable-buffer-local 'undo-extra-outer-limit)
2031 ;; When the first undo batch in an undo list is longer than
2032 ;; undo-outer-limit, this function gets called to warn the user that
2033 ;; the undo info for the current command was discarded. Garbage
2034 ;; collection is inhibited around the call, so it had better not do a
2035 ;; lot of consing.
2036 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2037 (defun undo-outer-limit-truncate (size)
2038 (if undo-ask-before-discard
2039 (when (or (null undo-extra-outer-limit)
2040 (> size undo-extra-outer-limit))
2041 ;; Don't ask the question again unless it gets even bigger.
2042 ;; This applies, in particular, if the user quits from the question.
2043 ;; Such a quit quits out of GC, but something else will call GC
2044 ;; again momentarily. It will call this function again,
2045 ;; but we don't want to ask the question again.
2046 (setq undo-extra-outer-limit (+ size 50000))
2047 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2048 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2049 (buffer-name) size)))
2050 (progn (setq buffer-undo-list nil)
2051 (setq undo-extra-outer-limit nil)
2053 nil))
2054 (display-warning '(undo discard-info)
2055 (concat
2056 (format "Buffer `%s' undo info was %d bytes long.\n"
2057 (buffer-name) size)
2058 "The undo info was discarded because it exceeded \
2059 `undo-outer-limit'.
2061 This is normal if you executed a command that made a huge change
2062 to the buffer. In that case, to prevent similar problems in the
2063 future, set `undo-outer-limit' to a value that is large enough to
2064 cover the maximum size of normal changes you expect a single
2065 command to make, but not so large that it might exceed the
2066 maximum memory allotted to Emacs.
2068 If you did not execute any such command, the situation is
2069 probably due to a bug and you should report it.
2071 You can disable the popping up of this buffer by adding the entry
2072 \(undo discard-info) to the user option `warning-suppress-types',
2073 which is defined in the `warnings' library.\n")
2074 :warning)
2075 (setq buffer-undo-list nil)
2078 (defvar shell-command-history nil
2079 "History list for some commands that read shell commands.
2081 Maximum length of the history list is determined by the value
2082 of `history-length', which see.")
2084 (defvar shell-command-switch (purecopy "-c")
2085 "Switch used to have the shell execute its command line argument.")
2087 (defvar shell-command-default-error-buffer nil
2088 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
2089 This buffer is used when `shell-command' or `shell-command-on-region'
2090 is run interactively. A value of nil means that output to stderr and
2091 stdout will be intermixed in the output stream.")
2093 (declare-function mailcap-file-default-commands "mailcap" (files))
2094 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2096 (defun minibuffer-default-add-shell-commands ()
2097 "Return a list of all commands associated with the current file.
2098 This function is used to add all related commands retrieved by `mailcap'
2099 to the end of the list of defaults just after the default value."
2100 (interactive)
2101 (let* ((filename (if (listp minibuffer-default)
2102 (car minibuffer-default)
2103 minibuffer-default))
2104 (commands (and filename (require 'mailcap nil t)
2105 (mailcap-file-default-commands (list filename)))))
2106 (setq commands (mapcar (lambda (command)
2107 (concat command " " filename))
2108 commands))
2109 (if (listp minibuffer-default)
2110 (append minibuffer-default commands)
2111 (cons minibuffer-default commands))))
2113 (declare-function shell-completion-vars "shell" ())
2115 (defvar minibuffer-local-shell-command-map
2116 (let ((map (make-sparse-keymap)))
2117 (set-keymap-parent map minibuffer-local-map)
2118 (define-key map "\t" 'completion-at-point)
2119 map)
2120 "Keymap used for completing shell commands in minibuffer.")
2122 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
2123 "Read a shell command from the minibuffer.
2124 The arguments are the same as the ones of `read-from-minibuffer',
2125 except READ and KEYMAP are missing and HIST defaults
2126 to `shell-command-history'."
2127 (require 'shell)
2128 (minibuffer-with-setup-hook
2129 (lambda ()
2130 (shell-completion-vars)
2131 (set (make-local-variable 'minibuffer-default-add-function)
2132 'minibuffer-default-add-shell-commands))
2133 (apply 'read-from-minibuffer prompt initial-contents
2134 minibuffer-local-shell-command-map
2136 (or hist 'shell-command-history)
2137 args)))
2139 (defun async-shell-command (command &optional output-buffer error-buffer)
2140 "Execute string COMMAND asynchronously in background.
2142 Like `shell-command' but if COMMAND doesn't end in ampersand, adds `&'
2143 surrounded by whitespace and executes the command asynchronously.
2144 The output appears in the buffer `*Async Shell Command*'.
2146 In Elisp, you will often be better served by calling `start-process'
2147 directly, since it offers more control and does not impose the use of a
2148 shell (with its need to quote arguments)."
2149 (interactive
2150 (list
2151 (read-shell-command "Async shell command: " nil nil
2152 (and buffer-file-name
2153 (file-relative-name buffer-file-name)))
2154 current-prefix-arg
2155 shell-command-default-error-buffer))
2156 (unless (string-match "&[ \t]*\\'" command)
2157 (setq command (concat command " &")))
2158 (shell-command command output-buffer error-buffer))
2160 (defun shell-command (command &optional output-buffer error-buffer)
2161 "Execute string COMMAND in inferior shell; display output, if any.
2162 With prefix argument, insert the COMMAND's output at point.
2164 If COMMAND ends in ampersand, execute it asynchronously.
2165 The output appears in the buffer `*Async Shell Command*'.
2166 That buffer is in shell mode.
2168 Otherwise, COMMAND is executed synchronously. The output appears in
2169 the buffer `*Shell Command Output*'. If the output is short enough to
2170 display in the echo area (which is determined by the variables
2171 `resize-mini-windows' and `max-mini-window-height'), it is shown
2172 there, but it is nonetheless available in buffer `*Shell Command
2173 Output*' even though that buffer is not automatically displayed.
2175 To specify a coding system for converting non-ASCII characters
2176 in the shell command output, use \\[universal-coding-system-argument] \
2177 before this command.
2179 Noninteractive callers can specify coding systems by binding
2180 `coding-system-for-read' and `coding-system-for-write'.
2182 The optional second argument OUTPUT-BUFFER, if non-nil,
2183 says to put the output in some other buffer.
2184 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2185 If OUTPUT-BUFFER is not a buffer and not nil,
2186 insert output in current buffer. (This cannot be done asynchronously.)
2187 In either case, the buffer is first erased, and the output is
2188 inserted after point (leaving mark after it).
2190 If the command terminates without error, but generates output,
2191 and you did not specify \"insert it in the current buffer\",
2192 the output can be displayed in the echo area or in its buffer.
2193 If the output is short enough to display in the echo area
2194 \(determined by the variable `max-mini-window-height' if
2195 `resize-mini-windows' is non-nil), it is shown there.
2196 Otherwise,the buffer containing the output is displayed.
2198 If there is output and an error, and you did not specify \"insert it
2199 in the current buffer\", a message about the error goes at the end
2200 of the output.
2202 If there is no output, or if output is inserted in the current buffer,
2203 then `*Shell Command Output*' is deleted.
2205 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2206 or buffer name to which to direct the command's standard error output.
2207 If it is nil, error output is mingled with regular output.
2208 In an interactive call, the variable `shell-command-default-error-buffer'
2209 specifies the value of ERROR-BUFFER.
2211 In Elisp, you will often be better served by calling `call-process' or
2212 `start-process' directly, since it offers more control and does not impose
2213 the use of a shell (with its need to quote arguments)."
2215 (interactive
2216 (list
2217 (read-shell-command "Shell command: " nil nil
2218 (let ((filename
2219 (cond
2220 (buffer-file-name)
2221 ((eq major-mode 'dired-mode)
2222 (dired-get-filename nil t)))))
2223 (and filename (file-relative-name filename))))
2224 current-prefix-arg
2225 shell-command-default-error-buffer))
2226 ;; Look for a handler in case default-directory is a remote file name.
2227 (let ((handler
2228 (find-file-name-handler (directory-file-name default-directory)
2229 'shell-command)))
2230 (if handler
2231 (funcall handler 'shell-command command output-buffer error-buffer)
2232 (if (and output-buffer
2233 (not (or (bufferp output-buffer) (stringp output-buffer))))
2234 ;; Output goes in current buffer.
2235 (let ((error-file
2236 (if error-buffer
2237 (make-temp-file
2238 (expand-file-name "scor"
2239 (or small-temporary-file-directory
2240 temporary-file-directory)))
2241 nil)))
2242 (barf-if-buffer-read-only)
2243 (push-mark nil t)
2244 ;; We do not use -f for csh; we will not support broken use of
2245 ;; .cshrcs. Even the BSD csh manual says to use
2246 ;; "if ($?prompt) exit" before things which are not useful
2247 ;; non-interactively. Besides, if someone wants their other
2248 ;; aliases for shell commands then they can still have them.
2249 (call-process shell-file-name nil
2250 (if error-file
2251 (list t error-file)
2253 nil shell-command-switch command)
2254 (when (and error-file (file-exists-p error-file))
2255 (if (< 0 (nth 7 (file-attributes error-file)))
2256 (with-current-buffer (get-buffer-create error-buffer)
2257 (let ((pos-from-end (- (point-max) (point))))
2258 (or (bobp)
2259 (insert "\f\n"))
2260 ;; Do no formatting while reading error file,
2261 ;; because that can run a shell command, and we
2262 ;; don't want that to cause an infinite recursion.
2263 (format-insert-file error-file nil)
2264 ;; Put point after the inserted errors.
2265 (goto-char (- (point-max) pos-from-end)))
2266 (display-buffer (current-buffer))))
2267 (delete-file error-file))
2268 ;; This is like exchange-point-and-mark, but doesn't
2269 ;; activate the mark. It is cleaner to avoid activation,
2270 ;; even though the command loop would deactivate the mark
2271 ;; because we inserted text.
2272 (goto-char (prog1 (mark t)
2273 (set-marker (mark-marker) (point)
2274 (current-buffer)))))
2275 ;; Output goes in a separate buffer.
2276 ;; Preserve the match data in case called from a program.
2277 (save-match-data
2278 (if (string-match "[ \t]*&[ \t]*\\'" command)
2279 ;; Command ending with ampersand means asynchronous.
2280 (let ((buffer (get-buffer-create
2281 (or output-buffer "*Async Shell Command*")))
2282 (directory default-directory)
2283 proc)
2284 ;; Remove the ampersand.
2285 (setq command (substring command 0 (match-beginning 0)))
2286 ;; If will kill a process, query first.
2287 (setq proc (get-buffer-process buffer))
2288 (if proc
2289 (if (yes-or-no-p "A command is running. Kill it? ")
2290 (kill-process proc)
2291 (error "Shell command in progress")))
2292 (with-current-buffer buffer
2293 (setq buffer-read-only nil)
2294 ;; Setting buffer-read-only to nil doesn't suffice
2295 ;; if some text has a non-nil read-only property,
2296 ;; which comint sometimes adds for prompts.
2297 (let ((inhibit-read-only t))
2298 (erase-buffer))
2299 (display-buffer buffer)
2300 (setq default-directory directory)
2301 (setq proc (start-process "Shell" buffer shell-file-name
2302 shell-command-switch command))
2303 (setq mode-line-process '(":%s"))
2304 (require 'shell) (shell-mode)
2305 (set-process-sentinel proc 'shell-command-sentinel)
2306 ;; Use the comint filter for proper handling of carriage motion
2307 ;; (see `comint-inhibit-carriage-motion'),.
2308 (set-process-filter proc 'comint-output-filter)
2310 ;; Otherwise, command is executed synchronously.
2311 (shell-command-on-region (point) (point) command
2312 output-buffer nil error-buffer)))))))
2314 (defun display-message-or-buffer (message
2315 &optional buffer-name not-this-window ignore)
2316 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2317 MESSAGE may be either a string or a buffer.
2319 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2320 the maximum height of the echo area, as defined by `max-mini-window-height'
2321 if `resize-mini-windows' is non-nil.
2323 Returns either the string shown in the echo area, or when a pop-up
2324 buffer is used, the window used to display it.
2326 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2327 name of the buffer used to display it in the case where a pop-up buffer
2328 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2329 string and it is displayed in the echo area, it is not specified whether
2330 the contents are inserted into the buffer anyway.
2332 Optional argument NOT-THIS-WINDOW is as for `display-buffer', and
2333 only used if a buffer is displayed. Optional argument IGNORE is
2334 ignored."
2335 (cond ((and (stringp message) (not (string-match "\n" message)))
2336 ;; Trivial case where we can use the echo area
2337 (message "%s" message))
2338 ((and (stringp message)
2339 (= (string-match "\n" message) (1- (length message))))
2340 ;; Trivial case where we can just remove single trailing newline
2341 (message "%s" (substring message 0 (1- (length message)))))
2343 ;; General case
2344 (with-current-buffer
2345 (if (bufferp message)
2346 message
2347 (get-buffer-create (or buffer-name "*Message*")))
2349 (unless (bufferp message)
2350 (erase-buffer)
2351 (insert message))
2353 (let ((lines
2354 (if (= (buffer-size) 0)
2356 (count-screen-lines nil nil nil (minibuffer-window)))))
2357 (cond ((= lines 0))
2358 ((and (or (<= lines 1)
2359 (<= lines
2360 (if resize-mini-windows
2361 (cond ((floatp max-mini-window-height)
2362 (* (frame-height)
2363 max-mini-window-height))
2364 ((integerp max-mini-window-height)
2365 max-mini-window-height)
2368 1)))
2369 ;; Don't use the echo area if the output buffer is
2370 ;; already dispayed in the selected frame.
2371 (not (get-buffer-window (current-buffer))))
2372 ;; Echo area
2373 (goto-char (point-max))
2374 (when (bolp)
2375 (backward-char 1))
2376 (message "%s" (buffer-substring (point-min) (point))))
2378 ;; Buffer
2379 (goto-char (point-min))
2380 (display-buffer nil not-this-window))))))))
2383 ;; We have a sentinel to prevent insertion of a termination message
2384 ;; in the buffer itself.
2385 (defun shell-command-sentinel (process signal)
2386 (if (memq (process-status process) '(exit signal))
2387 (message "%s: %s."
2388 (car (cdr (cdr (process-command process))))
2389 (substring signal 0 -1))))
2391 (defun shell-command-on-region (start end command
2392 &optional output-buffer replace
2393 error-buffer display-error-buffer)
2394 "Execute string COMMAND in inferior shell with region as input.
2395 Normally display output (if any) in temp buffer `*Shell Command Output*';
2396 Prefix arg means replace the region with it. Return the exit code of
2397 COMMAND.
2399 To specify a coding system for converting non-ASCII characters
2400 in the input and output to the shell command, use \\[universal-coding-system-argument]
2401 before this command. By default, the input (from the current buffer)
2402 is encoded in the same coding system that will be used to save the file,
2403 `buffer-file-coding-system'. If the output is going to replace the region,
2404 then it is decoded from that same coding system.
2406 The noninteractive arguments are START, END, COMMAND,
2407 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2408 Noninteractive callers can specify coding systems by binding
2409 `coding-system-for-read' and `coding-system-for-write'.
2411 If the command generates output, the output may be displayed
2412 in the echo area or in a buffer.
2413 If the output is short enough to display in the echo area
2414 \(determined by the variable `max-mini-window-height' if
2415 `resize-mini-windows' is non-nil), it is shown there. Otherwise
2416 it is displayed in the buffer `*Shell Command Output*'. The output
2417 is available in that buffer in both cases.
2419 If there is output and an error, a message about the error
2420 appears at the end of the output.
2422 If there is no output, or if output is inserted in the current buffer,
2423 then `*Shell Command Output*' is deleted.
2425 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2426 that says to put the output in some other buffer.
2427 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2428 If OUTPUT-BUFFER is not a buffer and not nil,
2429 insert output in the current buffer.
2430 In either case, the output is inserted after point (leaving mark after it).
2432 If REPLACE, the optional fifth argument, is non-nil, that means insert
2433 the output in place of text from START to END, putting point and mark
2434 around it.
2436 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2437 or buffer name to which to direct the command's standard error output.
2438 If it is nil, error output is mingled with regular output.
2439 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2440 were any errors. (This is always t, interactively.)
2441 In an interactive call, the variable `shell-command-default-error-buffer'
2442 specifies the value of ERROR-BUFFER."
2443 (interactive (let (string)
2444 (unless (mark)
2445 (error "The mark is not set now, so there is no region"))
2446 ;; Do this before calling region-beginning
2447 ;; and region-end, in case subprocess output
2448 ;; relocates them while we are in the minibuffer.
2449 (setq string (read-shell-command "Shell command on region: "))
2450 ;; call-interactively recognizes region-beginning and
2451 ;; region-end specially, leaving them in the history.
2452 (list (region-beginning) (region-end)
2453 string
2454 current-prefix-arg
2455 current-prefix-arg
2456 shell-command-default-error-buffer
2457 t)))
2458 (let ((error-file
2459 (if error-buffer
2460 (make-temp-file
2461 (expand-file-name "scor"
2462 (or small-temporary-file-directory
2463 temporary-file-directory)))
2464 nil))
2465 exit-status)
2466 (if (or replace
2467 (and output-buffer
2468 (not (or (bufferp output-buffer) (stringp output-buffer)))))
2469 ;; Replace specified region with output from command.
2470 (let ((swap (and replace (< start end))))
2471 ;; Don't muck with mark unless REPLACE says we should.
2472 (goto-char start)
2473 (and replace (push-mark (point) 'nomsg))
2474 (setq exit-status
2475 (call-process-region start end shell-file-name t
2476 (if error-file
2477 (list t error-file)
2479 nil shell-command-switch command))
2480 ;; It is rude to delete a buffer which the command is not using.
2481 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2482 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2483 ;; (kill-buffer shell-buffer)))
2484 ;; Don't muck with mark unless REPLACE says we should.
2485 (and replace swap (exchange-point-and-mark)))
2486 ;; No prefix argument: put the output in a temp buffer,
2487 ;; replacing its entire contents.
2488 (let ((buffer (get-buffer-create
2489 (or output-buffer "*Shell Command Output*"))))
2490 (unwind-protect
2491 (if (eq buffer (current-buffer))
2492 ;; If the input is the same buffer as the output,
2493 ;; delete everything but the specified region,
2494 ;; then replace that region with the output.
2495 (progn (setq buffer-read-only nil)
2496 (delete-region (max start end) (point-max))
2497 (delete-region (point-min) (min start end))
2498 (setq exit-status
2499 (call-process-region (point-min) (point-max)
2500 shell-file-name t
2501 (if error-file
2502 (list t error-file)
2504 nil shell-command-switch
2505 command)))
2506 ;; Clear the output buffer, then run the command with
2507 ;; output there.
2508 (let ((directory default-directory))
2509 (with-current-buffer buffer
2510 (setq buffer-read-only nil)
2511 (if (not output-buffer)
2512 (setq default-directory directory))
2513 (erase-buffer)))
2514 (setq exit-status
2515 (call-process-region start end shell-file-name nil
2516 (if error-file
2517 (list buffer error-file)
2518 buffer)
2519 nil shell-command-switch command)))
2520 ;; Report the output.
2521 (with-current-buffer buffer
2522 (setq mode-line-process
2523 (cond ((null exit-status)
2524 " - Error")
2525 ((stringp exit-status)
2526 (format " - Signal [%s]" exit-status))
2527 ((not (equal 0 exit-status))
2528 (format " - Exit [%d]" exit-status)))))
2529 (if (with-current-buffer buffer (> (point-max) (point-min)))
2530 ;; There's some output, display it
2531 (display-message-or-buffer buffer)
2532 ;; No output; error?
2533 (let ((output
2534 (if (and error-file
2535 (< 0 (nth 7 (file-attributes error-file))))
2536 "some error output"
2537 "no output")))
2538 (cond ((null exit-status)
2539 (message "(Shell command failed with error)"))
2540 ((equal 0 exit-status)
2541 (message "(Shell command succeeded with %s)"
2542 output))
2543 ((stringp exit-status)
2544 (message "(Shell command killed by signal %s)"
2545 exit-status))
2547 (message "(Shell command failed with code %d and %s)"
2548 exit-status output))))
2549 ;; Don't kill: there might be useful info in the undo-log.
2550 ;; (kill-buffer buffer)
2551 ))))
2553 (when (and error-file (file-exists-p error-file))
2554 (if (< 0 (nth 7 (file-attributes error-file)))
2555 (with-current-buffer (get-buffer-create error-buffer)
2556 (let ((pos-from-end (- (point-max) (point))))
2557 (or (bobp)
2558 (insert "\f\n"))
2559 ;; Do no formatting while reading error file,
2560 ;; because that can run a shell command, and we
2561 ;; don't want that to cause an infinite recursion.
2562 (format-insert-file error-file nil)
2563 ;; Put point after the inserted errors.
2564 (goto-char (- (point-max) pos-from-end)))
2565 (and display-error-buffer
2566 (display-buffer (current-buffer)))))
2567 (delete-file error-file))
2568 exit-status))
2570 (defun shell-command-to-string (command)
2571 "Execute shell command COMMAND and return its output as a string."
2572 (with-output-to-string
2573 (with-current-buffer
2574 standard-output
2575 (process-file shell-file-name nil t nil shell-command-switch command))))
2577 (defun process-file (program &optional infile buffer display &rest args)
2578 "Process files synchronously in a separate process.
2579 Similar to `call-process', but may invoke a file handler based on
2580 `default-directory'. The current working directory of the
2581 subprocess is `default-directory'.
2583 File names in INFILE and BUFFER are handled normally, but file
2584 names in ARGS should be relative to `default-directory', as they
2585 are passed to the process verbatim. \(This is a difference to
2586 `call-process' which does not support file handlers for INFILE
2587 and BUFFER.\)
2589 Some file handlers might not support all variants, for example
2590 they might behave as if DISPLAY was nil, regardless of the actual
2591 value passed."
2592 (let ((fh (find-file-name-handler default-directory 'process-file))
2593 lc stderr-file)
2594 (unwind-protect
2595 (if fh (apply fh 'process-file program infile buffer display args)
2596 (when infile (setq lc (file-local-copy infile)))
2597 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
2598 (make-temp-file "emacs")))
2599 (prog1
2600 (apply 'call-process program
2601 (or lc infile)
2602 (if stderr-file (list (car buffer) stderr-file) buffer)
2603 display args)
2604 (when stderr-file (copy-file stderr-file (cadr buffer)))))
2605 (when stderr-file (delete-file stderr-file))
2606 (when lc (delete-file lc)))))
2608 (defvar process-file-side-effects t
2609 "Whether a call of `process-file' changes remote files.
2611 Per default, this variable is always set to `t', meaning that a
2612 call of `process-file' could potentially change any file on a
2613 remote host. When set to `nil', a file handler could optimize
2614 its behaviour with respect to remote file attributes caching.
2616 This variable should never be changed by `setq'. Instead of, it
2617 shall be set only by let-binding.")
2619 (defun start-file-process (name buffer program &rest program-args)
2620 "Start a program in a subprocess. Return the process object for it.
2622 Similar to `start-process', but may invoke a file handler based on
2623 `default-directory'. See Info node `(elisp)Magic File Names'.
2625 This handler ought to run PROGRAM, perhaps on the local host,
2626 perhaps on a remote host that corresponds to `default-directory'.
2627 In the latter case, the local part of `default-directory' becomes
2628 the working directory of the process.
2630 PROGRAM and PROGRAM-ARGS might be file names. They are not
2631 objects of file handler invocation. File handlers might not
2632 support pty association, if PROGRAM is nil."
2633 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
2634 (if fh (apply fh 'start-file-process name buffer program program-args)
2635 (apply 'start-process name buffer program program-args))))
2637 ;;;; Process menu
2639 (defvar tabulated-list-format)
2640 (defvar tabulated-list-entries)
2641 (defvar tabulated-list-sort-key)
2642 (declare-function tabulated-list-init-header "tabulated-list" ())
2643 (declare-function tabulated-list-print "tabulated-list"
2644 (&optional remember-pos))
2646 (defvar process-menu-query-only nil)
2648 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
2649 "Major mode for listing the processes called by Emacs."
2650 (setq tabulated-list-format [("Process" 15 t)
2651 ("Status" 7 t)
2652 ("Buffer" 15 t)
2653 ("TTY" 12 t)
2654 ("Command" 0 t)])
2655 (make-local-variable 'process-menu-query-only)
2656 (setq tabulated-list-sort-key (cons "Process" nil))
2657 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
2658 (tabulated-list-init-header))
2660 (defun list-processes--refresh ()
2661 "Recompute the list of processes for the Process List buffer."
2662 (setq tabulated-list-entries nil)
2663 (dolist (p (process-list))
2664 (when (or (not process-menu-query-only)
2665 (process-query-on-exit-flag p))
2666 (let* ((buf (process-buffer p))
2667 (type (process-type p))
2668 (name (process-name p))
2669 (status (symbol-name (process-status p)))
2670 (buf-label (if (buffer-live-p buf)
2671 `(,(buffer-name buf)
2672 face link
2673 help-echo ,(concat "Visit buffer `"
2674 (buffer-name buf) "'")
2675 follow-link t
2676 process-buffer ,buf
2677 action process-menu-visit-buffer)
2678 "--"))
2679 (tty (or (process-tty-name p) "--"))
2680 (cmd
2681 (if (memq type '(network serial))
2682 (let ((contact (process-contact p t)))
2683 (if (eq type 'network)
2684 (format "(%s %s)"
2685 (if (plist-get contact :type)
2686 "datagram"
2687 "network")
2688 (if (plist-get contact :server)
2689 (format "server on %s"
2690 (plist-get contact :server))
2691 (format "connection to %s"
2692 (plist-get contact :host))))
2693 (format "(serial port %s%s)"
2694 (or (plist-get contact :port) "?")
2695 (let ((speed (plist-get contact :speed)))
2696 (if speed
2697 (format " at %s b/s" speed)
2698 "")))))
2699 (mapconcat 'identity (process-command p) " "))))
2700 (push (list p (vector name status buf-label tty cmd))
2701 tabulated-list-entries)))))
2703 (defun process-menu-visit-buffer (button)
2704 (display-buffer (button-get button 'process-buffer)))
2706 (defun list-processes (&optional query-only buffer)
2707 "Display a list of all processes.
2708 If optional argument QUERY-ONLY is non-nil, only processes with
2709 the query-on-exit flag set are listed.
2710 Any process listed as exited or signaled is actually eliminated
2711 after the listing is made.
2712 Optional argument BUFFER specifies a buffer to use, instead of
2713 \"*Process List\".
2714 The return value is always nil."
2715 (interactive)
2716 (or (fboundp 'process-list)
2717 (error "Asynchronous subprocesses are not supported on this system"))
2718 (unless (bufferp buffer)
2719 (setq buffer (get-buffer-create "*Process List*")))
2720 (with-current-buffer buffer
2721 (process-menu-mode)
2722 (setq process-menu-query-only query-only)
2723 (list-processes--refresh)
2724 (tabulated-list-print))
2725 (display-buffer buffer)
2726 nil)
2728 (defvar universal-argument-map
2729 (let ((map (make-sparse-keymap)))
2730 (define-key map [t] 'universal-argument-other-key)
2731 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2732 (define-key map [switch-frame] nil)
2733 (define-key map [?\C-u] 'universal-argument-more)
2734 (define-key map [?-] 'universal-argument-minus)
2735 (define-key map [?0] 'digit-argument)
2736 (define-key map [?1] 'digit-argument)
2737 (define-key map [?2] 'digit-argument)
2738 (define-key map [?3] 'digit-argument)
2739 (define-key map [?4] 'digit-argument)
2740 (define-key map [?5] 'digit-argument)
2741 (define-key map [?6] 'digit-argument)
2742 (define-key map [?7] 'digit-argument)
2743 (define-key map [?8] 'digit-argument)
2744 (define-key map [?9] 'digit-argument)
2745 (define-key map [kp-0] 'digit-argument)
2746 (define-key map [kp-1] 'digit-argument)
2747 (define-key map [kp-2] 'digit-argument)
2748 (define-key map [kp-3] 'digit-argument)
2749 (define-key map [kp-4] 'digit-argument)
2750 (define-key map [kp-5] 'digit-argument)
2751 (define-key map [kp-6] 'digit-argument)
2752 (define-key map [kp-7] 'digit-argument)
2753 (define-key map [kp-8] 'digit-argument)
2754 (define-key map [kp-9] 'digit-argument)
2755 (define-key map [kp-subtract] 'universal-argument-minus)
2756 map)
2757 "Keymap used while processing \\[universal-argument].")
2759 (defvar universal-argument-num-events nil
2760 "Number of argument-specifying events read by `universal-argument'.
2761 `universal-argument-other-key' uses this to discard those events
2762 from (this-command-keys), and reread only the final command.")
2764 (defvar overriding-map-is-bound nil
2765 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2767 (defvar saved-overriding-map nil
2768 "The saved value of `overriding-terminal-local-map'.
2769 That variable gets restored to this value on exiting \"universal
2770 argument mode\".")
2772 (defun ensure-overriding-map-is-bound ()
2773 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2774 (unless overriding-map-is-bound
2775 (setq saved-overriding-map overriding-terminal-local-map)
2776 (setq overriding-terminal-local-map universal-argument-map)
2777 (setq overriding-map-is-bound t)))
2779 (defun restore-overriding-map ()
2780 "Restore `overriding-terminal-local-map' to its saved value."
2781 (setq overriding-terminal-local-map saved-overriding-map)
2782 (setq overriding-map-is-bound nil))
2784 (defun universal-argument ()
2785 "Begin a numeric argument for the following command.
2786 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2787 \\[universal-argument] following the digits or minus sign ends the argument.
2788 \\[universal-argument] without digits or minus sign provides 4 as argument.
2789 Repeating \\[universal-argument] without digits or minus sign
2790 multiplies the argument by 4 each time.
2791 For some commands, just \\[universal-argument] by itself serves as a flag
2792 which is different in effect from any particular numeric argument.
2793 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2794 (interactive)
2795 (setq prefix-arg (list 4))
2796 (setq universal-argument-num-events (length (this-command-keys)))
2797 (ensure-overriding-map-is-bound))
2799 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2800 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2801 (defun universal-argument-more (arg)
2802 (interactive "P")
2803 (if (consp arg)
2804 (setq prefix-arg (list (* 4 (car arg))))
2805 (if (eq arg '-)
2806 (setq prefix-arg (list -4))
2807 (setq prefix-arg arg)
2808 (restore-overriding-map)))
2809 (setq universal-argument-num-events (length (this-command-keys))))
2811 (defun negative-argument (arg)
2812 "Begin a negative numeric argument for the next command.
2813 \\[universal-argument] following digits or minus sign ends the argument."
2814 (interactive "P")
2815 (cond ((integerp arg)
2816 (setq prefix-arg (- arg)))
2817 ((eq arg '-)
2818 (setq prefix-arg nil))
2820 (setq prefix-arg '-)))
2821 (setq universal-argument-num-events (length (this-command-keys)))
2822 (ensure-overriding-map-is-bound))
2824 (defun digit-argument (arg)
2825 "Part of the numeric argument for the next command.
2826 \\[universal-argument] following digits or minus sign ends the argument."
2827 (interactive "P")
2828 (let* ((char (if (integerp last-command-event)
2829 last-command-event
2830 (get last-command-event 'ascii-character)))
2831 (digit (- (logand char ?\177) ?0)))
2832 (cond ((integerp arg)
2833 (setq prefix-arg (+ (* arg 10)
2834 (if (< arg 0) (- digit) digit))))
2835 ((eq arg '-)
2836 ;; Treat -0 as just -, so that -01 will work.
2837 (setq prefix-arg (if (zerop digit) '- (- digit))))
2839 (setq prefix-arg digit))))
2840 (setq universal-argument-num-events (length (this-command-keys)))
2841 (ensure-overriding-map-is-bound))
2843 ;; For backward compatibility, minus with no modifiers is an ordinary
2844 ;; command if digits have already been entered.
2845 (defun universal-argument-minus (arg)
2846 (interactive "P")
2847 (if (integerp arg)
2848 (universal-argument-other-key arg)
2849 (negative-argument arg)))
2851 ;; Anything else terminates the argument and is left in the queue to be
2852 ;; executed as a command.
2853 (defun universal-argument-other-key (arg)
2854 (interactive "P")
2855 (setq prefix-arg arg)
2856 (let* ((key (this-command-keys))
2857 (keylist (listify-key-sequence key)))
2858 (setq unread-command-events
2859 (append (nthcdr universal-argument-num-events keylist)
2860 unread-command-events)))
2861 (reset-this-command-lengths)
2862 (restore-overriding-map))
2865 (defvar filter-buffer-substring-functions nil
2866 "Wrapper hook around `filter-buffer-substring'.
2867 The functions on this special hook are called with 4 arguments:
2868 NEXT-FUN BEG END DELETE
2869 NEXT-FUN is a function of 3 arguments (BEG END DELETE)
2870 that performs the default operation. The other 3 arguments are like
2871 the ones passed to `filter-buffer-substring'.")
2873 (defvar buffer-substring-filters nil
2874 "List of filter functions for `filter-buffer-substring'.
2875 Each function must accept a single argument, a string, and return
2876 a string. The buffer substring is passed to the first function
2877 in the list, and the return value of each function is passed to
2878 the next. The return value of the last function is used as the
2879 return value of `filter-buffer-substring'.
2881 If this variable is nil, no filtering is performed.")
2882 (make-obsolete-variable 'buffer-substring-filters
2883 'filter-buffer-substring-functions "24.1")
2885 (defun filter-buffer-substring (beg end &optional delete)
2886 "Return the buffer substring between BEG and END, after filtering.
2887 The filtering is performed by `filter-buffer-substring-functions'.
2889 If DELETE is non-nil, the text between BEG and END is deleted
2890 from the buffer.
2892 This function should be used instead of `buffer-substring',
2893 `buffer-substring-no-properties', or `delete-and-extract-region'
2894 when you want to allow filtering to take place. For example,
2895 major or minor modes can use `filter-buffer-substring-functions' to
2896 extract characters that are special to a buffer, and should not
2897 be copied into other buffers."
2898 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
2899 (cond
2900 ((or delete buffer-substring-filters)
2901 (save-excursion
2902 (goto-char beg)
2903 (let ((string (if delete (delete-and-extract-region beg end)
2904 (buffer-substring beg end))))
2905 (dolist (filter buffer-substring-filters)
2906 (setq string (funcall filter string)))
2907 string)))
2909 (buffer-substring beg end)))))
2912 ;;;; Window system cut and paste hooks.
2914 (defvar interprogram-cut-function nil
2915 "Function to call to make a killed region available to other programs.
2917 Most window systems provide some sort of facility for cutting and
2918 pasting text between the windows of different programs.
2919 This variable holds a function that Emacs calls whenever text
2920 is put in the kill ring, to make the new kill available to other
2921 programs.
2923 The function takes one argument, TEXT, which is a string containing
2924 the text which should be made available.")
2926 (defvar interprogram-paste-function nil
2927 "Function to call to get text cut from other programs.
2929 Most window systems provide some sort of facility for cutting and
2930 pasting text between the windows of different programs.
2931 This variable holds a function that Emacs calls to obtain
2932 text that other programs have provided for pasting.
2934 The function should be called with no arguments. If the function
2935 returns nil, then no other program has provided such text, and the top
2936 of the Emacs kill ring should be used. If the function returns a
2937 string, then the caller of the function \(usually `current-kill')
2938 should put this string in the kill ring as the latest kill.
2940 This function may also return a list of strings if the window
2941 system supports multiple selections. The first string will be
2942 used as the pasted text, but the other will be placed in the
2943 kill ring for easy access via `yank-pop'.
2945 Note that the function should return a string only if a program other
2946 than Emacs has provided a string for pasting; if Emacs provided the
2947 most recent string, the function should return nil. If it is
2948 difficult to tell whether Emacs or some other program provided the
2949 current string, it is probably good enough to return nil if the string
2950 is equal (according to `string=') to the last text Emacs provided.")
2954 ;;;; The kill ring data structure.
2956 (defvar kill-ring nil
2957 "List of killed text sequences.
2958 Since the kill ring is supposed to interact nicely with cut-and-paste
2959 facilities offered by window systems, use of this variable should
2960 interact nicely with `interprogram-cut-function' and
2961 `interprogram-paste-function'. The functions `kill-new',
2962 `kill-append', and `current-kill' are supposed to implement this
2963 interaction; you may want to use them instead of manipulating the kill
2964 ring directly.")
2966 (defcustom kill-ring-max 60
2967 "Maximum length of kill ring before oldest elements are thrown away."
2968 :type 'integer
2969 :group 'killing)
2971 (defvar kill-ring-yank-pointer nil
2972 "The tail of the kill ring whose car is the last thing yanked.")
2974 (defcustom save-interprogram-paste-before-kill nil
2975 "Save clipboard strings into kill ring before replacing them.
2976 When one selects something in another program to paste it into Emacs,
2977 but kills something in Emacs before actually pasting it,
2978 this selection is gone unless this variable is non-nil,
2979 in which case the other program's selection is saved in the `kill-ring'
2980 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
2981 :type 'boolean
2982 :group 'killing
2983 :version "23.2")
2985 (defcustom kill-do-not-save-duplicates nil
2986 "Do not add a new string to `kill-ring' when it is the same as the last one."
2987 :type 'boolean
2988 :group 'killing
2989 :version "23.2")
2991 (defun kill-new (string &optional replace yank-handler)
2992 "Make STRING the latest kill in the kill ring.
2993 Set `kill-ring-yank-pointer' to point to it.
2994 If `interprogram-cut-function' is non-nil, apply it to STRING.
2995 Optional second argument REPLACE non-nil means that STRING will replace
2996 the front of the kill ring, rather than being added to the list.
2998 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
2999 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3000 STRING.
3002 When the yank handler has a non-nil PARAM element, the original STRING
3003 argument is not used by `insert-for-yank'. However, since Lisp code
3004 may access and use elements from the kill ring directly, the STRING
3005 argument should still be a \"useful\" string for such uses."
3006 (if (> (length string) 0)
3007 (if yank-handler
3008 (put-text-property 0 (length string)
3009 'yank-handler yank-handler string))
3010 (if yank-handler
3011 (signal 'args-out-of-range
3012 (list string "yank-handler specified for empty string"))))
3013 (unless (and kill-do-not-save-duplicates
3014 (equal string (car kill-ring)))
3015 (if (fboundp 'menu-bar-update-yank-menu)
3016 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
3017 (when save-interprogram-paste-before-kill
3018 (let ((interprogram-paste (and interprogram-paste-function
3019 (funcall interprogram-paste-function))))
3020 (when interprogram-paste
3021 (dolist (s (if (listp interprogram-paste)
3022 (nreverse interprogram-paste)
3023 (list interprogram-paste)))
3024 (unless (and kill-do-not-save-duplicates
3025 (equal s (car kill-ring)))
3026 (push s kill-ring))))))
3027 (unless (and kill-do-not-save-duplicates
3028 (equal string (car kill-ring)))
3029 (if (and replace kill-ring)
3030 (setcar kill-ring string)
3031 (push string kill-ring)
3032 (if (> (length kill-ring) kill-ring-max)
3033 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
3034 (setq kill-ring-yank-pointer kill-ring)
3035 (if interprogram-cut-function
3036 (funcall interprogram-cut-function string)))
3037 (set-advertised-calling-convention
3038 'kill-new '(string &optional replace) "23.3")
3040 (defun kill-append (string before-p &optional yank-handler)
3041 "Append STRING to the end of the latest kill in the kill ring.
3042 If BEFORE-P is non-nil, prepend STRING to the kill.
3043 If `interprogram-cut-function' is set, pass the resulting kill to it."
3044 (let* ((cur (car kill-ring)))
3045 (kill-new (if before-p (concat string cur) (concat cur string))
3046 (or (= (length cur) 0)
3047 (equal yank-handler (get-text-property 0 'yank-handler cur)))
3048 yank-handler)))
3049 (set-advertised-calling-convention 'kill-append '(string before-p) "23.3")
3051 (defcustom yank-pop-change-selection nil
3052 "If non-nil, rotating the kill ring changes the window system selection."
3053 :type 'boolean
3054 :group 'killing
3055 :version "23.1")
3057 (defun current-kill (n &optional do-not-move)
3058 "Rotate the yanking point by N places, and then return that kill.
3059 If N is zero, `interprogram-paste-function' is set, and calling
3060 it returns a string or list of strings, then that string (or
3061 list) is added to the front of the kill ring and the string (or
3062 first string in the list) is returned as the latest kill.
3064 If N is not zero, and if `yank-pop-change-selection' is
3065 non-nil, use `interprogram-cut-function' to transfer the
3066 kill at the new yank point into the window system selection.
3068 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3069 move the yanking point; just return the Nth kill forward."
3071 (let ((interprogram-paste (and (= n 0)
3072 interprogram-paste-function
3073 (funcall interprogram-paste-function))))
3074 (if interprogram-paste
3075 (progn
3076 ;; Disable the interprogram cut function when we add the new
3077 ;; text to the kill ring, so Emacs doesn't try to own the
3078 ;; selection, with identical text.
3079 (let ((interprogram-cut-function nil))
3080 (if (listp interprogram-paste)
3081 (mapc 'kill-new (nreverse interprogram-paste))
3082 (kill-new interprogram-paste)))
3083 (car kill-ring))
3084 (or kill-ring (error "Kill ring is empty"))
3085 (let ((ARGth-kill-element
3086 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3087 (length kill-ring))
3088 kill-ring)))
3089 (unless do-not-move
3090 (setq kill-ring-yank-pointer ARGth-kill-element)
3091 (when (and yank-pop-change-selection
3092 (> n 0)
3093 interprogram-cut-function)
3094 (funcall interprogram-cut-function (car ARGth-kill-element))))
3095 (car ARGth-kill-element)))))
3099 ;;;; Commands for manipulating the kill ring.
3101 (defcustom kill-read-only-ok nil
3102 "Non-nil means don't signal an error for killing read-only text."
3103 :type 'boolean
3104 :group 'killing)
3106 (put 'text-read-only 'error-conditions
3107 '(text-read-only buffer-read-only error))
3108 (put 'text-read-only 'error-message (purecopy "Text is read-only"))
3110 (defun kill-region (beg end &optional yank-handler)
3111 "Kill (\"cut\") text between point and mark.
3112 This deletes the text from the buffer and saves it in the kill ring.
3113 The command \\[yank] can retrieve it from there.
3114 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3116 If you want to append the killed region to the last killed text,
3117 use \\[append-next-kill] before \\[kill-region].
3119 If the buffer is read-only, Emacs will beep and refrain from deleting
3120 the text, but put the text in the kill ring anyway. This means that
3121 you can use the killing commands to copy text from a read-only buffer.
3123 Lisp programs should use this function for killing text.
3124 (To delete text, use `delete-region'.)
3125 Supply two arguments, character positions indicating the stretch of text
3126 to be killed.
3127 Any command that calls this function is a \"kill command\".
3128 If the previous command was also a kill command,
3129 the text killed this time appends to the text killed last time
3130 to make one entry in the kill ring."
3131 ;; Pass point first, then mark, because the order matters
3132 ;; when calling kill-append.
3133 (interactive (list (point) (mark)))
3134 (unless (and beg end)
3135 (error "The mark is not set now, so there is no region"))
3136 (condition-case nil
3137 (let ((string (filter-buffer-substring beg end t)))
3138 (when string ;STRING is nil if BEG = END
3139 ;; Add that string to the kill ring, one way or another.
3140 (if (eq last-command 'kill-region)
3141 (kill-append string (< end beg) yank-handler)
3142 (kill-new string nil yank-handler)))
3143 (when (or string (eq last-command 'kill-region))
3144 (setq this-command 'kill-region))
3145 nil)
3146 ((buffer-read-only text-read-only)
3147 ;; The code above failed because the buffer, or some of the characters
3148 ;; in the region, are read-only.
3149 ;; We should beep, in case the user just isn't aware of this.
3150 ;; However, there's no harm in putting
3151 ;; the region's text in the kill ring, anyway.
3152 (copy-region-as-kill beg end)
3153 ;; Set this-command now, so it will be set even if we get an error.
3154 (setq this-command 'kill-region)
3155 ;; This should barf, if appropriate, and give us the correct error.
3156 (if kill-read-only-ok
3157 (progn (message "Read only text copied to kill ring") nil)
3158 ;; Signal an error if the buffer is read-only.
3159 (barf-if-buffer-read-only)
3160 ;; If the buffer isn't read-only, the text is.
3161 (signal 'text-read-only (list (current-buffer)))))))
3162 (set-advertised-calling-convention 'kill-region '(beg end) "23.3")
3164 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3165 ;; to get two copies of the text when the user accidentally types M-w and
3166 ;; then corrects it with the intended C-w.
3167 (defun copy-region-as-kill (beg end)
3168 "Save the region as if killed, but don't kill it.
3169 In Transient Mark mode, deactivate the mark.
3170 If `interprogram-cut-function' is non-nil, also save the text for a window
3171 system cut and paste.
3173 This command's old key binding has been given to `kill-ring-save'."
3174 (interactive "r")
3175 (if (eq last-command 'kill-region)
3176 (kill-append (filter-buffer-substring beg end) (< end beg))
3177 (kill-new (filter-buffer-substring beg end)))
3178 (setq deactivate-mark t)
3179 nil)
3181 (defun kill-ring-save (beg end)
3182 "Save the region as if killed, but don't kill it.
3183 In Transient Mark mode, deactivate the mark.
3184 If `interprogram-cut-function' is non-nil, also save the text for a window
3185 system cut and paste.
3187 If you want to append the killed line to the last killed text,
3188 use \\[append-next-kill] before \\[kill-ring-save].
3190 This command is similar to `copy-region-as-kill', except that it gives
3191 visual feedback indicating the extent of the region being copied."
3192 (interactive "r")
3193 (copy-region-as-kill beg end)
3194 ;; This use of called-interactively-p is correct
3195 ;; because the code it controls just gives the user visual feedback.
3196 (if (called-interactively-p 'interactive)
3197 (let ((other-end (if (= (point) beg) end beg))
3198 (opoint (point))
3199 ;; Inhibit quitting so we can make a quit here
3200 ;; look like a C-g typed as a command.
3201 (inhibit-quit t))
3202 (if (pos-visible-in-window-p other-end (selected-window))
3203 ;; Swap point-and-mark quickly so as to show the region that
3204 ;; was selected. Don't do it if the region is highlighted.
3205 (unless (and (region-active-p)
3206 (face-background 'region))
3207 ;; Swap point and mark.
3208 (set-marker (mark-marker) (point) (current-buffer))
3209 (goto-char other-end)
3210 (sit-for blink-matching-delay)
3211 ;; Swap back.
3212 (set-marker (mark-marker) other-end (current-buffer))
3213 (goto-char opoint)
3214 ;; If user quit, deactivate the mark
3215 ;; as C-g would as a command.
3216 (and quit-flag mark-active
3217 (deactivate-mark)))
3218 (let* ((killed-text (current-kill 0))
3219 (message-len (min (length killed-text) 40)))
3220 (if (= (point) beg)
3221 ;; Don't say "killed"; that is misleading.
3222 (message "Saved text until \"%s\""
3223 (substring killed-text (- message-len)))
3224 (message "Saved text from \"%s\""
3225 (substring killed-text 0 message-len))))))))
3227 (defun append-next-kill (&optional interactive)
3228 "Cause following command, if it kills, to append to previous kill.
3229 The argument is used for internal purposes; do not supply one."
3230 (interactive "p")
3231 ;; We don't use (interactive-p), since that breaks kbd macros.
3232 (if interactive
3233 (progn
3234 (setq this-command 'kill-region)
3235 (message "If the next command is a kill, it will append"))
3236 (setq last-command 'kill-region)))
3238 ;; Yanking.
3240 ;; This is actually used in subr.el but defcustom does not work there.
3241 (defcustom yank-excluded-properties
3242 '(read-only invisible intangible field mouse-face help-echo local-map keymap
3243 yank-handler follow-link fontified)
3244 "Text properties to discard when yanking.
3245 The value should be a list of text properties to discard or t,
3246 which means to discard all text properties."
3247 :type '(choice (const :tag "All" t) (repeat symbol))
3248 :group 'killing
3249 :version "22.1")
3251 (defvar yank-window-start nil)
3252 (defvar yank-undo-function nil
3253 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3254 Function is called with two parameters, START and END corresponding to
3255 the value of the mark and point; it is guaranteed that START <= END.
3256 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3258 (defun yank-pop (&optional arg)
3259 "Replace just-yanked stretch of killed text with a different stretch.
3260 This command is allowed only immediately after a `yank' or a `yank-pop'.
3261 At such a time, the region contains a stretch of reinserted
3262 previously-killed text. `yank-pop' deletes that text and inserts in its
3263 place a different stretch of killed text.
3265 With no argument, the previous kill is inserted.
3266 With argument N, insert the Nth previous kill.
3267 If N is negative, this is a more recent kill.
3269 The sequence of kills wraps around, so that after the oldest one
3270 comes the newest one.
3272 When this command inserts killed text into the buffer, it honors
3273 `yank-excluded-properties' and `yank-handler' as described in the
3274 doc string for `insert-for-yank-1', which see."
3275 (interactive "*p")
3276 (if (not (eq last-command 'yank))
3277 (error "Previous command was not a yank"))
3278 (setq this-command 'yank)
3279 (unless arg (setq arg 1))
3280 (let ((inhibit-read-only t)
3281 (before (< (point) (mark t))))
3282 (if before
3283 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3284 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
3285 (setq yank-undo-function nil)
3286 (set-marker (mark-marker) (point) (current-buffer))
3287 (insert-for-yank (current-kill arg))
3288 ;; Set the window start back where it was in the yank command,
3289 ;; if possible.
3290 (set-window-start (selected-window) yank-window-start t)
3291 (if before
3292 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3293 ;; It is cleaner to avoid activation, even though the command
3294 ;; loop would deactivate the mark because we inserted text.
3295 (goto-char (prog1 (mark t)
3296 (set-marker (mark-marker) (point) (current-buffer))))))
3297 nil)
3299 (defun yank (&optional arg)
3300 "Reinsert (\"paste\") the last stretch of killed text.
3301 More precisely, reinsert the stretch of killed text most recently
3302 killed OR yanked. Put point at end, and set mark at beginning.
3303 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
3304 With argument N, reinsert the Nth most recently killed stretch of killed
3305 text.
3307 When this command inserts killed text into the buffer, it honors
3308 `yank-excluded-properties' and `yank-handler' as described in the
3309 doc string for `insert-for-yank-1', which see.
3311 See also the command `yank-pop' (\\[yank-pop])."
3312 (interactive "*P")
3313 (setq yank-window-start (window-start))
3314 ;; If we don't get all the way thru, make last-command indicate that
3315 ;; for the following command.
3316 (setq this-command t)
3317 (push-mark (point))
3318 (insert-for-yank (current-kill (cond
3319 ((listp arg) 0)
3320 ((eq arg '-) -2)
3321 (t (1- arg)))))
3322 (if (consp arg)
3323 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3324 ;; It is cleaner to avoid activation, even though the command
3325 ;; loop would deactivate the mark because we inserted text.
3326 (goto-char (prog1 (mark t)
3327 (set-marker (mark-marker) (point) (current-buffer)))))
3328 ;; If we do get all the way thru, make this-command indicate that.
3329 (if (eq this-command t)
3330 (setq this-command 'yank))
3331 nil)
3333 (defun rotate-yank-pointer (arg)
3334 "Rotate the yanking point in the kill ring.
3335 With ARG, rotate that many kills forward (or backward, if negative)."
3336 (interactive "p")
3337 (current-kill arg))
3339 ;; Some kill commands.
3341 ;; Internal subroutine of delete-char
3342 (defun kill-forward-chars (arg)
3343 (if (listp arg) (setq arg (car arg)))
3344 (if (eq arg '-) (setq arg -1))
3345 (kill-region (point) (+ (point) arg)))
3347 ;; Internal subroutine of backward-delete-char
3348 (defun kill-backward-chars (arg)
3349 (if (listp arg) (setq arg (car arg)))
3350 (if (eq arg '-) (setq arg -1))
3351 (kill-region (point) (- (point) arg)))
3353 (defcustom backward-delete-char-untabify-method 'untabify
3354 "The method for untabifying when deleting backward.
3355 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3356 `hungry' -- delete all whitespace, both tabs and spaces;
3357 `all' -- delete all whitespace, including tabs, spaces and newlines;
3358 nil -- just delete one character."
3359 :type '(choice (const untabify) (const hungry) (const all) (const nil))
3360 :version "20.3"
3361 :group 'killing)
3363 (defun backward-delete-char-untabify (arg &optional killp)
3364 "Delete characters backward, changing tabs into spaces.
3365 The exact behavior depends on `backward-delete-char-untabify-method'.
3366 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3367 Interactively, ARG is the prefix arg (default 1)
3368 and KILLP is t if a prefix arg was specified."
3369 (interactive "*p\nP")
3370 (when (eq backward-delete-char-untabify-method 'untabify)
3371 (let ((count arg))
3372 (save-excursion
3373 (while (and (> count 0) (not (bobp)))
3374 (if (= (preceding-char) ?\t)
3375 (let ((col (current-column)))
3376 (forward-char -1)
3377 (setq col (- col (current-column)))
3378 (insert-char ?\s col)
3379 (delete-char 1)))
3380 (forward-char -1)
3381 (setq count (1- count))))))
3382 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3383 ((eq backward-delete-char-untabify-method 'all)
3384 " \t\n\r")))
3385 (n (if skip
3386 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
3387 (point)))))
3388 (+ arg (if (zerop wh) 0 (1- wh))))
3389 arg)))
3390 ;; Avoid warning about delete-backward-char
3391 (with-no-warnings (delete-backward-char n killp))))
3393 (defun zap-to-char (arg char)
3394 "Kill up to and including ARGth occurrence of CHAR.
3395 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3396 Goes backward if ARG is negative; error if CHAR not found."
3397 (interactive "p\ncZap to char: ")
3398 ;; Avoid "obsolete" warnings for translation-table-for-input.
3399 (with-no-warnings
3400 (if (char-table-p translation-table-for-input)
3401 (setq char (or (aref translation-table-for-input char) char))))
3402 (kill-region (point) (progn
3403 (search-forward (char-to-string char) nil nil arg)
3404 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3405 (point))))
3407 ;; kill-line and its subroutines.
3409 (defcustom kill-whole-line nil
3410 "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
3411 :type 'boolean
3412 :group 'killing)
3414 (defun kill-line (&optional arg)
3415 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3416 With prefix argument ARG, kill that many lines from point.
3417 Negative arguments kill lines backward.
3418 With zero argument, kills the text before point on the current line.
3420 When calling from a program, nil means \"no arg\",
3421 a number counts as a prefix arg.
3423 To kill a whole line, when point is not at the beginning, type \
3424 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3426 If `kill-whole-line' is non-nil, then this command kills the whole line
3427 including its terminating newline, when used at the beginning of a line
3428 with no argument. As a consequence, you can always kill a whole line
3429 by typing \\[move-beginning-of-line] \\[kill-line].
3431 If you want to append the killed line to the last killed text,
3432 use \\[append-next-kill] before \\[kill-line].
3434 If the buffer is read-only, Emacs will beep and refrain from deleting
3435 the line, but put the line in the kill ring anyway. This means that
3436 you can use this command to copy text from a read-only buffer.
3437 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3438 even beep.)"
3439 (interactive "P")
3440 (kill-region (point)
3441 ;; It is better to move point to the other end of the kill
3442 ;; before killing. That way, in a read-only buffer, point
3443 ;; moves across the text that is copied to the kill ring.
3444 ;; The choice has no effect on undo now that undo records
3445 ;; the value of point from before the command was run.
3446 (progn
3447 (if arg
3448 (forward-visible-line (prefix-numeric-value arg))
3449 (if (eobp)
3450 (signal 'end-of-buffer nil))
3451 (let ((end
3452 (save-excursion
3453 (end-of-visible-line) (point))))
3454 (if (or (save-excursion
3455 ;; If trailing whitespace is visible,
3456 ;; don't treat it as nothing.
3457 (unless show-trailing-whitespace
3458 (skip-chars-forward " \t" end))
3459 (= (point) end))
3460 (and kill-whole-line (bolp)))
3461 (forward-visible-line 1)
3462 (goto-char end))))
3463 (point))))
3465 (defun kill-whole-line (&optional arg)
3466 "Kill current line.
3467 With prefix ARG, kill that many lines starting from the current line.
3468 If ARG is negative, kill backward. Also kill the preceding newline.
3469 \(This is meant to make \\[repeat] work well with negative arguments.\)
3470 If ARG is zero, kill current line but exclude the trailing newline."
3471 (interactive "p")
3472 (or arg (setq arg 1))
3473 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3474 (signal 'end-of-buffer nil))
3475 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3476 (signal 'beginning-of-buffer nil))
3477 (unless (eq last-command 'kill-region)
3478 (kill-new "")
3479 (setq last-command 'kill-region))
3480 (cond ((zerop arg)
3481 ;; We need to kill in two steps, because the previous command
3482 ;; could have been a kill command, in which case the text
3483 ;; before point needs to be prepended to the current kill
3484 ;; ring entry and the text after point appended. Also, we
3485 ;; need to use save-excursion to avoid copying the same text
3486 ;; twice to the kill ring in read-only buffers.
3487 (save-excursion
3488 (kill-region (point) (progn (forward-visible-line 0) (point))))
3489 (kill-region (point) (progn (end-of-visible-line) (point))))
3490 ((< arg 0)
3491 (save-excursion
3492 (kill-region (point) (progn (end-of-visible-line) (point))))
3493 (kill-region (point)
3494 (progn (forward-visible-line (1+ arg))
3495 (unless (bobp) (backward-char))
3496 (point))))
3498 (save-excursion
3499 (kill-region (point) (progn (forward-visible-line 0) (point))))
3500 (kill-region (point)
3501 (progn (forward-visible-line arg) (point))))))
3503 (defun forward-visible-line (arg)
3504 "Move forward by ARG lines, ignoring currently invisible newlines only.
3505 If ARG is negative, move backward -ARG lines.
3506 If ARG is zero, move to the beginning of the current line."
3507 (condition-case nil
3508 (if (> arg 0)
3509 (progn
3510 (while (> arg 0)
3511 (or (zerop (forward-line 1))
3512 (signal 'end-of-buffer nil))
3513 ;; If the newline we just skipped is invisible,
3514 ;; don't count it.
3515 (let ((prop
3516 (get-char-property (1- (point)) 'invisible)))
3517 (if (if (eq buffer-invisibility-spec t)
3518 prop
3519 (or (memq prop buffer-invisibility-spec)
3520 (assq prop buffer-invisibility-spec)))
3521 (setq arg (1+ arg))))
3522 (setq arg (1- arg)))
3523 ;; If invisible text follows, and it is a number of complete lines,
3524 ;; skip it.
3525 (let ((opoint (point)))
3526 (while (and (not (eobp))
3527 (let ((prop
3528 (get-char-property (point) 'invisible)))
3529 (if (eq buffer-invisibility-spec t)
3530 prop
3531 (or (memq prop buffer-invisibility-spec)
3532 (assq prop buffer-invisibility-spec)))))
3533 (goto-char
3534 (if (get-text-property (point) 'invisible)
3535 (or (next-single-property-change (point) 'invisible)
3536 (point-max))
3537 (next-overlay-change (point)))))
3538 (unless (bolp)
3539 (goto-char opoint))))
3540 (let ((first t))
3541 (while (or first (<= arg 0))
3542 (if first
3543 (beginning-of-line)
3544 (or (zerop (forward-line -1))
3545 (signal 'beginning-of-buffer nil)))
3546 ;; If the newline we just moved to is invisible,
3547 ;; don't count it.
3548 (unless (bobp)
3549 (let ((prop
3550 (get-char-property (1- (point)) 'invisible)))
3551 (unless (if (eq buffer-invisibility-spec t)
3552 prop
3553 (or (memq prop buffer-invisibility-spec)
3554 (assq prop buffer-invisibility-spec)))
3555 (setq arg (1+ arg)))))
3556 (setq first nil))
3557 ;; If invisible text follows, and it is a number of complete lines,
3558 ;; skip it.
3559 (let ((opoint (point)))
3560 (while (and (not (bobp))
3561 (let ((prop
3562 (get-char-property (1- (point)) 'invisible)))
3563 (if (eq buffer-invisibility-spec t)
3564 prop
3565 (or (memq prop buffer-invisibility-spec)
3566 (assq prop buffer-invisibility-spec)))))
3567 (goto-char
3568 (if (get-text-property (1- (point)) 'invisible)
3569 (or (previous-single-property-change (point) 'invisible)
3570 (point-min))
3571 (previous-overlay-change (point)))))
3572 (unless (bolp)
3573 (goto-char opoint)))))
3574 ((beginning-of-buffer end-of-buffer)
3575 nil)))
3577 (defun end-of-visible-line ()
3578 "Move to end of current visible line."
3579 (end-of-line)
3580 ;; If the following character is currently invisible,
3581 ;; skip all characters with that same `invisible' property value,
3582 ;; then find the next newline.
3583 (while (and (not (eobp))
3584 (save-excursion
3585 (skip-chars-forward "^\n")
3586 (let ((prop
3587 (get-char-property (point) 'invisible)))
3588 (if (eq buffer-invisibility-spec t)
3589 prop
3590 (or (memq prop buffer-invisibility-spec)
3591 (assq prop buffer-invisibility-spec))))))
3592 (skip-chars-forward "^\n")
3593 (if (get-text-property (point) 'invisible)
3594 (goto-char (next-single-property-change (point) 'invisible))
3595 (goto-char (next-overlay-change (point))))
3596 (end-of-line)))
3598 (defun insert-buffer (buffer)
3599 "Insert after point the contents of BUFFER.
3600 Puts mark after the inserted text.
3601 BUFFER may be a buffer or a buffer name.
3603 This function is meant for the user to run interactively.
3604 Don't call it from programs: use `insert-buffer-substring' instead!"
3605 (interactive
3606 (list
3607 (progn
3608 (barf-if-buffer-read-only)
3609 (read-buffer "Insert buffer: "
3610 (if (eq (selected-window) (next-window (selected-window)))
3611 (other-buffer (current-buffer))
3612 (window-buffer (next-window (selected-window))))
3613 t))))
3614 (push-mark
3615 (save-excursion
3616 (insert-buffer-substring (get-buffer buffer))
3617 (point)))
3618 nil)
3620 (defun append-to-buffer (buffer start end)
3621 "Append to specified buffer the text of the region.
3622 It is inserted into that buffer before its point.
3624 When calling from a program, give three arguments:
3625 BUFFER (or buffer name), START and END.
3626 START and END specify the portion of the current buffer to be copied."
3627 (interactive
3628 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3629 (region-beginning) (region-end)))
3630 (let* ((oldbuf (current-buffer))
3631 (append-to (get-buffer-create buffer))
3632 (windows (get-buffer-window-list append-to t t))
3633 point)
3634 (save-excursion
3635 (with-current-buffer append-to
3636 (setq point (point))
3637 (barf-if-buffer-read-only)
3638 (insert-buffer-substring oldbuf start end)
3639 (dolist (window windows)
3640 (when (= (window-point window) point)
3641 (set-window-point window (point))))))))
3643 (defun prepend-to-buffer (buffer start end)
3644 "Prepend to specified buffer the text of the region.
3645 It is inserted into that buffer after its point.
3647 When calling from a program, give three arguments:
3648 BUFFER (or buffer name), START and END.
3649 START and END specify the portion of the current buffer to be copied."
3650 (interactive "BPrepend to buffer: \nr")
3651 (let ((oldbuf (current-buffer)))
3652 (with-current-buffer (get-buffer-create buffer)
3653 (barf-if-buffer-read-only)
3654 (save-excursion
3655 (insert-buffer-substring oldbuf start end)))))
3657 (defun copy-to-buffer (buffer start end)
3658 "Copy to specified buffer the text of the region.
3659 It is inserted into that buffer, replacing existing text there.
3661 When calling from a program, give three arguments:
3662 BUFFER (or buffer name), START and END.
3663 START and END specify the portion of the current buffer to be copied."
3664 (interactive "BCopy to buffer: \nr")
3665 (let ((oldbuf (current-buffer)))
3666 (with-current-buffer (get-buffer-create buffer)
3667 (barf-if-buffer-read-only)
3668 (erase-buffer)
3669 (save-excursion
3670 (insert-buffer-substring oldbuf start end)))))
3672 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3673 (put 'mark-inactive 'error-message (purecopy "The mark is not active now"))
3675 (defvar activate-mark-hook nil
3676 "Hook run when the mark becomes active.
3677 It is also run at the end of a command, if the mark is active and
3678 it is possible that the region may have changed.")
3680 (defvar deactivate-mark-hook nil
3681 "Hook run when the mark becomes inactive.")
3683 (defun mark (&optional force)
3684 "Return this buffer's mark value as integer, or nil if never set.
3686 In Transient Mark mode, this function signals an error if
3687 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3688 or the argument FORCE is non-nil, it disregards whether the mark
3689 is active, and returns an integer or nil in the usual way.
3691 If you are using this in an editing command, you are most likely making
3692 a mistake; see the documentation of `set-mark'."
3693 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3694 (marker-position (mark-marker))
3695 (signal 'mark-inactive nil)))
3697 (defsubst deactivate-mark (&optional force)
3698 "Deactivate the mark by setting `mark-active' to nil.
3699 Unless FORCE is non-nil, this function does nothing if Transient
3700 Mark mode is disabled.
3701 This function also runs `deactivate-mark-hook'."
3702 (when (or transient-mark-mode force)
3703 (when (and (if (eq select-active-regions 'only)
3704 (eq (car-safe transient-mark-mode) 'only)
3705 select-active-regions)
3706 (region-active-p)
3707 (display-selections-p))
3708 ;; The var `saved-region-selection', if non-nil, is the text in
3709 ;; the region prior to the last command modifying the buffer.
3710 ;; Set the selection to that, or to the current region.
3711 (cond (saved-region-selection
3712 (x-set-selection 'PRIMARY saved-region-selection)
3713 (setq saved-region-selection nil))
3714 ((/= (region-beginning) (region-end))
3715 (x-set-selection 'PRIMARY
3716 (buffer-substring-no-properties
3717 (region-beginning)
3718 (region-end))))))
3719 (if (and (null force)
3720 (or (eq transient-mark-mode 'lambda)
3721 (and (eq (car-safe transient-mark-mode) 'only)
3722 (null (cdr transient-mark-mode)))))
3723 ;; When deactivating a temporary region, don't change
3724 ;; `mark-active' or run `deactivate-mark-hook'.
3725 (setq transient-mark-mode nil)
3726 (if (eq (car-safe transient-mark-mode) 'only)
3727 (setq transient-mark-mode (cdr transient-mark-mode)))
3728 (setq mark-active nil)
3729 (run-hooks 'deactivate-mark-hook))))
3731 (defun activate-mark ()
3732 "Activate the mark."
3733 (when (mark t)
3734 (setq mark-active t)
3735 (unless transient-mark-mode
3736 (setq transient-mark-mode 'lambda))))
3738 (defun set-mark (pos)
3739 "Set this buffer's mark to POS. Don't use this function!
3740 That is to say, don't use this function unless you want
3741 the user to see that the mark has moved, and you want the previous
3742 mark position to be lost.
3744 Normally, when a new mark is set, the old one should go on the stack.
3745 This is why most applications should use `push-mark', not `set-mark'.
3747 Novice Emacs Lisp programmers often try to use the mark for the wrong
3748 purposes. The mark saves a location for the user's convenience.
3749 Most editing commands should not alter the mark.
3750 To remember a location for internal use in the Lisp program,
3751 store it in a Lisp variable. Example:
3753 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3755 (if pos
3756 (progn
3757 (setq mark-active t)
3758 (run-hooks 'activate-mark-hook)
3759 (set-marker (mark-marker) pos (current-buffer)))
3760 ;; Normally we never clear mark-active except in Transient Mark mode.
3761 ;; But when we actually clear out the mark value too, we must
3762 ;; clear mark-active in any mode.
3763 (deactivate-mark t)
3764 (set-marker (mark-marker) nil)))
3766 (defcustom use-empty-active-region nil
3767 "Whether \"region-aware\" commands should act on empty regions.
3768 If nil, region-aware commands treat empty regions as inactive.
3769 If non-nil, region-aware commands treat the region as active as
3770 long as the mark is active, even if the region is empty.
3772 Region-aware commands are those that act on the region if it is
3773 active and Transient Mark mode is enabled, and on the text near
3774 point otherwise."
3775 :type 'boolean
3776 :version "23.1"
3777 :group 'editing-basics)
3779 (defun use-region-p ()
3780 "Return t if the region is active and it is appropriate to act on it.
3781 This is used by commands that act specially on the region under
3782 Transient Mark mode.
3784 The return value is t if Transient Mark mode is enabled and the
3785 mark is active; furthermore, if `use-empty-active-region' is nil,
3786 the region must not be empty. Otherwise, the return value is nil.
3788 For some commands, it may be appropriate to ignore the value of
3789 `use-empty-active-region'; in that case, use `region-active-p'."
3790 (and (region-active-p)
3791 (or use-empty-active-region (> (region-end) (region-beginning)))))
3793 (defun region-active-p ()
3794 "Return t if Transient Mark mode is enabled and the mark is active.
3796 Some commands act specially on the region when Transient Mark
3797 mode is enabled. Usually, such commands should use
3798 `use-region-p' instead of this function, because `use-region-p'
3799 also checks the value of `use-empty-active-region'."
3800 (and transient-mark-mode mark-active))
3802 (defvar mark-ring nil
3803 "The list of former marks of the current buffer, most recent first.")
3804 (make-variable-buffer-local 'mark-ring)
3805 (put 'mark-ring 'permanent-local t)
3807 (defcustom mark-ring-max 16
3808 "Maximum size of mark ring. Start discarding off end if gets this big."
3809 :type 'integer
3810 :group 'editing-basics)
3812 (defvar global-mark-ring nil
3813 "The list of saved global marks, most recent first.")
3815 (defcustom global-mark-ring-max 16
3816 "Maximum size of global mark ring. \
3817 Start discarding off end if gets this big."
3818 :type 'integer
3819 :group 'editing-basics)
3821 (defun pop-to-mark-command ()
3822 "Jump to mark, and pop a new position for mark off the ring.
3823 \(Does not affect global mark ring\)."
3824 (interactive)
3825 (if (null (mark t))
3826 (error "No mark set in this buffer")
3827 (if (= (point) (mark t))
3828 (message "Mark popped"))
3829 (goto-char (mark t))
3830 (pop-mark)))
3832 (defun push-mark-command (arg &optional nomsg)
3833 "Set mark at where point is.
3834 If no prefix ARG and mark is already set there, just activate it.
3835 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3836 (interactive "P")
3837 (let ((mark (marker-position (mark-marker))))
3838 (if (or arg (null mark) (/= mark (point)))
3839 (push-mark nil nomsg t)
3840 (setq mark-active t)
3841 (run-hooks 'activate-mark-hook)
3842 (unless nomsg
3843 (message "Mark activated")))))
3845 (defcustom set-mark-command-repeat-pop nil
3846 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3847 That means that C-u \\[set-mark-command] \\[set-mark-command]
3848 will pop the mark twice, and
3849 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3850 will pop the mark three times.
3852 A value of nil means \\[set-mark-command]'s behavior does not change
3853 after C-u \\[set-mark-command]."
3854 :type 'boolean
3855 :group 'editing-basics)
3857 (defcustom set-mark-default-inactive nil
3858 "If non-nil, setting the mark does not activate it.
3859 This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
3860 behave the same whether or not `transient-mark-mode' is enabled."
3861 :type 'boolean
3862 :group 'editing-basics
3863 :version "23.1")
3865 (defun set-mark-command (arg)
3866 "Set the mark where point is, or jump to the mark.
3867 Setting the mark also alters the region, which is the text
3868 between point and mark; this is the closest equivalent in
3869 Emacs to what some editors call the \"selection\".
3871 With no prefix argument, set the mark at point, and push the
3872 old mark position on local mark ring. Also push the old mark on
3873 global mark ring, if the previous mark was set in another buffer.
3875 When Transient Mark Mode is off, immediately repeating this
3876 command activates `transient-mark-mode' temporarily.
3878 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3879 jump to the mark, and set the mark from
3880 position popped off the local mark ring \(this does not affect the global
3881 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3882 mark ring \(see `pop-global-mark'\).
3884 If `set-mark-command-repeat-pop' is non-nil, repeating
3885 the \\[set-mark-command] command with no prefix argument pops the next position
3886 off the local (or global) mark ring and jumps there.
3888 With \\[universal-argument] \\[universal-argument] as prefix
3889 argument, unconditionally set mark where point is, even if
3890 `set-mark-command-repeat-pop' is non-nil.
3892 Novice Emacs Lisp programmers often try to use the mark for the wrong
3893 purposes. See the documentation of `set-mark' for more information."
3894 (interactive "P")
3895 (cond ((eq transient-mark-mode 'lambda)
3896 (setq transient-mark-mode nil))
3897 ((eq (car-safe transient-mark-mode) 'only)
3898 (deactivate-mark)))
3899 (cond
3900 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3901 (push-mark-command nil))
3902 ((not (eq this-command 'set-mark-command))
3903 (if arg
3904 (pop-to-mark-command)
3905 (push-mark-command t)))
3906 ((and set-mark-command-repeat-pop
3907 (eq last-command 'pop-to-mark-command))
3908 (setq this-command 'pop-to-mark-command)
3909 (pop-to-mark-command))
3910 ((and set-mark-command-repeat-pop
3911 (eq last-command 'pop-global-mark)
3912 (not arg))
3913 (setq this-command 'pop-global-mark)
3914 (pop-global-mark))
3915 (arg
3916 (setq this-command 'pop-to-mark-command)
3917 (pop-to-mark-command))
3918 ((eq last-command 'set-mark-command)
3919 (if (region-active-p)
3920 (progn
3921 (deactivate-mark)
3922 (message "Mark deactivated"))
3923 (activate-mark)
3924 (message "Mark activated")))
3926 (push-mark-command nil)
3927 (if set-mark-default-inactive (deactivate-mark)))))
3929 (defun push-mark (&optional location nomsg activate)
3930 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3931 If the last global mark pushed was not in the current buffer,
3932 also push LOCATION on the global mark ring.
3933 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3935 Novice Emacs Lisp programmers often try to use the mark for the wrong
3936 purposes. See the documentation of `set-mark' for more information.
3938 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
3939 (unless (null (mark t))
3940 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3941 (when (> (length mark-ring) mark-ring-max)
3942 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3943 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3944 (set-marker (mark-marker) (or location (point)) (current-buffer))
3945 ;; Now push the mark on the global mark ring.
3946 (if (and global-mark-ring
3947 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3948 ;; The last global mark pushed was in this same buffer.
3949 ;; Don't push another one.
3951 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3952 (when (> (length global-mark-ring) global-mark-ring-max)
3953 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3954 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3955 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3956 (message "Mark set"))
3957 (if (or activate (not transient-mark-mode))
3958 (set-mark (mark t)))
3959 nil)
3961 (defun pop-mark ()
3962 "Pop off mark ring into the buffer's actual mark.
3963 Does not set point. Does nothing if mark ring is empty."
3964 (when mark-ring
3965 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3966 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3967 (move-marker (car mark-ring) nil)
3968 (if (null (mark t)) (ding))
3969 (setq mark-ring (cdr mark-ring)))
3970 (deactivate-mark))
3972 (define-obsolete-function-alias
3973 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
3974 (defun exchange-point-and-mark (&optional arg)
3975 "Put the mark where point is now, and point where the mark is now.
3976 This command works even when the mark is not active,
3977 and it reactivates the mark.
3979 If Transient Mark mode is on, a prefix ARG deactivates the mark
3980 if it is active, and otherwise avoids reactivating it. If
3981 Transient Mark mode is off, a prefix ARG enables Transient Mark
3982 mode temporarily."
3983 (interactive "P")
3984 (let ((omark (mark t))
3985 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
3986 (if (null omark)
3987 (error "No mark set in this buffer"))
3988 (deactivate-mark)
3989 (set-mark (point))
3990 (goto-char omark)
3991 (if set-mark-default-inactive (deactivate-mark))
3992 (cond (temp-highlight
3993 (setq transient-mark-mode (cons 'only transient-mark-mode)))
3994 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
3995 (not (or arg (region-active-p))))
3996 (deactivate-mark))
3997 (t (activate-mark)))
3998 nil))
4000 (defcustom shift-select-mode t
4001 "When non-nil, shifted motion keys activate the mark momentarily.
4003 While the mark is activated in this way, any shift-translated point
4004 motion key extends the region, and if Transient Mark mode was off, it
4005 is temporarily turned on. Furthermore, the mark will be deactivated
4006 by any subsequent point motion key that was not shift-translated, or
4007 by any action that normally deactivates the mark in Transient Mark mode.
4009 See `this-command-keys-shift-translated' for the meaning of
4010 shift-translation."
4011 :type 'boolean
4012 :group 'editing-basics)
4014 (defun handle-shift-selection ()
4015 "Activate/deactivate mark depending on invocation thru shift translation.
4016 This function is called by `call-interactively' when a command
4017 with a `^' character in its `interactive' spec is invoked, before
4018 running the command itself.
4020 If `shift-select-mode' is enabled and the command was invoked
4021 through shift translation, set the mark and activate the region
4022 temporarily, unless it was already set in this way. See
4023 `this-command-keys-shift-translated' for the meaning of shift
4024 translation.
4026 Otherwise, if the region has been activated temporarily,
4027 deactivate it, and restore the variable `transient-mark-mode' to
4028 its earlier value."
4029 (cond ((and shift-select-mode this-command-keys-shift-translated)
4030 (unless (and mark-active
4031 (eq (car-safe transient-mark-mode) 'only))
4032 (setq transient-mark-mode
4033 (cons 'only
4034 (unless (eq transient-mark-mode 'lambda)
4035 transient-mark-mode)))
4036 (push-mark nil nil t)))
4037 ((eq (car-safe transient-mark-mode) 'only)
4038 (setq transient-mark-mode (cdr transient-mark-mode))
4039 (deactivate-mark))))
4041 (define-minor-mode transient-mark-mode
4042 "Toggle Transient Mark mode.
4043 With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
4045 In Transient Mark mode, when the mark is active, the region is highlighted.
4046 Changing the buffer \"deactivates\" the mark.
4047 So do certain other operations that set the mark
4048 but whose main purpose is something else--for example,
4049 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4051 You can also deactivate the mark by typing \\[keyboard-quit] or
4052 \\[keyboard-escape-quit].
4054 Many commands change their behavior when Transient Mark mode is in effect
4055 and the mark is active, by acting on the region instead of their usual
4056 default part of the buffer's text. Examples of such commands include
4057 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
4058 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4059 Invoke \\[apropos-documentation] and type \"transient\" or
4060 \"mark.*active\" at the prompt, to see the documentation of
4061 commands which are sensitive to the Transient Mark mode."
4062 :global t
4063 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4064 :variable transient-mark-mode)
4066 (defvar widen-automatically t
4067 "Non-nil means it is ok for commands to call `widen' when they want to.
4068 Some commands will do this in order to go to positions outside
4069 the current accessible part of the buffer.
4071 If `widen-automatically' is nil, these commands will do something else
4072 as a fallback, and won't change the buffer bounds.")
4074 (defvar non-essential nil
4075 "Whether the currently executing code is performing an essential task.
4076 This variable should be non-nil only when running code which should not
4077 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4078 user for a password when we are simply scanning a set of files in the
4079 background or displaying possible completions before the user even asked
4080 for it.")
4082 (defun pop-global-mark ()
4083 "Pop off global mark ring and jump to the top location."
4084 (interactive)
4085 ;; Pop entries which refer to non-existent buffers.
4086 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4087 (setq global-mark-ring (cdr global-mark-ring)))
4088 (or global-mark-ring
4089 (error "No global mark set"))
4090 (let* ((marker (car global-mark-ring))
4091 (buffer (marker-buffer marker))
4092 (position (marker-position marker)))
4093 (setq global-mark-ring (nconc (cdr global-mark-ring)
4094 (list (car global-mark-ring))))
4095 (set-buffer buffer)
4096 (or (and (>= position (point-min))
4097 (<= position (point-max)))
4098 (if widen-automatically
4099 (widen)
4100 (error "Global mark position is outside accessible part of buffer")))
4101 (goto-char position)
4102 (pop-to-buffer-same-window buffer)))
4104 (defcustom next-line-add-newlines nil
4105 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4106 :type 'boolean
4107 :version "21.1"
4108 :group 'editing-basics)
4110 (defun next-line (&optional arg try-vscroll)
4111 "Move cursor vertically down ARG lines.
4112 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4113 If there is no character in the target line exactly under the current column,
4114 the cursor is positioned after the character in that line which spans this
4115 column, or at the end of the line if it is not long enough.
4116 If there is no line in the buffer after this one, behavior depends on the
4117 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4118 to create a line, and moves the cursor to that line. Otherwise it moves the
4119 cursor to the end of the buffer.
4121 If the variable `line-move-visual' is non-nil, this command moves
4122 by display lines. Otherwise, it moves by buffer lines, without
4123 taking variable-width characters or continued lines into account.
4125 The command \\[set-goal-column] can be used to create
4126 a semipermanent goal column for this command.
4127 Then instead of trying to move exactly vertically (or as close as possible),
4128 this command moves to the specified goal column (or as close as possible).
4129 The goal column is stored in the variable `goal-column', which is nil
4130 when there is no goal column.
4132 If you are thinking of using this in a Lisp program, consider
4133 using `forward-line' instead. It is usually easier to use
4134 and more reliable (no dependence on goal column, etc.)."
4135 (interactive "^p\np")
4136 (or arg (setq arg 1))
4137 (if (and next-line-add-newlines (= arg 1))
4138 (if (save-excursion (end-of-line) (eobp))
4139 ;; When adding a newline, don't expand an abbrev.
4140 (let ((abbrev-mode nil))
4141 (end-of-line)
4142 (insert (if use-hard-newlines hard-newline "\n")))
4143 (line-move arg nil nil try-vscroll))
4144 (if (called-interactively-p 'interactive)
4145 (condition-case err
4146 (line-move arg nil nil try-vscroll)
4147 ((beginning-of-buffer end-of-buffer)
4148 (signal (car err) (cdr err))))
4149 (line-move arg nil nil try-vscroll)))
4150 nil)
4152 (defun previous-line (&optional arg try-vscroll)
4153 "Move cursor vertically up ARG lines.
4154 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4155 If there is no character in the target line exactly over the current column,
4156 the cursor is positioned after the character in that line which spans this
4157 column, or at the end of the line if it is not long enough.
4159 If the variable `line-move-visual' is non-nil, this command moves
4160 by display lines. Otherwise, it moves by buffer lines, without
4161 taking variable-width characters or continued lines into account.
4163 The command \\[set-goal-column] can be used to create
4164 a semipermanent goal column for this command.
4165 Then instead of trying to move exactly vertically (or as close as possible),
4166 this command moves to the specified goal column (or as close as possible).
4167 The goal column is stored in the variable `goal-column', which is nil
4168 when there is no goal column.
4170 If you are thinking of using this in a Lisp program, consider using
4171 `forward-line' with a negative argument instead. It is usually easier
4172 to use and more reliable (no dependence on goal column, etc.)."
4173 (interactive "^p\np")
4174 (or arg (setq arg 1))
4175 (if (called-interactively-p 'interactive)
4176 (condition-case err
4177 (line-move (- arg) nil nil try-vscroll)
4178 ((beginning-of-buffer end-of-buffer)
4179 (signal (car err) (cdr err))))
4180 (line-move (- arg) nil nil try-vscroll))
4181 nil)
4183 (defcustom track-eol nil
4184 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4185 This means moving to the end of each line moved onto.
4186 The beginning of a blank line does not count as the end of a line.
4187 This has no effect when `line-move-visual' is non-nil."
4188 :type 'boolean
4189 :group 'editing-basics)
4191 (defcustom goal-column nil
4192 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
4193 :type '(choice integer
4194 (const :tag "None" nil))
4195 :group 'editing-basics)
4196 (make-variable-buffer-local 'goal-column)
4198 (defvar temporary-goal-column 0
4199 "Current goal column for vertical motion.
4200 It is the column where point was at the start of the current run
4201 of vertical motion commands.
4203 When moving by visual lines via `line-move-visual', it is a cons
4204 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4205 divided by the default column width, and HSCROLL is the number of
4206 columns by which window is scrolled from left margin.
4208 When the `track-eol' feature is doing its job, the value is
4209 `most-positive-fixnum'.")
4211 (defcustom line-move-ignore-invisible t
4212 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
4213 Outline mode sets this."
4214 :type 'boolean
4215 :group 'editing-basics)
4217 (defcustom line-move-visual t
4218 "When non-nil, `line-move' moves point by visual lines.
4219 This movement is based on where the cursor is displayed on the
4220 screen, instead of relying on buffer contents alone. It takes
4221 into account variable-width characters and line continuation.
4222 If nil, `line-move' moves point by logical lines."
4223 :type 'boolean
4224 :group 'editing-basics
4225 :version "23.1")
4227 ;; Returns non-nil if partial move was done.
4228 (defun line-move-partial (arg noerror to-end)
4229 (if (< arg 0)
4230 ;; Move backward (up).
4231 ;; If already vscrolled, reduce vscroll
4232 (let ((vs (window-vscroll nil t)))
4233 (when (> vs (frame-char-height))
4234 (set-window-vscroll nil (- vs (frame-char-height)) t)))
4236 ;; Move forward (down).
4237 (let* ((lh (window-line-height -1))
4238 (vpos (nth 1 lh))
4239 (ypos (nth 2 lh))
4240 (rbot (nth 3 lh))
4241 py vs)
4242 (when (or (null lh)
4243 (>= rbot (frame-char-height))
4244 (<= ypos (- (frame-char-height))))
4245 (unless lh
4246 (let ((wend (pos-visible-in-window-p t nil t)))
4247 (setq rbot (nth 3 wend)
4248 vpos (nth 5 wend))))
4249 (cond
4250 ;; If last line of window is fully visible, move forward.
4251 ((or (null rbot) (= rbot 0))
4252 nil)
4253 ;; If cursor is not in the bottom scroll margin, move forward.
4254 ((and (> vpos 0)
4255 (< (setq py
4256 (or (nth 1 (window-line-height))
4257 (let ((ppos (posn-at-point)))
4258 (cdr (or (posn-actual-col-row ppos)
4259 (posn-col-row ppos))))))
4260 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
4261 nil)
4262 ;; When already vscrolled, we vscroll some more if we can,
4263 ;; or clear vscroll and move forward at end of tall image.
4264 ((> (setq vs (window-vscroll nil t)) 0)
4265 (when (> rbot 0)
4266 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
4267 ;; If cursor just entered the bottom scroll margin, move forward,
4268 ;; but also vscroll one line so redisplay wont recenter.
4269 ((and (> vpos 0)
4270 (= py (min (- (window-text-height) scroll-margin 1)
4271 (1- vpos))))
4272 (set-window-vscroll nil (frame-char-height) t)
4273 (line-move-1 arg noerror to-end)
4275 ;; If there are lines above the last line, scroll-up one line.
4276 ((> vpos 0)
4277 (scroll-up 1)
4279 ;; Finally, start vscroll.
4281 (set-window-vscroll nil (frame-char-height) t)))))))
4284 ;; This is like line-move-1 except that it also performs
4285 ;; vertical scrolling of tall images if appropriate.
4286 ;; That is not really a clean thing to do, since it mixes
4287 ;; scrolling with cursor motion. But so far we don't have
4288 ;; a cleaner solution to the problem of making C-n do something
4289 ;; useful given a tall image.
4290 (defun line-move (arg &optional noerror to-end try-vscroll)
4291 (unless (and auto-window-vscroll try-vscroll
4292 ;; Only vscroll for single line moves
4293 (= (abs arg) 1)
4294 ;; But don't vscroll in a keyboard macro.
4295 (not defining-kbd-macro)
4296 (not executing-kbd-macro)
4297 (line-move-partial arg noerror to-end))
4298 (set-window-vscroll nil 0 t)
4299 (if line-move-visual
4300 (line-move-visual arg noerror)
4301 (line-move-1 arg noerror to-end))))
4303 ;; Display-based alternative to line-move-1.
4304 ;; Arg says how many lines to move. The value is t if we can move the
4305 ;; specified number of lines.
4306 (defun line-move-visual (arg &optional noerror)
4307 (let ((opoint (point))
4308 (hscroll (window-hscroll))
4309 target-hscroll)
4310 ;; Check if the previous command was a line-motion command, or if
4311 ;; we were called from some other command.
4312 (if (and (consp temporary-goal-column)
4313 (memq last-command `(next-line previous-line ,this-command)))
4314 ;; If so, there's no need to reset `temporary-goal-column',
4315 ;; but we may need to hscroll.
4316 (if (or (/= (cdr temporary-goal-column) hscroll)
4317 (> (cdr temporary-goal-column) 0))
4318 (setq target-hscroll (cdr temporary-goal-column)))
4319 ;; Otherwise, we should reset `temporary-goal-column'.
4320 (let ((posn (posn-at-point)))
4321 (cond
4322 ;; Handle the `overflow-newline-into-fringe' case:
4323 ((eq (nth 1 posn) 'right-fringe)
4324 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
4325 ((car (posn-x-y posn))
4326 (setq temporary-goal-column
4327 (cons (/ (float (car (posn-x-y posn)))
4328 (frame-char-width)) hscroll))))))
4329 (if target-hscroll
4330 (set-window-hscroll (selected-window) target-hscroll))
4331 (or (and (= (vertical-motion
4332 (cons (or goal-column
4333 (if (consp temporary-goal-column)
4334 (car temporary-goal-column)
4335 temporary-goal-column))
4336 arg))
4337 arg)
4338 (or (>= arg 0)
4339 (/= (point) opoint)
4340 ;; If the goal column lies on a display string,
4341 ;; `vertical-motion' advances the cursor to the end
4342 ;; of the string. For arg < 0, this can cause the
4343 ;; cursor to get stuck. (Bug#3020).
4344 (= (vertical-motion arg) arg)))
4345 (unless noerror
4346 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
4347 nil)))))
4349 ;; This is the guts of next-line and previous-line.
4350 ;; Arg says how many lines to move.
4351 ;; The value is t if we can move the specified number of lines.
4352 (defun line-move-1 (arg &optional noerror _to-end)
4353 ;; Don't run any point-motion hooks, and disregard intangibility,
4354 ;; for intermediate positions.
4355 (let ((inhibit-point-motion-hooks t)
4356 (opoint (point))
4357 (orig-arg arg))
4358 (if (consp temporary-goal-column)
4359 (setq temporary-goal-column (+ (car temporary-goal-column)
4360 (cdr temporary-goal-column))))
4361 (unwind-protect
4362 (progn
4363 (if (not (memq last-command '(next-line previous-line)))
4364 (setq temporary-goal-column
4365 (if (and track-eol (eolp)
4366 ;; Don't count beg of empty line as end of line
4367 ;; unless we just did explicit end-of-line.
4368 (or (not (bolp)) (eq last-command 'move-end-of-line)))
4369 most-positive-fixnum
4370 (current-column))))
4372 (if (not (or (integerp selective-display)
4373 line-move-ignore-invisible))
4374 ;; Use just newline characters.
4375 ;; Set ARG to 0 if we move as many lines as requested.
4376 (or (if (> arg 0)
4377 (progn (if (> arg 1) (forward-line (1- arg)))
4378 ;; This way of moving forward ARG lines
4379 ;; verifies that we have a newline after the last one.
4380 ;; It doesn't get confused by intangible text.
4381 (end-of-line)
4382 (if (zerop (forward-line 1))
4383 (setq arg 0)))
4384 (and (zerop (forward-line arg))
4385 (bolp)
4386 (setq arg 0)))
4387 (unless noerror
4388 (signal (if (< arg 0)
4389 'beginning-of-buffer
4390 'end-of-buffer)
4391 nil)))
4392 ;; Move by arg lines, but ignore invisible ones.
4393 (let (done)
4394 (while (and (> arg 0) (not done))
4395 ;; If the following character is currently invisible,
4396 ;; skip all characters with that same `invisible' property value.
4397 (while (and (not (eobp)) (invisible-p (point)))
4398 (goto-char (next-char-property-change (point))))
4399 ;; Move a line.
4400 ;; We don't use `end-of-line', since we want to escape
4401 ;; from field boundaries occurring exactly at point.
4402 (goto-char (constrain-to-field
4403 (let ((inhibit-field-text-motion t))
4404 (line-end-position))
4405 (point) t t
4406 'inhibit-line-move-field-capture))
4407 ;; If there's no invisibility here, move over the newline.
4408 (cond
4409 ((eobp)
4410 (if (not noerror)
4411 (signal 'end-of-buffer nil)
4412 (setq done t)))
4413 ((and (> arg 1) ;; Use vertical-motion for last move
4414 (not (integerp selective-display))
4415 (not (invisible-p (point))))
4416 ;; We avoid vertical-motion when possible
4417 ;; because that has to fontify.
4418 (forward-line 1))
4419 ;; Otherwise move a more sophisticated way.
4420 ((zerop (vertical-motion 1))
4421 (if (not noerror)
4422 (signal 'end-of-buffer nil)
4423 (setq done t))))
4424 (unless done
4425 (setq arg (1- arg))))
4426 ;; The logic of this is the same as the loop above,
4427 ;; it just goes in the other direction.
4428 (while (and (< arg 0) (not done))
4429 ;; For completely consistency with the forward-motion
4430 ;; case, we should call beginning-of-line here.
4431 ;; However, if point is inside a field and on a
4432 ;; continued line, the call to (vertical-motion -1)
4433 ;; below won't move us back far enough; then we return
4434 ;; to the same column in line-move-finish, and point
4435 ;; gets stuck -- cyd
4436 (forward-line 0)
4437 (cond
4438 ((bobp)
4439 (if (not noerror)
4440 (signal 'beginning-of-buffer nil)
4441 (setq done t)))
4442 ((and (< arg -1) ;; Use vertical-motion for last move
4443 (not (integerp selective-display))
4444 (not (invisible-p (1- (point)))))
4445 (forward-line -1))
4446 ((zerop (vertical-motion -1))
4447 (if (not noerror)
4448 (signal 'beginning-of-buffer nil)
4449 (setq done t))))
4450 (unless done
4451 (setq arg (1+ arg))
4452 (while (and ;; Don't move over previous invis lines
4453 ;; if our target is the middle of this line.
4454 (or (zerop (or goal-column temporary-goal-column))
4455 (< arg 0))
4456 (not (bobp)) (invisible-p (1- (point))))
4457 (goto-char (previous-char-property-change (point))))))))
4458 ;; This is the value the function returns.
4459 (= arg 0))
4461 (cond ((> arg 0)
4462 ;; If we did not move down as far as desired, at least go
4463 ;; to end of line. Be sure to call point-entered and
4464 ;; point-left-hooks.
4465 (let* ((npoint (prog1 (line-end-position)
4466 (goto-char opoint)))
4467 (inhibit-point-motion-hooks nil))
4468 (goto-char npoint)))
4469 ((< arg 0)
4470 ;; If we did not move up as far as desired,
4471 ;; at least go to beginning of line.
4472 (let* ((npoint (prog1 (line-beginning-position)
4473 (goto-char opoint)))
4474 (inhibit-point-motion-hooks nil))
4475 (goto-char npoint)))
4477 (line-move-finish (or goal-column temporary-goal-column)
4478 opoint (> orig-arg 0)))))))
4480 (defun line-move-finish (column opoint forward)
4481 (let ((repeat t))
4482 (while repeat
4483 ;; Set REPEAT to t to repeat the whole thing.
4484 (setq repeat nil)
4486 (let (new
4487 (old (point))
4488 (line-beg (line-beginning-position))
4489 (line-end
4490 ;; Compute the end of the line
4491 ;; ignoring effectively invisible newlines.
4492 (save-excursion
4493 ;; Like end-of-line but ignores fields.
4494 (skip-chars-forward "^\n")
4495 (while (and (not (eobp)) (invisible-p (point)))
4496 (goto-char (next-char-property-change (point)))
4497 (skip-chars-forward "^\n"))
4498 (point))))
4500 ;; Move to the desired column.
4501 (line-move-to-column (truncate column))
4503 ;; Corner case: suppose we start out in a field boundary in
4504 ;; the middle of a continued line. When we get to
4505 ;; line-move-finish, point is at the start of a new *screen*
4506 ;; line but the same text line; then line-move-to-column would
4507 ;; move us backwards. Test using C-n with point on the "x" in
4508 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4509 (and forward
4510 (< (point) old)
4511 (goto-char old))
4513 (setq new (point))
4515 ;; Process intangibility within a line.
4516 ;; With inhibit-point-motion-hooks bound to nil, a call to
4517 ;; goto-char moves point past intangible text.
4519 ;; However, inhibit-point-motion-hooks controls both the
4520 ;; intangibility and the point-entered/point-left hooks. The
4521 ;; following hack avoids calling the point-* hooks
4522 ;; unnecessarily. Note that we move *forward* past intangible
4523 ;; text when the initial and final points are the same.
4524 (goto-char new)
4525 (let ((inhibit-point-motion-hooks nil))
4526 (goto-char new)
4528 ;; If intangibility moves us to a different (later) place
4529 ;; in the same line, use that as the destination.
4530 (if (<= (point) line-end)
4531 (setq new (point))
4532 ;; If that position is "too late",
4533 ;; try the previous allowable position.
4534 ;; See if it is ok.
4535 (backward-char)
4536 (if (if forward
4537 ;; If going forward, don't accept the previous
4538 ;; allowable position if it is before the target line.
4539 (< line-beg (point))
4540 ;; If going backward, don't accept the previous
4541 ;; allowable position if it is still after the target line.
4542 (<= (point) line-end))
4543 (setq new (point))
4544 ;; As a last resort, use the end of the line.
4545 (setq new line-end))))
4547 ;; Now move to the updated destination, processing fields
4548 ;; as well as intangibility.
4549 (goto-char opoint)
4550 (let ((inhibit-point-motion-hooks nil))
4551 (goto-char
4552 ;; Ignore field boundaries if the initial and final
4553 ;; positions have the same `field' property, even if the
4554 ;; fields are non-contiguous. This seems to be "nicer"
4555 ;; behavior in many situations.
4556 (if (eq (get-char-property new 'field)
4557 (get-char-property opoint 'field))
4559 (constrain-to-field new opoint t t
4560 'inhibit-line-move-field-capture))))
4562 ;; If all this moved us to a different line,
4563 ;; retry everything within that new line.
4564 (when (or (< (point) line-beg) (> (point) line-end))
4565 ;; Repeat the intangibility and field processing.
4566 (setq repeat t))))))
4568 (defun line-move-to-column (col)
4569 "Try to find column COL, considering invisibility.
4570 This function works only in certain cases,
4571 because what we really need is for `move-to-column'
4572 and `current-column' to be able to ignore invisible text."
4573 (if (zerop col)
4574 (beginning-of-line)
4575 (move-to-column col))
4577 (when (and line-move-ignore-invisible
4578 (not (bolp)) (invisible-p (1- (point))))
4579 (let ((normal-location (point))
4580 (normal-column (current-column)))
4581 ;; If the following character is currently invisible,
4582 ;; skip all characters with that same `invisible' property value.
4583 (while (and (not (eobp))
4584 (invisible-p (point)))
4585 (goto-char (next-char-property-change (point))))
4586 ;; Have we advanced to a larger column position?
4587 (if (> (current-column) normal-column)
4588 ;; We have made some progress towards the desired column.
4589 ;; See if we can make any further progress.
4590 (line-move-to-column (+ (current-column) (- col normal-column)))
4591 ;; Otherwise, go to the place we originally found
4592 ;; and move back over invisible text.
4593 ;; that will get us to the same place on the screen
4594 ;; but with a more reasonable buffer position.
4595 (goto-char normal-location)
4596 (let ((line-beg (line-beginning-position)))
4597 (while (and (not (bolp)) (invisible-p (1- (point))))
4598 (goto-char (previous-char-property-change (point) line-beg))))))))
4600 (defun move-end-of-line (arg)
4601 "Move point to end of current line as displayed.
4602 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4603 If point reaches the beginning or end of buffer, it stops there.
4605 To ignore the effects of the `intangible' text or overlay
4606 property, bind `inhibit-point-motion-hooks' to t.
4607 If there is an image in the current line, this function
4608 disregards newlines that are part of the text on which the image
4609 rests."
4610 (interactive "^p")
4611 (or arg (setq arg 1))
4612 (let (done)
4613 (while (not done)
4614 (let ((newpos
4615 (save-excursion
4616 (let ((goal-column 0)
4617 (line-move-visual nil))
4618 (and (line-move arg t)
4619 ;; With bidi reordering, we may not be at bol,
4620 ;; so make sure we are.
4621 (skip-chars-backward "^\n")
4622 (not (bobp))
4623 (progn
4624 (while (and (not (bobp)) (invisible-p (1- (point))))
4625 (goto-char (previous-single-char-property-change
4626 (point) 'invisible)))
4627 (backward-char 1)))
4628 (point)))))
4629 (goto-char newpos)
4630 (if (and (> (point) newpos)
4631 (eq (preceding-char) ?\n))
4632 (backward-char 1)
4633 (if (and (> (point) newpos) (not (eobp))
4634 (not (eq (following-char) ?\n)))
4635 ;; If we skipped something intangible and now we're not
4636 ;; really at eol, keep going.
4637 (setq arg 1)
4638 (setq done t)))))))
4640 (defun move-beginning-of-line (arg)
4641 "Move point to beginning of current line as displayed.
4642 \(If there's an image in the line, this disregards newlines
4643 which are part of the text that the image rests on.)
4645 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4646 If point reaches the beginning or end of buffer, it stops there.
4647 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4648 (interactive "^p")
4649 (or arg (setq arg 1))
4651 (let ((orig (point))
4652 first-vis first-vis-field-value)
4654 ;; Move by lines, if ARG is not 1 (the default).
4655 (if (/= arg 1)
4656 (let ((line-move-visual nil))
4657 (line-move (1- arg) t)))
4659 ;; Move to beginning-of-line, ignoring fields and invisibles.
4660 (skip-chars-backward "^\n")
4661 (while (and (not (bobp)) (invisible-p (1- (point))))
4662 (goto-char (previous-char-property-change (point)))
4663 (skip-chars-backward "^\n"))
4665 ;; Now find first visible char in the line
4666 (while (and (not (eobp)) (invisible-p (point)))
4667 (goto-char (next-char-property-change (point))))
4668 (setq first-vis (point))
4670 ;; See if fields would stop us from reaching FIRST-VIS.
4671 (setq first-vis-field-value
4672 (constrain-to-field first-vis orig (/= arg 1) t nil))
4674 (goto-char (if (/= first-vis-field-value first-vis)
4675 ;; If yes, obey them.
4676 first-vis-field-value
4677 ;; Otherwise, move to START with attention to fields.
4678 ;; (It is possible that fields never matter in this case.)
4679 (constrain-to-field (point) orig
4680 (/= arg 1) t nil)))))
4683 ;; Many people have said they rarely use this feature, and often type
4684 ;; it by accident. Maybe it shouldn't even be on a key.
4685 (put 'set-goal-column 'disabled t)
4687 (defun set-goal-column (arg)
4688 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4689 Those commands will move to this position in the line moved to
4690 rather than trying to keep the same horizontal position.
4691 With a non-nil argument ARG, clears out the goal column
4692 so that \\[next-line] and \\[previous-line] resume vertical motion.
4693 The goal column is stored in the variable `goal-column'."
4694 (interactive "P")
4695 (if arg
4696 (progn
4697 (setq goal-column nil)
4698 (message "No goal column"))
4699 (setq goal-column (current-column))
4700 ;; The older method below can be erroneous if `set-goal-column' is bound
4701 ;; to a sequence containing %
4702 ;;(message (substitute-command-keys
4703 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4704 ;;goal-column)
4705 (message "%s"
4706 (concat
4707 (format "Goal column %d " goal-column)
4708 (substitute-command-keys
4709 "(use \\[set-goal-column] with an arg to unset it)")))
4712 nil)
4714 ;;; Editing based on visual lines, as opposed to logical lines.
4716 (defun end-of-visual-line (&optional n)
4717 "Move point to end of current visual line.
4718 With argument N not nil or 1, move forward N - 1 visual lines first.
4719 If point reaches the beginning or end of buffer, it stops there.
4720 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4721 (interactive "^p")
4722 (or n (setq n 1))
4723 (if (/= n 1)
4724 (let ((line-move-visual t))
4725 (line-move (1- n) t)))
4726 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
4727 ;; constrain to field boundaries, so we don't either.
4728 (vertical-motion (cons (window-width) 0)))
4730 (defun beginning-of-visual-line (&optional n)
4731 "Move point to beginning of current visual line.
4732 With argument N not nil or 1, move forward N - 1 visual lines first.
4733 If point reaches the beginning or end of buffer, it stops there.
4734 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4735 (interactive "^p")
4736 (or n (setq n 1))
4737 (let ((opoint (point)))
4738 (if (/= n 1)
4739 (let ((line-move-visual t))
4740 (line-move (1- n) t)))
4741 (vertical-motion 0)
4742 ;; Constrain to field boundaries, like `move-beginning-of-line'.
4743 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
4745 (defun kill-visual-line (&optional arg)
4746 "Kill the rest of the visual line.
4747 With prefix argument ARG, kill that many visual lines from point.
4748 If ARG is negative, kill visual lines backward.
4749 If ARG is zero, kill the text before point on the current visual
4750 line.
4752 If you want to append the killed line to the last killed text,
4753 use \\[append-next-kill] before \\[kill-line].
4755 If the buffer is read-only, Emacs will beep and refrain from deleting
4756 the line, but put the line in the kill ring anyway. This means that
4757 you can use this command to copy text from a read-only buffer.
4758 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4759 even beep.)"
4760 (interactive "P")
4761 ;; Like in `kill-line', it's better to move point to the other end
4762 ;; of the kill before killing.
4763 (let ((opoint (point))
4764 (kill-whole-line (and kill-whole-line (bolp))))
4765 (if arg
4766 (vertical-motion (prefix-numeric-value arg))
4767 (end-of-visual-line 1)
4768 (if (= (point) opoint)
4769 (vertical-motion 1)
4770 ;; Skip any trailing whitespace at the end of the visual line.
4771 ;; We used to do this only if `show-trailing-whitespace' is
4772 ;; nil, but that's wrong; the correct thing would be to check
4773 ;; whether the trailing whitespace is highlighted. But, it's
4774 ;; OK to just do this unconditionally.
4775 (skip-chars-forward " \t")))
4776 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
4777 (1+ (point))
4778 (point)))))
4780 (defun next-logical-line (&optional arg try-vscroll)
4781 "Move cursor vertically down ARG lines.
4782 This is identical to `next-line', except that it always moves
4783 by logical lines instead of visual lines, ignoring the value of
4784 the variable `line-move-visual'."
4785 (interactive "^p\np")
4786 (let ((line-move-visual nil))
4787 (with-no-warnings
4788 (next-line arg try-vscroll))))
4790 (defun previous-logical-line (&optional arg try-vscroll)
4791 "Move cursor vertically up ARG lines.
4792 This is identical to `previous-line', except that it always moves
4793 by logical lines instead of visual lines, ignoring the value of
4794 the variable `line-move-visual'."
4795 (interactive "^p\np")
4796 (let ((line-move-visual nil))
4797 (with-no-warnings
4798 (previous-line arg try-vscroll))))
4800 (defgroup visual-line nil
4801 "Editing based on visual lines."
4802 :group 'convenience
4803 :version "23.1")
4805 (defvar visual-line-mode-map
4806 (let ((map (make-sparse-keymap)))
4807 (define-key map [remap kill-line] 'kill-visual-line)
4808 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4809 (define-key map [remap move-end-of-line] 'end-of-visual-line)
4810 ;; These keybindings interfere with xterm function keys. Are
4811 ;; there any other suitable bindings?
4812 ;; (define-key map "\M-[" 'previous-logical-line)
4813 ;; (define-key map "\M-]" 'next-logical-line)
4814 map))
4816 (defcustom visual-line-fringe-indicators '(nil nil)
4817 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4818 The value should be a list of the form (LEFT RIGHT), where LEFT
4819 and RIGHT are symbols representing the bitmaps to display, to
4820 indicate wrapped lines, in the left and right fringes respectively.
4821 See also `fringe-indicator-alist'.
4822 The default is not to display fringe indicators for wrapped lines.
4823 This variable does not affect fringe indicators displayed for
4824 other purposes."
4825 :type '(list (choice (const :tag "Hide left indicator" nil)
4826 (const :tag "Left curly arrow" left-curly-arrow)
4827 (symbol :tag "Other bitmap"))
4828 (choice (const :tag "Hide right indicator" nil)
4829 (const :tag "Right curly arrow" right-curly-arrow)
4830 (symbol :tag "Other bitmap")))
4831 :set (lambda (symbol value)
4832 (dolist (buf (buffer-list))
4833 (with-current-buffer buf
4834 (when (and (boundp 'visual-line-mode)
4835 (symbol-value 'visual-line-mode))
4836 (setq fringe-indicator-alist
4837 (cons (cons 'continuation value)
4838 (assq-delete-all
4839 'continuation
4840 (copy-tree fringe-indicator-alist)))))))
4841 (set-default symbol value)))
4843 (defvar visual-line--saved-state nil)
4845 (define-minor-mode visual-line-mode
4846 "Redefine simple editing commands to act on visual lines, not logical lines.
4847 This also turns on `word-wrap' in the buffer."
4848 :keymap visual-line-mode-map
4849 :group 'visual-line
4850 :lighter " Wrap"
4851 (if visual-line-mode
4852 (progn
4853 (set (make-local-variable 'visual-line--saved-state) nil)
4854 ;; Save the local values of some variables, to be restored if
4855 ;; visual-line-mode is turned off.
4856 (dolist (var '(line-move-visual truncate-lines
4857 truncate-partial-width-windows
4858 word-wrap fringe-indicator-alist))
4859 (if (local-variable-p var)
4860 (push (cons var (symbol-value var))
4861 visual-line--saved-state)))
4862 (set (make-local-variable 'line-move-visual) t)
4863 (set (make-local-variable 'truncate-partial-width-windows) nil)
4864 (setq truncate-lines nil
4865 word-wrap t
4866 fringe-indicator-alist
4867 (cons (cons 'continuation visual-line-fringe-indicators)
4868 fringe-indicator-alist)))
4869 (kill-local-variable 'line-move-visual)
4870 (kill-local-variable 'word-wrap)
4871 (kill-local-variable 'truncate-lines)
4872 (kill-local-variable 'truncate-partial-width-windows)
4873 (kill-local-variable 'fringe-indicator-alist)
4874 (dolist (saved visual-line--saved-state)
4875 (set (make-local-variable (car saved)) (cdr saved)))
4876 (kill-local-variable 'visual-line--saved-state)))
4878 (defun turn-on-visual-line-mode ()
4879 (visual-line-mode 1))
4881 (define-globalized-minor-mode global-visual-line-mode
4882 visual-line-mode turn-on-visual-line-mode
4883 :lighter " vl")
4886 (defun transpose-chars (arg)
4887 "Interchange characters around point, moving forward one character.
4888 With prefix arg ARG, effect is to take character before point
4889 and drag it forward past ARG other characters (backward if ARG negative).
4890 If no argument and at end of line, the previous two chars are exchanged."
4891 (interactive "*P")
4892 (and (null arg) (eolp) (forward-char -1))
4893 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4895 (defun transpose-words (arg)
4896 "Interchange words around point, leaving point at end of them.
4897 With prefix arg ARG, effect is to take word before or around point
4898 and drag it forward past ARG other words (backward if ARG negative).
4899 If ARG is zero, the words around or after point and around or after mark
4900 are interchanged."
4901 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
4902 (interactive "*p")
4903 (transpose-subr 'forward-word arg))
4905 (defun transpose-sexps (arg)
4906 "Like \\[transpose-words] but applies to sexps.
4907 Does not work on a sexp that point is in the middle of
4908 if it is a list or string."
4909 (interactive "*p")
4910 (transpose-subr
4911 (lambda (arg)
4912 ;; Here we should try to simulate the behavior of
4913 ;; (cons (progn (forward-sexp x) (point))
4914 ;; (progn (forward-sexp (- x)) (point)))
4915 ;; Except that we don't want to rely on the second forward-sexp
4916 ;; putting us back to where we want to be, since forward-sexp-function
4917 ;; might do funny things like infix-precedence.
4918 (if (if (> arg 0)
4919 (looking-at "\\sw\\|\\s_")
4920 (and (not (bobp))
4921 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4922 ;; Jumping over a symbol. We might be inside it, mind you.
4923 (progn (funcall (if (> arg 0)
4924 'skip-syntax-backward 'skip-syntax-forward)
4925 "w_")
4926 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4927 ;; Otherwise, we're between sexps. Take a step back before jumping
4928 ;; to make sure we'll obey the same precedence no matter which direction
4929 ;; we're going.
4930 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4931 (cons (save-excursion (forward-sexp arg) (point))
4932 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4933 (not (zerop (funcall (if (> arg 0)
4934 'skip-syntax-forward
4935 'skip-syntax-backward)
4936 ".")))))
4937 (point)))))
4938 arg 'special))
4940 (defun transpose-lines (arg)
4941 "Exchange current line and previous line, leaving point after both.
4942 With argument ARG, takes previous line and moves it past ARG lines.
4943 With argument 0, interchanges line point is in with line mark is in."
4944 (interactive "*p")
4945 (transpose-subr (function
4946 (lambda (arg)
4947 (if (> arg 0)
4948 (progn
4949 ;; Move forward over ARG lines,
4950 ;; but create newlines if necessary.
4951 (setq arg (forward-line arg))
4952 (if (/= (preceding-char) ?\n)
4953 (setq arg (1+ arg)))
4954 (if (> arg 0)
4955 (newline arg)))
4956 (forward-line arg))))
4957 arg))
4959 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
4960 ;; which seems inconsistent with the ARG /= 0 case.
4961 ;; FIXME document SPECIAL.
4962 (defun transpose-subr (mover arg &optional special)
4963 "Subroutine to do the work of transposing objects.
4964 Works for lines, sentences, paragraphs, etc. MOVER is a function that
4965 moves forward by units of the given object (e.g. forward-sentence,
4966 forward-paragraph). If ARG is zero, exchanges the current object
4967 with the one containing mark. If ARG is an integer, moves the
4968 current object past ARG following (if ARG is positive) or
4969 preceding (if ARG is negative) objects, leaving point after the
4970 current object."
4971 (let ((aux (if special mover
4972 (lambda (x)
4973 (cons (progn (funcall mover x) (point))
4974 (progn (funcall mover (- x)) (point))))))
4975 pos1 pos2)
4976 (cond
4977 ((= arg 0)
4978 (save-excursion
4979 (setq pos1 (funcall aux 1))
4980 (goto-char (or (mark) (error "No mark set in this buffer")))
4981 (setq pos2 (funcall aux 1))
4982 (transpose-subr-1 pos1 pos2))
4983 (exchange-point-and-mark))
4984 ((> arg 0)
4985 (setq pos1 (funcall aux -1))
4986 (setq pos2 (funcall aux arg))
4987 (transpose-subr-1 pos1 pos2)
4988 (goto-char (car pos2)))
4990 (setq pos1 (funcall aux -1))
4991 (goto-char (car pos1))
4992 (setq pos2 (funcall aux arg))
4993 (transpose-subr-1 pos1 pos2)))))
4995 (defun transpose-subr-1 (pos1 pos2)
4996 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
4997 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
4998 (when (> (car pos1) (car pos2))
4999 (let ((swap pos1))
5000 (setq pos1 pos2 pos2 swap)))
5001 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
5002 (atomic-change-group
5003 (let (word2)
5004 ;; FIXME: We first delete the two pieces of text, so markers that
5005 ;; used to point to after the text end up pointing to before it :-(
5006 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
5007 (goto-char (car pos2))
5008 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
5009 (goto-char (car pos1))
5010 (insert word2))))
5012 (defun backward-word (&optional arg)
5013 "Move backward until encountering the beginning of a word.
5014 With argument ARG, do this that many times."
5015 (interactive "^p")
5016 (forward-word (- (or arg 1))))
5018 (defun mark-word (&optional arg allow-extend)
5019 "Set mark ARG words away from point.
5020 The place mark goes is the same place \\[forward-word] would
5021 move to with the same argument.
5022 Interactively, if this command is repeated
5023 or (in Transient Mark mode) if the mark is active,
5024 it marks the next ARG words after the ones already marked."
5025 (interactive "P\np")
5026 (cond ((and allow-extend
5027 (or (and (eq last-command this-command) (mark t))
5028 (region-active-p)))
5029 (setq arg (if arg (prefix-numeric-value arg)
5030 (if (< (mark) (point)) -1 1)))
5031 (set-mark
5032 (save-excursion
5033 (goto-char (mark))
5034 (forward-word arg)
5035 (point))))
5037 (push-mark
5038 (save-excursion
5039 (forward-word (prefix-numeric-value arg))
5040 (point))
5041 nil t))))
5043 (defun kill-word (arg)
5044 "Kill characters forward until encountering the end of a word.
5045 With argument ARG, do this that many times."
5046 (interactive "p")
5047 (kill-region (point) (progn (forward-word arg) (point))))
5049 (defun backward-kill-word (arg)
5050 "Kill characters backward until encountering the beginning of a word.
5051 With argument ARG, do this that many times."
5052 (interactive "p")
5053 (kill-word (- arg)))
5055 (defun current-word (&optional strict really-word)
5056 "Return the symbol or word that point is on (or a nearby one) as a string.
5057 The return value includes no text properties.
5058 If optional arg STRICT is non-nil, return nil unless point is within
5059 or adjacent to a symbol or word. In all cases the value can be nil
5060 if there is no word nearby.
5061 The function, belying its name, normally finds a symbol.
5062 If optional arg REALLY-WORD is non-nil, it finds just a word."
5063 (save-excursion
5064 (let* ((oldpoint (point)) (start (point)) (end (point))
5065 (syntaxes (if really-word "w" "w_"))
5066 (not-syntaxes (concat "^" syntaxes)))
5067 (skip-syntax-backward syntaxes) (setq start (point))
5068 (goto-char oldpoint)
5069 (skip-syntax-forward syntaxes) (setq end (point))
5070 (when (and (eq start oldpoint) (eq end oldpoint)
5071 ;; Point is neither within nor adjacent to a word.
5072 (not strict))
5073 ;; Look for preceding word in same line.
5074 (skip-syntax-backward not-syntaxes (line-beginning-position))
5075 (if (bolp)
5076 ;; No preceding word in same line.
5077 ;; Look for following word in same line.
5078 (progn
5079 (skip-syntax-forward not-syntaxes (line-end-position))
5080 (setq start (point))
5081 (skip-syntax-forward syntaxes)
5082 (setq end (point)))
5083 (setq end (point))
5084 (skip-syntax-backward syntaxes)
5085 (setq start (point))))
5086 ;; If we found something nonempty, return it as a string.
5087 (unless (= start end)
5088 (buffer-substring-no-properties start end)))))
5090 (defcustom fill-prefix nil
5091 "String for filling to insert at front of new line, or nil for none."
5092 :type '(choice (const :tag "None" nil)
5093 string)
5094 :group 'fill)
5095 (make-variable-buffer-local 'fill-prefix)
5096 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
5098 (defcustom auto-fill-inhibit-regexp nil
5099 "Regexp to match lines which should not be auto-filled."
5100 :type '(choice (const :tag "None" nil)
5101 regexp)
5102 :group 'fill)
5104 (defun do-auto-fill ()
5105 "The default value for `normal-auto-fill-function'.
5106 This is the default auto-fill function, some major modes use a different one.
5107 Returns t if it really did any work."
5108 (let (fc justify give-up
5109 (fill-prefix fill-prefix))
5110 (if (or (not (setq justify (current-justification)))
5111 (null (setq fc (current-fill-column)))
5112 (and (eq justify 'left)
5113 (<= (current-column) fc))
5114 (and auto-fill-inhibit-regexp
5115 (save-excursion (beginning-of-line)
5116 (looking-at auto-fill-inhibit-regexp))))
5117 nil ;; Auto-filling not required
5118 (if (memq justify '(full center right))
5119 (save-excursion (unjustify-current-line)))
5121 ;; Choose a fill-prefix automatically.
5122 (when (and adaptive-fill-mode
5123 (or (null fill-prefix) (string= fill-prefix "")))
5124 (let ((prefix
5125 (fill-context-prefix
5126 (save-excursion (backward-paragraph 1) (point))
5127 (save-excursion (forward-paragraph 1) (point)))))
5128 (and prefix (not (equal prefix ""))
5129 ;; Use auto-indentation rather than a guessed empty prefix.
5130 (not (and fill-indent-according-to-mode
5131 (string-match "\\`[ \t]*\\'" prefix)))
5132 (setq fill-prefix prefix))))
5134 (while (and (not give-up) (> (current-column) fc))
5135 ;; Determine where to split the line.
5136 (let* (after-prefix
5137 (fill-point
5138 (save-excursion
5139 (beginning-of-line)
5140 (setq after-prefix (point))
5141 (and fill-prefix
5142 (looking-at (regexp-quote fill-prefix))
5143 (setq after-prefix (match-end 0)))
5144 (move-to-column (1+ fc))
5145 (fill-move-to-break-point after-prefix)
5146 (point))))
5148 ;; See whether the place we found is any good.
5149 (if (save-excursion
5150 (goto-char fill-point)
5151 (or (bolp)
5152 ;; There is no use breaking at end of line.
5153 (save-excursion (skip-chars-forward " ") (eolp))
5154 ;; It is futile to split at the end of the prefix
5155 ;; since we would just insert the prefix again.
5156 (and after-prefix (<= (point) after-prefix))
5157 ;; Don't split right after a comment starter
5158 ;; since we would just make another comment starter.
5159 (and comment-start-skip
5160 (let ((limit (point)))
5161 (beginning-of-line)
5162 (and (re-search-forward comment-start-skip
5163 limit t)
5164 (eq (point) limit))))))
5165 ;; No good place to break => stop trying.
5166 (setq give-up t)
5167 ;; Ok, we have a useful place to break the line. Do it.
5168 (let ((prev-column (current-column)))
5169 ;; If point is at the fill-point, do not `save-excursion'.
5170 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5171 ;; point will end up before it rather than after it.
5172 (if (save-excursion
5173 (skip-chars-backward " \t")
5174 (= (point) fill-point))
5175 (default-indent-new-line t)
5176 (save-excursion
5177 (goto-char fill-point)
5178 (default-indent-new-line t)))
5179 ;; Now do justification, if required
5180 (if (not (eq justify 'left))
5181 (save-excursion
5182 (end-of-line 0)
5183 (justify-current-line justify nil t)))
5184 ;; If making the new line didn't reduce the hpos of
5185 ;; the end of the line, then give up now;
5186 ;; trying again will not help.
5187 (if (>= (current-column) prev-column)
5188 (setq give-up t))))))
5189 ;; Justify last line.
5190 (justify-current-line justify t t)
5191 t)))
5193 (defvar comment-line-break-function 'comment-indent-new-line
5194 "*Mode-specific function which line breaks and continues a comment.
5195 This function is called during auto-filling when a comment syntax
5196 is defined.
5197 The function should take a single optional argument, which is a flag
5198 indicating whether it should use soft newlines.")
5200 (defun default-indent-new-line (&optional soft)
5201 "Break line at point and indent.
5202 If a comment syntax is defined, call `comment-indent-new-line'.
5204 The inserted newline is marked hard if variable `use-hard-newlines' is true,
5205 unless optional argument SOFT is non-nil."
5206 (interactive)
5207 (if comment-start
5208 (funcall comment-line-break-function soft)
5209 ;; Insert the newline before removing empty space so that markers
5210 ;; get preserved better.
5211 (if soft (insert-and-inherit ?\n) (newline 1))
5212 (save-excursion (forward-char -1) (delete-horizontal-space))
5213 (delete-horizontal-space)
5215 (if (and fill-prefix (not adaptive-fill-mode))
5216 ;; Blindly trust a non-adaptive fill-prefix.
5217 (progn
5218 (indent-to-left-margin)
5219 (insert-before-markers-and-inherit fill-prefix))
5221 (cond
5222 ;; If there's an adaptive prefix, use it unless we're inside
5223 ;; a comment and the prefix is not a comment starter.
5224 (fill-prefix
5225 (indent-to-left-margin)
5226 (insert-and-inherit fill-prefix))
5227 ;; If we're not inside a comment, just try to indent.
5228 (t (indent-according-to-mode))))))
5230 (defvar normal-auto-fill-function 'do-auto-fill
5231 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
5232 Some major modes set this.")
5234 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
5235 ;; `functions' and `hooks' are usually unsafe to set, but setting
5236 ;; auto-fill-function to nil in a file-local setting is safe and
5237 ;; can be useful to prevent auto-filling.
5238 (put 'auto-fill-function 'safe-local-variable 'null)
5239 ;; FIXME: turn into a proper minor mode.
5240 ;; Add a global minor mode version of it.
5241 (define-minor-mode auto-fill-mode
5242 "Toggle Auto Fill mode.
5243 With ARG, turn Auto Fill mode on if and only if ARG is positive.
5244 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
5245 automatically breaks the line at a previous space.
5247 The value of `normal-auto-fill-function' specifies the function to use
5248 for `auto-fill-function' when turning Auto Fill mode on."
5249 :variable (eq auto-fill-function normal-auto-fill-function))
5251 ;; This holds a document string used to document auto-fill-mode.
5252 (defun auto-fill-function ()
5253 "Automatically break line at a previous space, in insertion of text."
5254 nil)
5256 (defun turn-on-auto-fill ()
5257 "Unconditionally turn on Auto Fill mode."
5258 (auto-fill-mode 1))
5260 (defun turn-off-auto-fill ()
5261 "Unconditionally turn off Auto Fill mode."
5262 (auto-fill-mode -1))
5264 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
5266 (defun set-fill-column (arg)
5267 "Set `fill-column' to specified argument.
5268 Use \\[universal-argument] followed by a number to specify a column.
5269 Just \\[universal-argument] as argument means to use the current column."
5270 (interactive
5271 (list (or current-prefix-arg
5272 ;; We used to use current-column silently, but C-x f is too easily
5273 ;; typed as a typo for C-x C-f, so we turned it into an error and
5274 ;; now an interactive prompt.
5275 (read-number "Set fill-column to: " (current-column)))))
5276 (if (consp arg)
5277 (setq arg (current-column)))
5278 (if (not (integerp arg))
5279 ;; Disallow missing argument; it's probably a typo for C-x C-f.
5280 (error "set-fill-column requires an explicit argument")
5281 (message "Fill column set to %d (was %d)" arg fill-column)
5282 (setq fill-column arg)))
5284 (defun set-selective-display (arg)
5285 "Set `selective-display' to ARG; clear it if no arg.
5286 When the value of `selective-display' is a number > 0,
5287 lines whose indentation is >= that value are not displayed.
5288 The variable `selective-display' has a separate value for each buffer."
5289 (interactive "P")
5290 (if (eq selective-display t)
5291 (error "selective-display already in use for marked lines"))
5292 (let ((current-vpos
5293 (save-restriction
5294 (narrow-to-region (point-min) (point))
5295 (goto-char (window-start))
5296 (vertical-motion (window-height)))))
5297 (setq selective-display
5298 (and arg (prefix-numeric-value arg)))
5299 (recenter current-vpos))
5300 (set-window-start (selected-window) (window-start (selected-window)))
5301 (princ "selective-display set to " t)
5302 (prin1 selective-display t)
5303 (princ "." t))
5305 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
5307 (defun toggle-truncate-lines (&optional arg)
5308 "Toggle whether to fold or truncate long lines for the current buffer.
5309 With prefix argument ARG, truncate long lines if ARG is positive,
5310 otherwise don't truncate them. Note that in side-by-side windows,
5311 this command has no effect if `truncate-partial-width-windows'
5312 is non-nil."
5313 (interactive "P")
5314 (setq truncate-lines
5315 (if (null arg)
5316 (not truncate-lines)
5317 (> (prefix-numeric-value arg) 0)))
5318 (force-mode-line-update)
5319 (unless truncate-lines
5320 (let ((buffer (current-buffer)))
5321 (walk-windows (lambda (window)
5322 (if (eq buffer (window-buffer window))
5323 (set-window-hscroll window 0)))
5324 nil t)))
5325 (message "Truncate long lines %s"
5326 (if truncate-lines "enabled" "disabled")))
5328 (defun toggle-word-wrap (&optional arg)
5329 "Toggle whether to use word-wrapping for continuation lines.
5330 With prefix argument ARG, wrap continuation lines at word boundaries
5331 if ARG is positive, otherwise wrap them at the right screen edge.
5332 This command toggles the value of `word-wrap'. It has no effect
5333 if long lines are truncated."
5334 (interactive "P")
5335 (setq word-wrap
5336 (if (null arg)
5337 (not word-wrap)
5338 (> (prefix-numeric-value arg) 0)))
5339 (force-mode-line-update)
5340 (message "Word wrapping %s"
5341 (if word-wrap "enabled" "disabled")))
5343 (defvar overwrite-mode-textual (purecopy " Ovwrt")
5344 "The string displayed in the mode line when in overwrite mode.")
5345 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
5346 "The string displayed in the mode line when in binary overwrite mode.")
5348 (define-minor-mode overwrite-mode
5349 "Toggle overwrite mode.
5350 With prefix argument ARG, turn overwrite mode on if ARG is positive,
5351 otherwise turn it off. In overwrite mode, printing characters typed
5352 in replace existing text on a one-for-one basis, rather than pushing
5353 it to the right. At the end of a line, such characters extend the line.
5354 Before a tab, such characters insert until the tab is filled in.
5355 \\[quoted-insert] still inserts characters in overwrite mode; this
5356 is supposed to make it easier to insert characters when necessary."
5357 :variable (eq overwrite-mode 'overwrite-mode-textual))
5359 (define-minor-mode binary-overwrite-mode
5360 "Toggle binary overwrite mode.
5361 With prefix argument ARG, turn binary overwrite mode on if ARG is
5362 positive, otherwise turn it off. In binary overwrite mode, printing
5363 characters typed in replace existing text. Newlines are not treated
5364 specially, so typing at the end of a line joins the line to the next,
5365 with the typed character between them. Typing before a tab character
5366 simply replaces the tab with the character typed. \\[quoted-insert]
5367 replaces the text at the cursor, just as ordinary typing characters do.
5369 Note that binary overwrite mode is not its own minor mode; it is a
5370 specialization of overwrite mode, entered by setting the
5371 `overwrite-mode' variable to `overwrite-mode-binary'."
5372 :variable (eq overwrite-mode 'overwrite-mode-binary))
5374 (define-minor-mode line-number-mode
5375 "Toggle Line Number mode.
5376 With ARG, turn Line Number mode on if ARG is positive, otherwise
5377 turn it off. When Line Number mode is enabled, the line number
5378 appears in the mode line.
5380 Line numbers do not appear for very large buffers and buffers
5381 with very long lines; see variables `line-number-display-limit'
5382 and `line-number-display-limit-width'."
5383 :init-value t :global t :group 'mode-line)
5385 (define-minor-mode column-number-mode
5386 "Toggle Column Number mode.
5387 With ARG, turn Column Number mode on if ARG is positive,
5388 otherwise turn it off. When Column Number mode is enabled, the
5389 column number appears in the mode line."
5390 :global t :group 'mode-line)
5392 (define-minor-mode size-indication-mode
5393 "Toggle Size Indication mode.
5394 With ARG, turn Size Indication mode on if ARG is positive,
5395 otherwise turn it off. When Size Indication mode is enabled, the
5396 size of the accessible part of the buffer appears in the mode line."
5397 :global t :group 'mode-line)
5399 (define-minor-mode auto-save-mode
5400 "Toggle auto-saving of contents of current buffer.
5401 With prefix argument ARG, turn auto-saving on if positive, else off."
5402 :variable ((and buffer-auto-save-file-name
5403 ;; If auto-save is off because buffer has shrunk,
5404 ;; then toggling should turn it on.
5405 (>= buffer-saved-size 0))
5406 . (lambda (val)
5407 (setq buffer-auto-save-file-name
5408 (cond
5409 ((null val) nil)
5410 ((and buffer-file-name auto-save-visited-file-name
5411 (not buffer-read-only))
5412 buffer-file-name)
5413 (t (make-auto-save-file-name))))))
5414 ;; If -1 was stored here, to temporarily turn off saving,
5415 ;; turn it back on.
5416 (and (< buffer-saved-size 0)
5417 (setq buffer-saved-size 0)))
5419 (defgroup paren-blinking nil
5420 "Blinking matching of parens and expressions."
5421 :prefix "blink-matching-"
5422 :group 'paren-matching)
5424 (defcustom blink-matching-paren t
5425 "Non-nil means show matching open-paren when close-paren is inserted."
5426 :type 'boolean
5427 :group 'paren-blinking)
5429 (defcustom blink-matching-paren-on-screen t
5430 "Non-nil means show matching open-paren when it is on screen.
5431 If nil, don't show it (but the open-paren can still be shown
5432 when it is off screen).
5434 This variable has no effect if `blink-matching-paren' is nil.
5435 \(In that case, the open-paren is never shown.)
5436 It is also ignored if `show-paren-mode' is enabled."
5437 :type 'boolean
5438 :group 'paren-blinking)
5440 (defcustom blink-matching-paren-distance (* 100 1024)
5441 "If non-nil, maximum distance to search backwards for matching open-paren.
5442 If nil, search stops at the beginning of the accessible portion of the buffer."
5443 :version "23.2" ; 25->100k
5444 :type '(choice (const nil) integer)
5445 :group 'paren-blinking)
5447 (defcustom blink-matching-delay 1
5448 "Time in seconds to delay after showing a matching paren."
5449 :type 'number
5450 :group 'paren-blinking)
5452 (defcustom blink-matching-paren-dont-ignore-comments nil
5453 "If nil, `blink-matching-paren' ignores comments.
5454 More precisely, when looking for the matching parenthesis,
5455 it skips the contents of comments that end before point."
5456 :type 'boolean
5457 :group 'paren-blinking)
5459 (defun blink-matching-check-mismatch (start end)
5460 "Return whether or not START...END are matching parens.
5461 END is the current point and START is the blink position.
5462 START might be nil if no matching starter was found.
5463 Returns non-nil if we find there is a mismatch."
5464 (let* ((end-syntax (syntax-after (1- end)))
5465 (matching-paren (and (consp end-syntax)
5466 (eq (syntax-class end-syntax) 5)
5467 (cdr end-syntax))))
5468 ;; For self-matched chars like " and $, we can't know when they're
5469 ;; mismatched or unmatched, so we can only do it for parens.
5470 (when matching-paren
5471 (not (and start
5473 (eq (char-after start) matching-paren)
5474 ;; The cdr might hold a new paren-class info rather than
5475 ;; a matching-char info, in which case the two CDRs
5476 ;; should match.
5477 (eq matching-paren (cdr-safe (syntax-after start)))))))))
5479 (defvar blink-matching-check-function #'blink-matching-check-mismatch
5480 "Function to check parentheses mismatches.
5481 The function takes two arguments (START and END) where START is the
5482 position just before the opening token and END is the position right after.
5483 START can be nil, if it was not found.
5484 The function should return non-nil if the two tokens do not match.")
5486 (defun blink-matching-open ()
5487 "Move cursor momentarily to the beginning of the sexp before point."
5488 (interactive)
5489 (when (and (not (bobp))
5490 blink-matching-paren)
5491 (let* ((oldpos (point))
5492 (message-log-max nil) ; Don't log messages about paren matching.
5493 (blinkpos
5494 (save-excursion
5495 (save-restriction
5496 (if blink-matching-paren-distance
5497 (narrow-to-region
5498 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5499 (- (point) blink-matching-paren-distance))
5500 oldpos))
5501 (let ((parse-sexp-ignore-comments
5502 (and parse-sexp-ignore-comments
5503 (not blink-matching-paren-dont-ignore-comments))))
5504 (condition-case ()
5505 (progn
5506 (forward-sexp -1)
5507 ;; backward-sexp skips backward over prefix chars,
5508 ;; so move back to the matching paren.
5509 (while (and (< (point) (1- oldpos))
5510 (let ((code (syntax-after (point))))
5511 (or (eq (syntax-class code) 6)
5512 (eq (logand 1048576 (car code))
5513 1048576))))
5514 (forward-char 1))
5515 (point))
5516 (error nil))))))
5517 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
5518 (cond
5519 (mismatch
5520 (if blinkpos
5521 (if (minibufferp)
5522 (minibuffer-message "Mismatched parentheses")
5523 (message "Mismatched parentheses"))
5524 (if (minibufferp)
5525 (minibuffer-message "Unmatched parenthesis")
5526 (message "Unmatched parenthesis"))))
5527 ((not blinkpos) nil)
5528 ((pos-visible-in-window-p blinkpos)
5529 ;; Matching open within window, temporarily move to blinkpos but only
5530 ;; if `blink-matching-paren-on-screen' is non-nil.
5531 (and blink-matching-paren-on-screen
5532 (not show-paren-mode)
5533 (save-excursion
5534 (goto-char blinkpos)
5535 (sit-for blink-matching-delay))))
5537 (save-excursion
5538 (goto-char blinkpos)
5539 (let ((open-paren-line-string
5540 ;; Show what precedes the open in its line, if anything.
5541 (cond
5542 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5543 (buffer-substring (line-beginning-position)
5544 (1+ blinkpos)))
5545 ;; Show what follows the open in its line, if anything.
5546 ((save-excursion
5547 (forward-char 1)
5548 (skip-chars-forward " \t")
5549 (not (eolp)))
5550 (buffer-substring blinkpos
5551 (line-end-position)))
5552 ;; Otherwise show the previous nonblank line,
5553 ;; if there is one.
5554 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5555 (concat
5556 (buffer-substring (progn
5557 (skip-chars-backward "\n \t")
5558 (line-beginning-position))
5559 (progn (end-of-line)
5560 (skip-chars-backward " \t")
5561 (point)))
5562 ;; Replace the newline and other whitespace with `...'.
5563 "..."
5564 (buffer-substring blinkpos (1+ blinkpos))))
5565 ;; There is nothing to show except the char itself.
5566 (t (buffer-substring blinkpos (1+ blinkpos))))))
5567 (message "Matches %s"
5568 (substring-no-properties open-paren-line-string)))))))))
5570 (defvar blink-paren-function 'blink-matching-open
5571 "Function called, if non-nil, whenever a close parenthesis is inserted.
5572 More precisely, a char with closeparen syntax is self-inserted.")
5574 (defun blink-paren-post-self-insert-function ()
5575 (when (and (eq (char-before) last-command-event) ; Sanity check.
5576 (memq (char-syntax last-command-event) '(?\) ?\$))
5577 blink-paren-function
5578 (not executing-kbd-macro)
5579 (not noninteractive)
5580 ;; Verify an even number of quoting characters precede the close.
5581 (= 1 (logand 1 (- (point)
5582 (save-excursion
5583 (forward-char -1)
5584 (skip-syntax-backward "/\\")
5585 (point))))))
5586 (funcall blink-paren-function)))
5588 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
5589 ;; Most likely, this hook is nil, so this arg doesn't matter,
5590 ;; but I use it as a reminder that this function usually
5591 ;; likes to be run after others since it does `sit-for'.
5592 'append)
5594 ;; This executes C-g typed while Emacs is waiting for a command.
5595 ;; Quitting out of a program does not go through here;
5596 ;; that happens in the QUIT macro at the C code level.
5597 (defun keyboard-quit ()
5598 "Signal a `quit' condition.
5599 During execution of Lisp code, this character causes a quit directly.
5600 At top-level, as an editor command, this simply beeps."
5601 (interactive)
5602 ;; Avoid adding the region to the window selection.
5603 (setq saved-region-selection nil)
5604 (let (select-active-regions)
5605 (deactivate-mark))
5606 (if (fboundp 'kmacro-keyboard-quit)
5607 (kmacro-keyboard-quit))
5608 (setq defining-kbd-macro nil)
5609 (signal 'quit nil))
5611 (defvar buffer-quit-function nil
5612 "Function to call to \"quit\" the current buffer, or nil if none.
5613 \\[keyboard-escape-quit] calls this function when its more local actions
5614 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5616 (defun keyboard-escape-quit ()
5617 "Exit the current \"mode\" (in a generalized sense of the word).
5618 This command can exit an interactive command such as `query-replace',
5619 can clear out a prefix argument or a region,
5620 can get out of the minibuffer or other recursive edit,
5621 cancel the use of the current buffer (for special-purpose buffers),
5622 or go back to just one window (by deleting all but the selected window)."
5623 (interactive)
5624 (cond ((eq last-command 'mode-exited) nil)
5625 ((region-active-p)
5626 (deactivate-mark))
5627 ((> (minibuffer-depth) 0)
5628 (abort-recursive-edit))
5629 (current-prefix-arg
5630 nil)
5631 ((> (recursion-depth) 0)
5632 (exit-recursive-edit))
5633 (buffer-quit-function
5634 (funcall buffer-quit-function))
5635 ((not (one-window-p t))
5636 (delete-other-windows))
5637 ((string-match "^ \\*" (buffer-name (current-buffer)))
5638 (bury-buffer))))
5640 (defun play-sound-file (file &optional volume device)
5641 "Play sound stored in FILE.
5642 VOLUME and DEVICE correspond to the keywords of the sound
5643 specification for `play-sound'."
5644 (interactive "fPlay sound file: ")
5645 (let ((sound (list :file file)))
5646 (if volume
5647 (plist-put sound :volume volume))
5648 (if device
5649 (plist-put sound :device device))
5650 (push 'sound sound)
5651 (play-sound sound)))
5654 (defcustom read-mail-command 'rmail
5655 "Your preference for a mail reading package.
5656 This is used by some keybindings which support reading mail.
5657 See also `mail-user-agent' concerning sending mail."
5658 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
5659 (function-item :tag "Gnus" :format "%t\n" gnus)
5660 (function-item :tag "Emacs interface to MH"
5661 :format "%t\n" mh-rmail)
5662 (function :tag "Other"))
5663 :version "21.1"
5664 :group 'mail)
5666 (defcustom mail-user-agent 'message-user-agent
5667 "Your preference for a mail composition package.
5668 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
5669 outgoing email message. This variable lets you specify which
5670 mail-sending package you prefer.
5672 Valid values include:
5674 `message-user-agent' -- use the Message package.
5675 See Info node `(message)'.
5676 `sendmail-user-agent' -- use the Mail package.
5677 See Info node `(emacs)Sending Mail'.
5678 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5679 See Info node `(mh-e)'.
5680 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5681 paraphernalia, particularly the Gcc: header for
5682 archiving.
5684 Additional valid symbols may be available; check with the author of
5685 your package for details. The function should return non-nil if it
5686 succeeds.
5688 See also `read-mail-command' concerning reading mail."
5689 :type '(radio (function-item :tag "Message package"
5690 :format "%t\n"
5691 message-user-agent)
5692 (function-item :tag "Mail package"
5693 :format "%t\n"
5694 sendmail-user-agent)
5695 (function-item :tag "Emacs interface to MH"
5696 :format "%t\n"
5697 mh-e-user-agent)
5698 (function-item :tag "Message with full Gnus features"
5699 :format "%t\n"
5700 gnus-user-agent)
5701 (function :tag "Other"))
5702 :version "23.2" ; sendmail->message
5703 :group 'mail)
5705 (defcustom compose-mail-user-agent-warnings t
5706 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
5707 If the value of `mail-user-agent' is the default, and the user
5708 appears to have customizations applying to the old default,
5709 `compose-mail' issues a warning."
5710 :type 'boolean
5711 :version "23.2"
5712 :group 'mail)
5714 (defun rfc822-goto-eoh ()
5715 "If the buffer starts with a mail header, move point to the header's end.
5716 Otherwise, moves to `point-min'.
5717 The end of the header is the start of the next line, if there is one,
5718 else the end of the last line. This function obeys RFC822."
5719 (goto-char (point-min))
5720 (when (re-search-forward
5721 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5722 (goto-char (match-beginning 0))))
5724 (defun compose-mail (&optional to subject other-headers continue
5725 switch-function yank-action send-actions
5726 return-action)
5727 "Start composing a mail message to send.
5728 This uses the user's chosen mail composition package
5729 as selected with the variable `mail-user-agent'.
5730 The optional arguments TO and SUBJECT specify recipients
5731 and the initial Subject field, respectively.
5733 OTHER-HEADERS is an alist specifying additional
5734 header fields. Elements look like (HEADER . VALUE) where both
5735 HEADER and VALUE are strings.
5737 CONTINUE, if non-nil, says to continue editing a message already
5738 being composed. Interactively, CONTINUE is the prefix argument.
5740 SWITCH-FUNCTION, if non-nil, is a function to use to
5741 switch to and display the buffer used for mail composition.
5743 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
5744 to insert the raw text of the message being replied to.
5745 It has the form (FUNCTION . ARGS). The user agent will apply
5746 FUNCTION to ARGS, to insert the raw text of the original message.
5747 \(The user agent will also run `mail-citation-hook', *after* the
5748 original text has been inserted in this way.)
5750 SEND-ACTIONS is a list of actions to call when the message is sent.
5751 Each action has the form (FUNCTION . ARGS).
5753 RETURN-ACTION, if non-nil, is an action for returning to the
5754 caller. It has the form (FUNCTION . ARGS). The function is
5755 called after the mail has been sent or put aside, and the mail
5756 buffer buried."
5757 (interactive
5758 (list nil nil nil current-prefix-arg))
5760 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
5761 ;; from sendmail-user-agent to message-user-agent. Some users may
5762 ;; encounter incompatibilities. This hack tries to detect problems
5763 ;; and warn about them.
5764 (and compose-mail-user-agent-warnings
5765 (eq mail-user-agent 'message-user-agent)
5766 (let (warn-vars)
5767 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
5768 mail-yank-hooks mail-archive-file-name
5769 mail-default-reply-to mail-mailing-lists
5770 mail-self-blind))
5771 (and (boundp var)
5772 (symbol-value var)
5773 (push var warn-vars)))
5774 (when warn-vars
5775 (display-warning 'mail
5776 (format "\
5777 The default mail mode is now Message mode.
5778 You have the following Mail mode variable%s customized:
5779 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
5780 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
5781 (if (> (length warn-vars) 1) "s" "")
5782 (mapconcat 'symbol-name
5783 warn-vars " "))))))
5785 (let ((function (get mail-user-agent 'composefunc)))
5786 (funcall function to subject other-headers continue switch-function
5787 yank-action send-actions return-action)))
5789 (defun compose-mail-other-window (&optional to subject other-headers continue
5790 yank-action send-actions
5791 return-action)
5792 "Like \\[compose-mail], but edit the outgoing message in another window."
5793 (interactive (list nil nil nil current-prefix-arg))
5794 (compose-mail to subject other-headers continue
5795 'pop-to-buffer-other-window yank-action send-actions
5796 return-action))
5798 (defun compose-mail-other-frame (&optional to subject other-headers continue
5799 yank-action send-actions
5800 return-action)
5801 "Like \\[compose-mail], but edit the outgoing message in another frame."
5802 (interactive (list nil nil nil current-prefix-arg))
5803 (compose-mail to subject other-headers continue
5804 'pop-to-buffer-other-frame yank-action send-actions
5805 return-action))
5807 (defvar set-variable-value-history nil
5808 "History of values entered with `set-variable'.
5810 Maximum length of the history list is determined by the value
5811 of `history-length', which see.")
5813 (defun set-variable (variable value &optional make-local)
5814 "Set VARIABLE to VALUE. VALUE is a Lisp object.
5815 VARIABLE should be a user option variable name, a Lisp variable
5816 meant to be customized by users. You should enter VALUE in Lisp syntax,
5817 so if you want VALUE to be a string, you must surround it with doublequotes.
5818 VALUE is used literally, not evaluated.
5820 If VARIABLE has a `variable-interactive' property, that is used as if
5821 it were the arg to `interactive' (which see) to interactively read VALUE.
5823 If VARIABLE has been defined with `defcustom', then the type information
5824 in the definition is used to check that VALUE is valid.
5826 With a prefix argument, set VARIABLE to VALUE buffer-locally."
5827 (interactive
5828 (let* ((default-var (variable-at-point))
5829 (var (if (user-variable-p default-var)
5830 (read-variable (format "Set variable (default %s): " default-var)
5831 default-var)
5832 (read-variable "Set variable: ")))
5833 (minibuffer-help-form '(describe-variable var))
5834 (prop (get var 'variable-interactive))
5835 (obsolete (car (get var 'byte-obsolete-variable)))
5836 (prompt (format "Set %s %s to value: " var
5837 (cond ((local-variable-p var)
5838 "(buffer-local)")
5839 ((or current-prefix-arg
5840 (local-variable-if-set-p var))
5841 "buffer-locally")
5842 (t "globally"))))
5843 (val (progn
5844 (when obsolete
5845 (message (concat "`%S' is obsolete; "
5846 (if (symbolp obsolete) "use `%S' instead" "%s"))
5847 var obsolete)
5848 (sit-for 3))
5849 (if prop
5850 ;; Use VAR's `variable-interactive' property
5851 ;; as an interactive spec for prompting.
5852 (call-interactively `(lambda (arg)
5853 (interactive ,prop)
5854 arg))
5855 (read
5856 (read-string prompt nil
5857 'set-variable-value-history
5858 (format "%S" (symbol-value var))))))))
5859 (list var val current-prefix-arg)))
5861 (and (custom-variable-p variable)
5862 (not (get variable 'custom-type))
5863 (custom-load-symbol variable))
5864 (let ((type (get variable 'custom-type)))
5865 (when type
5866 ;; Match with custom type.
5867 (require 'cus-edit)
5868 (setq type (widget-convert type))
5869 (unless (widget-apply type :match value)
5870 (error "Value `%S' does not match type %S of %S"
5871 value (car type) variable))))
5873 (if make-local
5874 (make-local-variable variable))
5876 (set variable value)
5878 ;; Force a thorough redisplay for the case that the variable
5879 ;; has an effect on the display, like `tab-width' has.
5880 (force-mode-line-update))
5882 ;; Define the major mode for lists of completions.
5884 (defvar completion-list-mode-map
5885 (let ((map (make-sparse-keymap)))
5886 (define-key map [mouse-2] 'mouse-choose-completion)
5887 (define-key map [follow-link] 'mouse-face)
5888 (define-key map [down-mouse-2] nil)
5889 (define-key map "\C-m" 'choose-completion)
5890 (define-key map "\e\e\e" 'delete-completion-window)
5891 (define-key map [left] 'previous-completion)
5892 (define-key map [right] 'next-completion)
5893 (define-key map "q" 'quit-window)
5894 (define-key map "z" 'kill-this-buffer)
5895 map)
5896 "Local map for completion list buffers.")
5898 ;; Completion mode is suitable only for specially formatted data.
5899 (put 'completion-list-mode 'mode-class 'special)
5901 (defvar completion-reference-buffer nil
5902 "Record the buffer that was current when the completion list was requested.
5903 This is a local variable in the completion list buffer.
5904 Initial value is nil to avoid some compiler warnings.")
5906 (defvar completion-no-auto-exit nil
5907 "Non-nil means `choose-completion-string' should never exit the minibuffer.
5908 This also applies to other functions such as `choose-completion'.")
5910 (defvar completion-base-position nil
5911 "Position of the base of the text corresponding to the shown completions.
5912 This variable is used in the *Completions* buffers.
5913 Its value is a list of the form (START END) where START is the place
5914 where the completion should be inserted and END (if non-nil) is the end
5915 of the text to replace. If END is nil, point is used instead.")
5917 (defvar completion-base-size nil
5918 "Number of chars before point not involved in completion.
5919 This is a local variable in the completion list buffer.
5920 It refers to the chars in the minibuffer if completing in the
5921 minibuffer, or in `completion-reference-buffer' otherwise.
5922 Only characters in the field at point are included.
5924 If nil, Emacs determines which part of the tail end of the
5925 buffer's text is involved in completion by comparing the text
5926 directly.")
5927 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
5929 (defun delete-completion-window ()
5930 "Delete the completion list window.
5931 Go to the window from which completion was requested."
5932 (interactive)
5933 (let ((buf completion-reference-buffer))
5934 (if (one-window-p t)
5935 (if (window-dedicated-p (selected-window))
5936 (delete-frame (selected-frame)))
5937 (delete-window (selected-window))
5938 (if (get-buffer-window buf)
5939 (select-window (get-buffer-window buf))))))
5941 (defun previous-completion (n)
5942 "Move to the previous item in the completion list."
5943 (interactive "p")
5944 (next-completion (- n)))
5946 (defun next-completion (n)
5947 "Move to the next item in the completion list.
5948 With prefix argument N, move N items (negative N means move backward)."
5949 (interactive "p")
5950 (let ((beg (point-min)) (end (point-max)))
5951 (while (and (> n 0) (not (eobp)))
5952 ;; If in a completion, move to the end of it.
5953 (when (get-text-property (point) 'mouse-face)
5954 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5955 ;; Move to start of next one.
5956 (unless (get-text-property (point) 'mouse-face)
5957 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5958 (setq n (1- n)))
5959 (while (and (< n 0) (not (bobp)))
5960 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
5961 ;; If in a completion, move to the start of it.
5962 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
5963 (goto-char (previous-single-property-change
5964 (point) 'mouse-face nil beg)))
5965 ;; Move to end of the previous completion.
5966 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
5967 (goto-char (previous-single-property-change
5968 (point) 'mouse-face nil beg)))
5969 ;; Move to the start of that one.
5970 (goto-char (previous-single-property-change
5971 (point) 'mouse-face nil beg))
5972 (setq n (1+ n))))))
5974 (defun choose-completion (&optional event)
5975 "Choose the completion at point."
5976 (interactive (list last-nonmenu-event))
5977 ;; In case this is run via the mouse, give temporary modes such as
5978 ;; isearch a chance to turn off.
5979 (run-hooks 'mouse-leave-buffer-hook)
5980 (let (buffer base-size base-position choice)
5981 (with-current-buffer (window-buffer (posn-window (event-start event)))
5982 (setq buffer completion-reference-buffer)
5983 (setq base-size completion-base-size)
5984 (setq base-position completion-base-position)
5985 (save-excursion
5986 (goto-char (posn-point (event-start event)))
5987 (let (beg end)
5988 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
5989 (setq end (point) beg (1+ (point))))
5990 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
5991 (setq end (1- (point)) beg (point)))
5992 (if (null beg)
5993 (error "No completion here"))
5994 (setq beg (previous-single-property-change beg 'mouse-face))
5995 (setq end (or (next-single-property-change end 'mouse-face)
5996 (point-max)))
5997 (setq choice (buffer-substring-no-properties beg end)))))
5999 (let ((owindow (selected-window)))
6000 (select-window (posn-window (event-start event)))
6001 (if (and (one-window-p t 'selected-frame)
6002 (window-dedicated-p (selected-window)))
6003 ;; This is a special buffer's frame
6004 (iconify-frame (selected-frame))
6005 (or (window-dedicated-p (selected-window))
6006 (bury-buffer)))
6007 (select-window
6008 (or (and (buffer-live-p buffer)
6009 (get-buffer-window buffer 0))
6010 owindow)))
6012 (choose-completion-string
6013 choice buffer
6014 (or base-position
6015 (when base-size
6016 ;; Someone's using old completion code that doesn't know
6017 ;; about base-position yet.
6018 (list (+ base-size (with-current-buffer buffer (field-beginning)))))
6019 ;; If all else fails, just guess.
6020 (with-current-buffer buffer
6021 (list (choose-completion-guess-base-position choice)))))))
6023 ;; Delete the longest partial match for STRING
6024 ;; that can be found before POINT.
6025 (defun choose-completion-guess-base-position (string)
6026 (save-excursion
6027 (let ((opoint (point))
6028 len)
6029 ;; Try moving back by the length of the string.
6030 (goto-char (max (- (point) (length string))
6031 (minibuffer-prompt-end)))
6032 ;; See how far back we were actually able to move. That is the
6033 ;; upper bound on how much we can match and delete.
6034 (setq len (- opoint (point)))
6035 (if completion-ignore-case
6036 (setq string (downcase string)))
6037 (while (and (> len 0)
6038 (let ((tail (buffer-substring (point) opoint)))
6039 (if completion-ignore-case
6040 (setq tail (downcase tail)))
6041 (not (string= tail (substring string 0 len)))))
6042 (setq len (1- len))
6043 (forward-char 1))
6044 (point))))
6046 (defun choose-completion-delete-max-match (string)
6047 (delete-region (choose-completion-guess-base-position string) (point)))
6048 (make-obsolete 'choose-completion-delete-max-match
6049 'choose-completion-guess-base-position "23.2")
6051 (defvar choose-completion-string-functions nil
6052 "Functions that may override the normal insertion of a completion choice.
6053 These functions are called in order with four arguments:
6054 CHOICE - the string to insert in the buffer,
6055 BUFFER - the buffer in which the choice should be inserted,
6056 MINI-P - non-nil if BUFFER is a minibuffer, and
6057 BASE-SIZE - the number of characters in BUFFER before
6058 the string being completed.
6060 If a function in the list returns non-nil, that function is supposed
6061 to have inserted the CHOICE in the BUFFER, and possibly exited
6062 the minibuffer; no further functions will be called.
6064 If all functions in the list return nil, that means to use
6065 the default method of inserting the completion in BUFFER.")
6067 (defun choose-completion-string (choice &optional buffer base-position)
6068 "Switch to BUFFER and insert the completion choice CHOICE.
6069 BASE-POSITION, says where to insert the completion."
6071 ;; If BUFFER is the minibuffer, exit the minibuffer
6072 ;; unless it is reading a file name and CHOICE is a directory,
6073 ;; or completion-no-auto-exit is non-nil.
6075 ;; Some older code may call us passing `base-size' instead of
6076 ;; `base-position'. It's difficult to make any use of `base-size',
6077 ;; so we just ignore it.
6078 (unless (consp base-position)
6079 (message "Obsolete `base-size' passed to choose-completion-string")
6080 (setq base-position nil))
6082 (let* ((buffer (or buffer completion-reference-buffer))
6083 (mini-p (minibufferp buffer)))
6084 ;; If BUFFER is a minibuffer, barf unless it's the currently
6085 ;; active minibuffer.
6086 (if (and mini-p
6087 (or (not (active-minibuffer-window))
6088 (not (equal buffer
6089 (window-buffer (active-minibuffer-window))))))
6090 (error "Minibuffer is not active for completion")
6091 ;; Set buffer so buffer-local choose-completion-string-functions works.
6092 (set-buffer buffer)
6093 (unless (run-hook-with-args-until-success
6094 'choose-completion-string-functions
6095 ;; The fourth arg used to be `mini-p' but was useless
6096 ;; (since minibufferp can be used on the `buffer' arg)
6097 ;; and indeed unused. The last used to be `base-size', so we
6098 ;; keep it to try and avoid breaking old code.
6099 choice buffer base-position nil)
6100 ;; Insert the completion into the buffer where it was requested.
6101 (delete-region (or (car base-position) (point))
6102 (or (cadr base-position) (point)))
6103 (insert choice)
6104 (remove-text-properties (- (point) (length choice)) (point)
6105 '(mouse-face nil))
6106 ;; Update point in the window that BUFFER is showing in.
6107 (let ((window (get-buffer-window buffer t)))
6108 (set-window-point window (point)))
6109 ;; If completing for the minibuffer, exit it with this choice.
6110 (and (not completion-no-auto-exit)
6111 (minibufferp buffer)
6112 minibuffer-completion-table
6113 ;; If this is reading a file name, and the file name chosen
6114 ;; is a directory, don't exit the minibuffer.
6115 (let* ((result (buffer-substring (field-beginning) (point)))
6116 (bounds
6117 (completion-boundaries result minibuffer-completion-table
6118 minibuffer-completion-predicate
6119 "")))
6120 (if (eq (car bounds) (length result))
6121 ;; The completion chosen leads to a new set of completions
6122 ;; (e.g. it's a directory): don't exit the minibuffer yet.
6123 (let ((mini (active-minibuffer-window)))
6124 (select-window mini)
6125 (when minibuffer-auto-raise
6126 (raise-frame (window-frame mini))))
6127 (exit-minibuffer))))))))
6129 (define-derived-mode completion-list-mode nil "Completion List"
6130 "Major mode for buffers showing lists of possible completions.
6131 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
6132 to select the completion near point.
6133 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
6134 with the mouse.
6136 \\{completion-list-mode-map}"
6137 (set (make-local-variable 'completion-base-size) nil))
6139 (defun completion-list-mode-finish ()
6140 "Finish setup of the completions buffer.
6141 Called from `temp-buffer-show-hook'."
6142 (when (eq major-mode 'completion-list-mode)
6143 (toggle-read-only 1)))
6145 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
6148 ;; Variables and faces used in `completion-setup-function'.
6150 (defcustom completion-show-help t
6151 "Non-nil means show help message in *Completions* buffer."
6152 :type 'boolean
6153 :version "22.1"
6154 :group 'completion)
6156 ;; This function goes in completion-setup-hook, so that it is called
6157 ;; after the text of the completion list buffer is written.
6158 (defun completion-setup-function ()
6159 (let* ((mainbuf (current-buffer))
6160 (base-dir
6161 ;; When reading a file name in the minibuffer,
6162 ;; try and find the right default-directory to set in the
6163 ;; completion list buffer.
6164 ;; FIXME: Why do we do that, actually? --Stef
6165 (if minibuffer-completing-file-name
6166 (file-name-as-directory
6167 (expand-file-name
6168 (substring (minibuffer-completion-contents)
6169 0 (or completion-base-size 0)))))))
6170 (with-current-buffer standard-output
6171 (let ((base-size completion-base-size) ;Read before killing localvars.
6172 (base-position completion-base-position))
6173 (completion-list-mode)
6174 (set (make-local-variable 'completion-base-size) base-size)
6175 (set (make-local-variable 'completion-base-position) base-position))
6176 (set (make-local-variable 'completion-reference-buffer) mainbuf)
6177 (if base-dir (setq default-directory base-dir))
6178 ;; Maybe insert help string.
6179 (when completion-show-help
6180 (goto-char (point-min))
6181 (if (display-mouse-p)
6182 (insert (substitute-command-keys
6183 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
6184 (insert (substitute-command-keys
6185 "In this buffer, type \\[choose-completion] to \
6186 select the completion near point.\n\n"))))))
6188 (add-hook 'completion-setup-hook 'completion-setup-function)
6190 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
6191 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
6193 (defun switch-to-completions ()
6194 "Select the completion list window."
6195 (interactive)
6196 (let ((window (or (get-buffer-window "*Completions*" 0)
6197 ;; Make sure we have a completions window.
6198 (progn (minibuffer-completion-help)
6199 (get-buffer-window "*Completions*" 0)))))
6200 (when window
6201 (select-window window)
6202 ;; In the new buffer, go to the first completion.
6203 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
6204 (when (bobp)
6205 (next-completion 1)))))
6207 ;;; Support keyboard commands to turn on various modifiers.
6209 ;; These functions -- which are not commands -- each add one modifier
6210 ;; to the following event.
6212 (defun event-apply-alt-modifier (_ignore-prompt)
6213 "\\<function-key-map>Add the Alt modifier to the following event.
6214 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
6215 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
6216 (defun event-apply-super-modifier (_ignore-prompt)
6217 "\\<function-key-map>Add the Super modifier to the following event.
6218 For example, type \\[event-apply-super-modifier] & to enter Super-&."
6219 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
6220 (defun event-apply-hyper-modifier (_ignore-prompt)
6221 "\\<function-key-map>Add the Hyper modifier to the following event.
6222 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
6223 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
6224 (defun event-apply-shift-modifier (_ignore-prompt)
6225 "\\<function-key-map>Add the Shift modifier to the following event.
6226 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
6227 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
6228 (defun event-apply-control-modifier (_ignore-prompt)
6229 "\\<function-key-map>Add the Ctrl modifier to the following event.
6230 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
6231 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
6232 (defun event-apply-meta-modifier (_ignore-prompt)
6233 "\\<function-key-map>Add the Meta modifier to the following event.
6234 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
6235 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
6237 (defun event-apply-modifier (event symbol lshiftby prefix)
6238 "Apply a modifier flag to event EVENT.
6239 SYMBOL is the name of this modifier, as a symbol.
6240 LSHIFTBY is the numeric value of this modifier, in keyboard events.
6241 PREFIX is the string that represents this modifier in an event type symbol."
6242 (if (numberp event)
6243 (cond ((eq symbol 'control)
6244 (if (and (<= (downcase event) ?z)
6245 (>= (downcase event) ?a))
6246 (- (downcase event) ?a -1)
6247 (if (and (<= (downcase event) ?Z)
6248 (>= (downcase event) ?A))
6249 (- (downcase event) ?A -1)
6250 (logior (lsh 1 lshiftby) event))))
6251 ((eq symbol 'shift)
6252 (if (and (<= (downcase event) ?z)
6253 (>= (downcase event) ?a))
6254 (upcase event)
6255 (logior (lsh 1 lshiftby) event)))
6257 (logior (lsh 1 lshiftby) event)))
6258 (if (memq symbol (event-modifiers event))
6259 event
6260 (let ((event-type (if (symbolp event) event (car event))))
6261 (setq event-type (intern (concat prefix (symbol-name event-type))))
6262 (if (symbolp event)
6263 event-type
6264 (cons event-type (cdr event)))))))
6266 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
6267 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
6268 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
6269 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
6270 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
6271 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
6273 ;;;; Keypad support.
6275 ;; Make the keypad keys act like ordinary typing keys. If people add
6276 ;; bindings for the function key symbols, then those bindings will
6277 ;; override these, so this shouldn't interfere with any existing
6278 ;; bindings.
6280 ;; Also tell read-char how to handle these keys.
6281 (mapc
6282 (lambda (keypad-normal)
6283 (let ((keypad (nth 0 keypad-normal))
6284 (normal (nth 1 keypad-normal)))
6285 (put keypad 'ascii-character normal)
6286 (define-key function-key-map (vector keypad) (vector normal))))
6287 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
6288 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
6289 (kp-space ?\s)
6290 (kp-tab ?\t)
6291 (kp-enter ?\r)
6292 (kp-multiply ?*)
6293 (kp-add ?+)
6294 (kp-separator ?,)
6295 (kp-subtract ?-)
6296 (kp-decimal ?.)
6297 (kp-divide ?/)
6298 (kp-equal ?=)
6299 ;; Do the same for various keys that are represented as symbols under
6300 ;; GUIs but naturally correspond to characters.
6301 (backspace 127)
6302 (delete 127)
6303 (tab ?\t)
6304 (linefeed ?\n)
6305 (clear ?\C-l)
6306 (return ?\C-m)
6307 (escape ?\e)
6310 ;;;;
6311 ;;;; forking a twin copy of a buffer.
6312 ;;;;
6314 (defvar clone-buffer-hook nil
6315 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
6317 (defvar clone-indirect-buffer-hook nil
6318 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
6320 (defun clone-process (process &optional newname)
6321 "Create a twin copy of PROCESS.
6322 If NEWNAME is nil, it defaults to PROCESS' name;
6323 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
6324 If PROCESS is associated with a buffer, the new process will be associated
6325 with the current buffer instead.
6326 Returns nil if PROCESS has already terminated."
6327 (setq newname (or newname (process-name process)))
6328 (if (string-match "<[0-9]+>\\'" newname)
6329 (setq newname (substring newname 0 (match-beginning 0))))
6330 (when (memq (process-status process) '(run stop open))
6331 (let* ((process-connection-type (process-tty-name process))
6332 (new-process
6333 (if (memq (process-status process) '(open))
6334 (let ((args (process-contact process t)))
6335 (setq args (plist-put args :name newname))
6336 (setq args (plist-put args :buffer
6337 (if (process-buffer process)
6338 (current-buffer))))
6339 (apply 'make-network-process args))
6340 (apply 'start-process newname
6341 (if (process-buffer process) (current-buffer))
6342 (process-command process)))))
6343 (set-process-query-on-exit-flag
6344 new-process (process-query-on-exit-flag process))
6345 (set-process-inherit-coding-system-flag
6346 new-process (process-inherit-coding-system-flag process))
6347 (set-process-filter new-process (process-filter process))
6348 (set-process-sentinel new-process (process-sentinel process))
6349 (set-process-plist new-process (copy-sequence (process-plist process)))
6350 new-process)))
6352 ;; things to maybe add (currently partly covered by `funcall mode'):
6353 ;; - syntax-table
6354 ;; - overlays
6355 (defun clone-buffer (&optional newname display-flag)
6356 "Create and return a twin copy of the current buffer.
6357 Unlike an indirect buffer, the new buffer can be edited
6358 independently of the old one (if it is not read-only).
6359 NEWNAME is the name of the new buffer. It may be modified by
6360 adding or incrementing <N> at the end as necessary to create a
6361 unique buffer name. If nil, it defaults to the name of the
6362 current buffer, with the proper suffix. If DISPLAY-FLAG is
6363 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
6364 clone a file-visiting buffer, or a buffer whose major mode symbol
6365 has a non-nil `no-clone' property, results in an error.
6367 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
6368 current buffer with appropriate suffix. However, if a prefix
6369 argument is given, then the command prompts for NEWNAME in the
6370 minibuffer.
6372 This runs the normal hook `clone-buffer-hook' in the new buffer
6373 after it has been set up properly in other respects."
6374 (interactive
6375 (progn
6376 (if buffer-file-name
6377 (error "Cannot clone a file-visiting buffer"))
6378 (if (get major-mode 'no-clone)
6379 (error "Cannot clone a buffer in %s mode" mode-name))
6380 (list (if current-prefix-arg
6381 (read-buffer "Name of new cloned buffer: " (current-buffer)))
6382 t)))
6383 (if buffer-file-name
6384 (error "Cannot clone a file-visiting buffer"))
6385 (if (get major-mode 'no-clone)
6386 (error "Cannot clone a buffer in %s mode" mode-name))
6387 (setq newname (or newname (buffer-name)))
6388 (if (string-match "<[0-9]+>\\'" newname)
6389 (setq newname (substring newname 0 (match-beginning 0))))
6390 (let ((buf (current-buffer))
6391 (ptmin (point-min))
6392 (ptmax (point-max))
6393 (pt (point))
6394 (mk (if mark-active (mark t)))
6395 (modified (buffer-modified-p))
6396 (mode major-mode)
6397 (lvars (buffer-local-variables))
6398 (process (get-buffer-process (current-buffer)))
6399 (new (generate-new-buffer (or newname (buffer-name)))))
6400 (save-restriction
6401 (widen)
6402 (with-current-buffer new
6403 (insert-buffer-substring buf)))
6404 (with-current-buffer new
6405 (narrow-to-region ptmin ptmax)
6406 (goto-char pt)
6407 (if mk (set-mark mk))
6408 (set-buffer-modified-p modified)
6410 ;; Clone the old buffer's process, if any.
6411 (when process (clone-process process))
6413 ;; Now set up the major mode.
6414 (funcall mode)
6416 ;; Set up other local variables.
6417 (mapc (lambda (v)
6418 (condition-case () ;in case var is read-only
6419 (if (symbolp v)
6420 (makunbound v)
6421 (set (make-local-variable (car v)) (cdr v)))
6422 (error nil)))
6423 lvars)
6425 ;; Run any hooks (typically set up by the major mode
6426 ;; for cloning to work properly).
6427 (run-hooks 'clone-buffer-hook))
6428 (if display-flag
6429 ;; Presumably the current buffer is shown in the selected frame, so
6430 ;; we want to display the clone elsewhere.
6431 (pop-to-buffer-other-window new))
6432 new))
6435 (defun clone-indirect-buffer (newname display-flag &optional norecord)
6436 "Create an indirect buffer that is a twin copy of the current buffer.
6438 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
6439 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6440 or if not called with a prefix arg, NEWNAME defaults to the current
6441 buffer's name. The name is modified by adding a `<N>' suffix to it
6442 or by incrementing the N in an existing suffix. Trying to clone a
6443 buffer whose major mode symbol has a non-nil `no-clone-indirect'
6444 property results in an error.
6446 DISPLAY-FLAG non-nil means show the new buffer with
6447 `pop-to-buffer'. This is always done when called interactively.
6448 Non-interactively, if DISPLAY-FLAG equals 'other-window, display
6449 the buffer in another window.
6451 Optional third arg NORECORD non-nil means do not put this buffer
6452 at the front of the list of recently selected ones."
6453 (interactive
6454 (progn
6455 (if (get major-mode 'no-clone-indirect)
6456 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6457 (list (if current-prefix-arg
6458 (read-buffer "Name of indirect buffer: " (current-buffer)))
6459 t)))
6460 (if (get major-mode 'no-clone-indirect)
6461 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6462 (setq newname (or newname (buffer-name)))
6463 (if (string-match "<[0-9]+>\\'" newname)
6464 (setq newname (substring newname 0 (match-beginning 0))))
6465 (let* ((name (generate-new-buffer-name newname))
6466 (buffer (make-indirect-buffer (current-buffer) name t)))
6467 (with-current-buffer buffer
6468 (run-hooks 'clone-indirect-buffer-hook))
6469 (when display-flag
6470 (pop-to-buffer buffer (eq display-flag 'other-window) norecord))
6471 buffer))
6473 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6474 "Like `clone-indirect-buffer' but display in another window."
6475 (interactive
6476 (progn
6477 (if (get major-mode 'no-clone-indirect)
6478 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6479 (list (if current-prefix-arg
6480 (read-buffer "Name of indirect buffer: " (current-buffer)))
6481 'other-window)))
6482 (clone-indirect-buffer newname display-flag norecord))
6485 ;;; Handling of Backspace and Delete keys.
6487 (defcustom normal-erase-is-backspace 'maybe
6488 "Set the default behavior of the Delete and Backspace keys.
6490 If set to t, Delete key deletes forward and Backspace key deletes
6491 backward.
6493 If set to nil, both Delete and Backspace keys delete backward.
6495 If set to 'maybe (which is the default), Emacs automatically
6496 selects a behavior. On window systems, the behavior depends on
6497 the keyboard used. If the keyboard has both a Backspace key and
6498 a Delete key, and both are mapped to their usual meanings, the
6499 option's default value is set to t, so that Backspace can be used
6500 to delete backward, and Delete can be used to delete forward.
6502 If not running under a window system, customizing this option
6503 accomplishes a similar effect by mapping C-h, which is usually
6504 generated by the Backspace key, to DEL, and by mapping DEL to C-d
6505 via `keyboard-translate'. The former functionality of C-h is
6506 available on the F1 key. You should probably not use this
6507 setting if you don't have both Backspace, Delete and F1 keys.
6509 Setting this variable with setq doesn't take effect. Programmatically,
6510 call `normal-erase-is-backspace-mode' (which see) instead."
6511 :type '(choice (const :tag "Off" nil)
6512 (const :tag "Maybe" maybe)
6513 (other :tag "On" t))
6514 :group 'editing-basics
6515 :version "21.1"
6516 :set (lambda (symbol value)
6517 ;; The fboundp is because of a problem with :set when
6518 ;; dumping Emacs. It doesn't really matter.
6519 (if (fboundp 'normal-erase-is-backspace-mode)
6520 (normal-erase-is-backspace-mode (or value 0))
6521 (set-default symbol value))))
6523 (defun normal-erase-is-backspace-setup-frame (&optional frame)
6524 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6525 (unless frame (setq frame (selected-frame)))
6526 (with-selected-frame frame
6527 (unless (terminal-parameter nil 'normal-erase-is-backspace)
6528 (normal-erase-is-backspace-mode
6529 (if (if (eq normal-erase-is-backspace 'maybe)
6530 (and (not noninteractive)
6531 (or (memq system-type '(ms-dos windows-nt))
6532 (memq window-system '(ns))
6533 (and (memq window-system '(x))
6534 (fboundp 'x-backspace-delete-keys-p)
6535 (x-backspace-delete-keys-p))
6536 ;; If the terminal Emacs is running on has erase char
6537 ;; set to ^H, use the Backspace key for deleting
6538 ;; backward, and the Delete key for deleting forward.
6539 (and (null window-system)
6540 (eq tty-erase-char ?\^H))))
6541 normal-erase-is-backspace)
6542 1 0)))))
6544 (define-minor-mode normal-erase-is-backspace-mode
6545 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6547 With numeric ARG, turn the mode on if and only if ARG is positive.
6549 On window systems, when this mode is on, Delete is mapped to C-d
6550 and Backspace is mapped to DEL; when this mode is off, both
6551 Delete and Backspace are mapped to DEL. (The remapping goes via
6552 `local-function-key-map', so binding Delete or Backspace in the
6553 global or local keymap will override that.)
6555 In addition, on window systems, the bindings of C-Delete, M-Delete,
6556 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6557 the global keymap in accordance with the functionality of Delete and
6558 Backspace. For example, if Delete is remapped to C-d, which deletes
6559 forward, C-Delete is bound to `kill-word', but if Delete is remapped
6560 to DEL, which deletes backward, C-Delete is bound to
6561 `backward-kill-word'.
6563 If not running on a window system, a similar effect is accomplished by
6564 remapping C-h (normally produced by the Backspace key) and DEL via
6565 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6566 to C-d; if it's off, the keys are not remapped.
6568 When not running on a window system, and this mode is turned on, the
6569 former functionality of C-h is available on the F1 key. You should
6570 probably not turn on this mode on a text-only terminal if you don't
6571 have both Backspace, Delete and F1 keys.
6573 See also `normal-erase-is-backspace'."
6574 :variable (eq (terminal-parameter
6575 nil 'normal-erase-is-backspace) 1)
6576 (let ((enabled (eq 1 (terminal-parameter
6577 nil 'normal-erase-is-backspace))))
6579 (cond ((or (memq window-system '(x w32 ns pc))
6580 (memq system-type '(ms-dos windows-nt)))
6581 (let ((bindings
6582 `(([M-delete] [M-backspace])
6583 ([C-M-delete] [C-M-backspace])
6584 ([?\e C-delete] [?\e C-backspace]))))
6586 (if enabled
6587 (progn
6588 (define-key local-function-key-map [delete] [deletechar])
6589 (define-key local-function-key-map [kp-delete] [?\C-d])
6590 (define-key local-function-key-map [backspace] [?\C-?])
6591 (dolist (b bindings)
6592 ;; Not sure if input-decode-map is really right, but
6593 ;; keyboard-translate-table (used below) only works
6594 ;; for integer events, and key-translation-table is
6595 ;; global (like the global-map, used earlier).
6596 (define-key input-decode-map (car b) nil)
6597 (define-key input-decode-map (cadr b) nil)))
6598 (define-key local-function-key-map [delete] [?\C-?])
6599 (define-key local-function-key-map [kp-delete] [?\C-?])
6600 (define-key local-function-key-map [backspace] [?\C-?])
6601 (dolist (b bindings)
6602 (define-key input-decode-map (car b) (cadr b))
6603 (define-key input-decode-map (cadr b) (car b))))))
6605 (if enabled
6606 (progn
6607 (keyboard-translate ?\C-h ?\C-?)
6608 (keyboard-translate ?\C-? ?\C-d))
6609 (keyboard-translate ?\C-h ?\C-h)
6610 (keyboard-translate ?\C-? ?\C-?))))
6612 (if (called-interactively-p 'interactive)
6613 (message "Delete key deletes %s"
6614 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
6615 "forward" "backward")))))
6617 (defvar vis-mode-saved-buffer-invisibility-spec nil
6618 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
6620 (define-minor-mode visible-mode
6621 "Toggle Visible mode.
6622 With argument ARG turn Visible mode on if ARG is positive, otherwise
6623 turn it off.
6625 Enabling Visible mode makes all invisible text temporarily visible.
6626 Disabling Visible mode turns off that effect. Visible mode works by
6627 saving the value of `buffer-invisibility-spec' and setting it to nil."
6628 :lighter " Vis"
6629 :group 'editing-basics
6630 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6631 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6632 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
6633 (when visible-mode
6634 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6635 buffer-invisibility-spec)
6636 (setq buffer-invisibility-spec nil)))
6638 ;; Minibuffer prompt stuff.
6640 ;;(defun minibuffer-prompt-modification (start end)
6641 ;; (error "You cannot modify the prompt"))
6644 ;;(defun minibuffer-prompt-insertion (start end)
6645 ;; (let ((inhibit-modification-hooks t))
6646 ;; (delete-region start end)
6647 ;; ;; Discard undo information for the text insertion itself
6648 ;; ;; and for the text deletion.above.
6649 ;; (when (consp buffer-undo-list)
6650 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
6651 ;; (message "You cannot modify the prompt")))
6654 ;;(setq minibuffer-prompt-properties
6655 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
6656 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
6659 ;;;; Problematic external packages.
6661 ;; rms says this should be done by specifying symbols that define
6662 ;; versions together with bad values. This is therefore not as
6663 ;; flexible as it could be. See the thread:
6664 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6665 (defconst bad-packages-alist
6666 ;; Not sure exactly which semantic versions have problems.
6667 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
6668 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
6669 "The version of `semantic' loaded does not work in Emacs 22.
6670 It can cause constant high CPU load.
6671 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
6672 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6673 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6674 ;; provided the `CUA-mode' feature. Since this is no longer true,
6675 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6676 (CUA-mode t nil
6677 "CUA-mode is now part of the standard GNU Emacs distribution,
6678 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6680 You have loaded an older version of CUA-mode which does not work
6681 correctly with this version of Emacs. You should remove the old
6682 version and use the one distributed with Emacs."))
6683 "Alist of packages known to cause problems in this version of Emacs.
6684 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6685 PACKAGE is either a regular expression to match file names, or a
6686 symbol (a feature name); see the documentation of
6687 `after-load-alist', to which this variable adds functions.
6688 SYMBOL is either the name of a string variable, or `t'. Upon
6689 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6690 warning using STRING as the message.")
6692 (defun bad-package-check (package)
6693 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6694 (condition-case nil
6695 (let* ((list (assoc package bad-packages-alist))
6696 (symbol (nth 1 list)))
6697 (and list
6698 (boundp symbol)
6699 (or (eq symbol t)
6700 (and (stringp (setq symbol (eval symbol)))
6701 (string-match-p (nth 2 list) symbol)))
6702 (display-warning package (nth 3 list) :warning)))
6703 (error nil)))
6705 (mapc (lambda (elem)
6706 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6707 bad-packages-alist)
6710 (provide 'simple)
6712 ;;; simple.el ends here