Merge from emacs-23.
[emacs.git] / lisp / simple.el
blob612f942e6d1a56a79e9296ea0baee2c201d6a230
1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998,
4 ;; 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
5 ;; 2010, 2011 Free Software Foundation, Inc.
7 ;; Maintainer: FSF
8 ;; Keywords: internal
9 ;; Package: emacs
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; A grab-bag of basic Emacs commands not specifically related to some
29 ;; major mode or to file-handling.
31 ;;; Code:
33 ;; This is for lexical-let in apply-partially.
34 (eval-when-compile (require 'cl))
36 (declare-function widget-convert "wid-edit" (type &rest args))
37 (declare-function shell-mode "shell" ())
39 (defvar compilation-current-error)
41 (defcustom idle-update-delay 0.5
42 "Idle time delay before updating various things on the screen.
43 Various Emacs features that update auxiliary information when point moves
44 wait this many seconds after Emacs becomes idle before doing an update."
45 :type 'number
46 :group 'display
47 :version "22.1")
49 (defgroup killing nil
50 "Killing and yanking commands."
51 :group 'editing)
53 (defgroup paren-matching nil
54 "Highlight (un)matching of parens and expressions."
55 :group 'matching)
57 (defun get-next-valid-buffer (list &optional buffer visible-ok frame)
58 "Search LIST for a valid buffer to display in FRAME.
59 Return nil when all buffers in LIST are undesirable for display,
60 otherwise return the first suitable buffer in LIST.
62 Buffers not visible in windows are preferred to visible buffers,
63 unless VISIBLE-OK is non-nil.
64 If the optional argument FRAME is nil, it defaults to the selected frame.
65 If BUFFER is non-nil, ignore occurrences of that buffer in LIST."
66 ;; This logic is more or less copied from other-buffer.
67 (setq frame (or frame (selected-frame)))
68 (let ((pred (frame-parameter frame 'buffer-predicate))
69 found buf)
70 (while (and (not found) list)
71 (setq buf (car list))
72 (if (and (not (eq buffer buf))
73 (buffer-live-p buf)
74 (or (null pred) (funcall pred buf))
75 (not (eq (aref (buffer-name buf) 0) ?\s))
76 (or visible-ok (null (get-buffer-window buf 'visible))))
77 (setq found buf)
78 (setq list (cdr list))))
79 (car list)))
81 (defun last-buffer (&optional buffer visible-ok frame)
82 "Return the last buffer in FRAME's buffer list.
83 If BUFFER is the last buffer, return the preceding buffer instead.
84 Buffers not visible in windows are preferred to visible buffers,
85 unless optional argument VISIBLE-OK is non-nil.
86 Optional third argument FRAME nil or omitted means use the
87 selected frame's buffer list.
88 If no such buffer exists, return the buffer `*scratch*', creating
89 it if necessary."
90 (setq frame (or frame (selected-frame)))
91 (or (get-next-valid-buffer (nreverse (buffer-list frame))
92 buffer visible-ok frame)
93 (get-buffer "*scratch*")
94 (let ((scratch (get-buffer-create "*scratch*")))
95 (set-buffer-major-mode scratch)
96 scratch)))
98 (defun next-buffer ()
99 "Switch to the next buffer in cyclic order."
100 (interactive)
101 (let ((buffer (current-buffer)))
102 (switch-to-buffer (other-buffer buffer t))
103 (bury-buffer buffer)))
105 (defun previous-buffer ()
106 "Switch to the previous buffer in cyclic order."
107 (interactive)
108 (switch-to-buffer (last-buffer (current-buffer) t)))
111 ;;; next-error support framework
113 (defgroup next-error nil
114 "`next-error' support framework."
115 :group 'compilation
116 :version "22.1")
118 (defface next-error
119 '((t (:inherit region)))
120 "Face used to highlight next error locus."
121 :group 'next-error
122 :version "22.1")
124 (defcustom next-error-highlight 0.5
125 "Highlighting of locations in selected source buffers.
126 If a number, highlight the locus in `next-error' face for the given time
127 in seconds, or until the next command is executed.
128 If t, highlight the locus until the next command is executed, or until
129 some other locus replaces it.
130 If nil, don't highlight the locus in the source buffer.
131 If `fringe-arrow', indicate the locus by the fringe arrow."
132 :type '(choice (number :tag "Highlight for specified time")
133 (const :tag "Semipermanent highlighting" t)
134 (const :tag "No highlighting" nil)
135 (const :tag "Fringe arrow" fringe-arrow))
136 :group 'next-error
137 :version "22.1")
139 (defcustom next-error-highlight-no-select 0.5
140 "Highlighting of locations in `next-error-no-select'.
141 If number, highlight the locus in `next-error' face for given time in seconds.
142 If t, highlight the locus indefinitely until some other locus replaces it.
143 If nil, don't highlight the locus in the source buffer.
144 If `fringe-arrow', indicate the locus by the fringe arrow."
145 :type '(choice (number :tag "Highlight for specified time")
146 (const :tag "Semipermanent highlighting" t)
147 (const :tag "No highlighting" nil)
148 (const :tag "Fringe arrow" fringe-arrow))
149 :group 'next-error
150 :version "22.1")
152 (defcustom next-error-recenter nil
153 "Display the line in the visited source file recentered as specified.
154 If non-nil, the value is passed directly to `recenter'."
155 :type '(choice (integer :tag "Line to recenter to")
156 (const :tag "Center of window" (4))
157 (const :tag "No recentering" nil))
158 :group 'next-error
159 :version "23.1")
161 (defcustom next-error-hook nil
162 "List of hook functions run by `next-error' after visiting source file."
163 :type 'hook
164 :group 'next-error)
166 (defvar next-error-highlight-timer nil)
168 (defvar next-error-overlay-arrow-position nil)
169 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
170 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
172 (defvar next-error-last-buffer nil
173 "The most recent `next-error' buffer.
174 A buffer becomes most recent when its compilation, grep, or
175 similar mode is started, or when it is used with \\[next-error]
176 or \\[compile-goto-error].")
178 (defvar next-error-function nil
179 "Function to use to find the next error in the current buffer.
180 The function is called with 2 parameters:
181 ARG is an integer specifying by how many errors to move.
182 RESET is a boolean which, if non-nil, says to go back to the beginning
183 of the errors before moving.
184 Major modes providing compile-like functionality should set this variable
185 to indicate to `next-error' that this is a candidate buffer and how
186 to navigate in it.")
187 (make-variable-buffer-local 'next-error-function)
189 (defvar next-error-move-function nil
190 "Function to use to move to an error locus.
191 It takes two arguments, a buffer position in the error buffer
192 and a buffer position in the error locus buffer.
193 The buffer for the error locus should already be current.
194 nil means use goto-char using the second argument position.")
195 (make-variable-buffer-local 'next-error-move-function)
197 (defsubst next-error-buffer-p (buffer
198 &optional avoid-current
199 extra-test-inclusive
200 extra-test-exclusive)
201 "Test if BUFFER is a `next-error' capable buffer.
203 If AVOID-CURRENT is non-nil, treat the current buffer
204 as an absolute last resort only.
206 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
207 that normally would not qualify. If it returns t, the buffer
208 in question is treated as usable.
210 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
211 that would normally be considered usable. If it returns nil,
212 that buffer is rejected."
213 (and (buffer-name buffer) ;First make sure it's live.
214 (not (and avoid-current (eq buffer (current-buffer))))
215 (with-current-buffer buffer
216 (if next-error-function ; This is the normal test.
217 ;; Optionally reject some buffers.
218 (if extra-test-exclusive
219 (funcall extra-test-exclusive)
221 ;; Optionally accept some other buffers.
222 (and extra-test-inclusive
223 (funcall extra-test-inclusive))))))
225 (defun next-error-find-buffer (&optional avoid-current
226 extra-test-inclusive
227 extra-test-exclusive)
228 "Return a `next-error' capable buffer.
230 If AVOID-CURRENT is non-nil, treat the current buffer
231 as an absolute last resort only.
233 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
234 that normally would not qualify. If it returns t, the buffer
235 in question is treated as usable.
237 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
238 that would normally be considered usable. If it returns nil,
239 that buffer is rejected."
241 ;; 1. If one window on the selected frame displays such buffer, return it.
242 (let ((window-buffers
243 (delete-dups
244 (delq nil (mapcar (lambda (w)
245 (if (next-error-buffer-p
246 (window-buffer w)
247 avoid-current
248 extra-test-inclusive extra-test-exclusive)
249 (window-buffer w)))
250 (window-list))))))
251 (if (eq (length window-buffers) 1)
252 (car window-buffers)))
253 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
254 (if (and next-error-last-buffer
255 (next-error-buffer-p next-error-last-buffer avoid-current
256 extra-test-inclusive extra-test-exclusive))
257 next-error-last-buffer)
258 ;; 3. If the current buffer is acceptable, choose it.
259 (if (next-error-buffer-p (current-buffer) avoid-current
260 extra-test-inclusive extra-test-exclusive)
261 (current-buffer))
262 ;; 4. Look for any acceptable buffer.
263 (let ((buffers (buffer-list)))
264 (while (and buffers
265 (not (next-error-buffer-p
266 (car buffers) avoid-current
267 extra-test-inclusive extra-test-exclusive)))
268 (setq buffers (cdr buffers)))
269 (car buffers))
270 ;; 5. Use the current buffer as a last resort if it qualifies,
271 ;; even despite AVOID-CURRENT.
272 (and avoid-current
273 (next-error-buffer-p (current-buffer) nil
274 extra-test-inclusive extra-test-exclusive)
275 (progn
276 (message "This is the only buffer with error message locations")
277 (current-buffer)))
278 ;; 6. Give up.
279 (error "No buffers contain error message locations")))
281 (defun next-error (&optional arg reset)
282 "Visit next `next-error' message and corresponding source code.
284 If all the error messages parsed so far have been processed already,
285 the message buffer is checked for new ones.
287 A prefix ARG specifies how many error messages to move;
288 negative means move back to previous error messages.
289 Just \\[universal-argument] as a prefix means reparse the error message buffer
290 and start at the first error.
292 The RESET argument specifies that we should restart from the beginning.
294 \\[next-error] normally uses the most recently started
295 compilation, grep, or occur buffer. It can also operate on any
296 buffer with output from the \\[compile], \\[grep] commands, or,
297 more generally, on any buffer in Compilation mode or with
298 Compilation Minor mode enabled, or any buffer in which
299 `next-error-function' is bound to an appropriate function.
300 To specify use of a particular buffer for error messages, type
301 \\[next-error] in that buffer when it is the only one displayed
302 in the current frame.
304 Once \\[next-error] has chosen the buffer for error messages, it
305 runs `next-error-hook' with `run-hooks', and stays with that buffer
306 until you use it in some other buffer which uses Compilation mode
307 or Compilation Minor mode.
309 See variables `compilation-parse-errors-function' and
310 \`compilation-error-regexp-alist' for customization ideas."
311 (interactive "P")
312 (if (consp arg) (setq reset t arg nil))
313 (when (setq next-error-last-buffer (next-error-find-buffer))
314 ;; we know here that next-error-function is a valid symbol we can funcall
315 (with-current-buffer next-error-last-buffer
316 (funcall next-error-function (prefix-numeric-value arg) reset)
317 (when next-error-recenter
318 (recenter next-error-recenter))
319 (run-hooks 'next-error-hook))))
321 (defun next-error-internal ()
322 "Visit the source code corresponding to the `next-error' message at point."
323 (setq next-error-last-buffer (current-buffer))
324 ;; we know here that next-error-function is a valid symbol we can funcall
325 (with-current-buffer next-error-last-buffer
326 (funcall next-error-function 0 nil)
327 (when next-error-recenter
328 (recenter next-error-recenter))
329 (run-hooks 'next-error-hook)))
331 (defalias 'goto-next-locus 'next-error)
332 (defalias 'next-match 'next-error)
334 (defun previous-error (&optional n)
335 "Visit previous `next-error' message and corresponding source code.
337 Prefix arg N says how many error messages to move backwards (or
338 forwards, if negative).
340 This operates on the output from the \\[compile] and \\[grep] commands."
341 (interactive "p")
342 (next-error (- (or n 1))))
344 (defun first-error (&optional n)
345 "Restart at the first error.
346 Visit corresponding source code.
347 With prefix arg N, visit the source code of the Nth error.
348 This operates on the output from the \\[compile] command, for instance."
349 (interactive "p")
350 (next-error n t))
352 (defun next-error-no-select (&optional n)
353 "Move point to the next error in the `next-error' buffer and highlight match.
354 Prefix arg N says how many error messages to move forwards (or
355 backwards, if negative).
356 Finds and highlights the source line like \\[next-error], but does not
357 select the source buffer."
358 (interactive "p")
359 (let ((next-error-highlight next-error-highlight-no-select))
360 (next-error n))
361 (pop-to-buffer next-error-last-buffer))
363 (defun previous-error-no-select (&optional n)
364 "Move point to the previous error in the `next-error' buffer and highlight match.
365 Prefix arg N says how many error messages to move backwards (or
366 forwards, if negative).
367 Finds and highlights the source line like \\[previous-error], but does not
368 select the source buffer."
369 (interactive "p")
370 (next-error-no-select (- (or n 1))))
372 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
373 (defvar next-error-follow-last-line nil)
375 (define-minor-mode next-error-follow-minor-mode
376 "Minor mode for compilation, occur and diff modes.
377 When turned on, cursor motion in the compilation, grep, occur or diff
378 buffer causes automatic display of the corresponding source code
379 location."
380 :group 'next-error :init-value nil :lighter " Fol"
381 (if (not next-error-follow-minor-mode)
382 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
383 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
384 (make-local-variable 'next-error-follow-last-line)))
386 ;; Used as a `post-command-hook' by `next-error-follow-mode'
387 ;; for the *Compilation* *grep* and *Occur* buffers.
388 (defun next-error-follow-mode-post-command-hook ()
389 (unless (equal next-error-follow-last-line (line-number-at-pos))
390 (setq next-error-follow-last-line (line-number-at-pos))
391 (condition-case nil
392 (let ((compilation-context-lines nil))
393 (setq compilation-current-error (point))
394 (next-error-no-select 0))
395 (error t))))
400 (defun fundamental-mode ()
401 "Major mode not specialized for anything in particular.
402 Other major modes are defined by comparison with this one."
403 (interactive)
404 (kill-all-local-variables)
405 (run-mode-hooks 'fundamental-mode-hook))
407 ;; Special major modes to view specially formatted data rather than files.
409 (defvar special-mode-map
410 (let ((map (make-sparse-keymap)))
411 (suppress-keymap map)
412 (define-key map "q" 'quit-window)
413 (define-key map " " 'scroll-up)
414 (define-key map "\C-?" 'scroll-down)
415 (define-key map "?" 'describe-mode)
416 (define-key map ">" 'end-of-buffer)
417 (define-key map "<" 'beginning-of-buffer)
418 (define-key map "g" 'revert-buffer)
419 map))
421 (put 'special-mode 'mode-class 'special)
422 (define-derived-mode special-mode nil "Special"
423 "Parent major mode from which special major modes should inherit."
424 (setq buffer-read-only t))
426 ;; Major mode meant to be the parent of programming modes.
428 (defvar prog-mode-map
429 (let ((map (make-sparse-keymap)))
430 (define-key map [?\C-\M-q] 'prog-indent-sexp)
431 map)
432 "Keymap used for programming modes.")
434 (defun prog-indent-sexp ()
435 "Indent the expression after point."
436 (interactive)
437 (let ((start (point))
438 (end (save-excursion (forward-sexp 1) (point))))
439 (indent-region start end nil)))
441 (define-derived-mode prog-mode fundamental-mode "Prog"
442 "Major mode for editing programming language source code."
443 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
444 (set (make-local-variable 'parse-sexp-ignore-comments) t)
445 ;; Any programming language is always written left to right.
446 (setq bidi-paragraph-direction 'left-to-right))
448 ;; Making and deleting lines.
450 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
451 "Propertized string representing a hard newline character.")
453 (defun newline (&optional arg)
454 "Insert a newline, and move to left margin of the new line if it's blank.
455 If `use-hard-newlines' is non-nil, the newline is marked with the
456 text-property `hard'.
457 With ARG, insert that many newlines.
458 Call `auto-fill-function' if the current column number is greater
459 than the value of `fill-column' and ARG is nil."
460 (interactive "*P")
461 (barf-if-buffer-read-only)
462 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
463 ;; Set last-command-event to tell self-insert what to insert.
464 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
465 (beforepos (point))
466 (last-command-event ?\n)
467 ;; Don't auto-fill if we have a numeric argument.
468 (auto-fill-function (if arg nil auto-fill-function))
469 (postproc
470 ;; Do the rest in post-self-insert-hook, because we want to do it
471 ;; *before* other functions on that hook.
472 (lambda ()
473 ;; Mark the newline(s) `hard'.
474 (if use-hard-newlines
475 (set-hard-newline-properties
476 (- (point) (prefix-numeric-value arg)) (point)))
477 ;; If the newline leaves the previous line blank, and we
478 ;; have a left margin, delete that from the blank line.
479 (save-excursion
480 (goto-char beforepos)
481 (beginning-of-line)
482 (and (looking-at "[ \t]$")
483 (> (current-left-margin) 0)
484 (delete-region (point)
485 (line-end-position))))
486 ;; Indent the line after the newline, except in one case:
487 ;; when we added the newline at the beginning of a line which
488 ;; starts a page.
489 (or was-page-start
490 (move-to-left-margin nil t)))))
491 (unwind-protect
492 (progn
493 (add-hook 'post-self-insert-hook postproc)
494 (self-insert-command (prefix-numeric-value arg)))
495 ;; We first used let-binding to protect the hook, but that was naive
496 ;; since add-hook affects the symbol-default value of the variable,
497 ;; whereas the let-binding might only protect the buffer-local value.
498 (remove-hook 'post-self-insert-hook postproc)))
499 nil)
501 (defun set-hard-newline-properties (from to)
502 (let ((sticky (get-text-property from 'rear-nonsticky)))
503 (put-text-property from to 'hard 't)
504 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
505 (if (and (listp sticky) (not (memq 'hard sticky)))
506 (put-text-property from (point) 'rear-nonsticky
507 (cons 'hard sticky)))))
509 (defun open-line (n)
510 "Insert a newline and leave point before it.
511 If there is a fill prefix and/or a `left-margin', insert them
512 on the new line if the line would have been blank.
513 With arg N, insert N newlines."
514 (interactive "*p")
515 (let* ((do-fill-prefix (and fill-prefix (bolp)))
516 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
517 (loc (point-marker))
518 ;; Don't expand an abbrev before point.
519 (abbrev-mode nil))
520 (newline n)
521 (goto-char loc)
522 (while (> n 0)
523 (cond ((bolp)
524 (if do-left-margin (indent-to (current-left-margin)))
525 (if do-fill-prefix (insert-and-inherit fill-prefix))))
526 (forward-line 1)
527 (setq n (1- n)))
528 (goto-char loc)
529 (end-of-line)))
531 (defun split-line (&optional arg)
532 "Split current line, moving portion beyond point vertically down.
533 If the current line starts with `fill-prefix', insert it on the new
534 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
536 When called from Lisp code, ARG may be a prefix string to copy."
537 (interactive "*P")
538 (skip-chars-forward " \t")
539 (let* ((col (current-column))
540 (pos (point))
541 ;; What prefix should we check for (nil means don't).
542 (prefix (cond ((stringp arg) arg)
543 (arg nil)
544 (t fill-prefix)))
545 ;; Does this line start with it?
546 (have-prfx (and prefix
547 (save-excursion
548 (beginning-of-line)
549 (looking-at (regexp-quote prefix))))))
550 (newline 1)
551 (if have-prfx (insert-and-inherit prefix))
552 (indent-to col 0)
553 (goto-char pos)))
555 (defun delete-indentation (&optional arg)
556 "Join this line to previous and fix up whitespace at join.
557 If there is a fill prefix, delete it from the beginning of this line.
558 With argument, join this line to following line."
559 (interactive "*P")
560 (beginning-of-line)
561 (if arg (forward-line 1))
562 (if (eq (preceding-char) ?\n)
563 (progn
564 (delete-region (point) (1- (point)))
565 ;; If the second line started with the fill prefix,
566 ;; delete the prefix.
567 (if (and fill-prefix
568 (<= (+ (point) (length fill-prefix)) (point-max))
569 (string= fill-prefix
570 (buffer-substring (point)
571 (+ (point) (length fill-prefix)))))
572 (delete-region (point) (+ (point) (length fill-prefix))))
573 (fixup-whitespace))))
575 (defalias 'join-line #'delete-indentation) ; easier to find
577 (defun delete-blank-lines ()
578 "On blank line, delete all surrounding blank lines, leaving just one.
579 On isolated blank line, delete that one.
580 On nonblank line, delete any immediately following blank lines."
581 (interactive "*")
582 (let (thisblank singleblank)
583 (save-excursion
584 (beginning-of-line)
585 (setq thisblank (looking-at "[ \t]*$"))
586 ;; Set singleblank if there is just one blank line here.
587 (setq singleblank
588 (and thisblank
589 (not (looking-at "[ \t]*\n[ \t]*$"))
590 (or (bobp)
591 (progn (forward-line -1)
592 (not (looking-at "[ \t]*$")))))))
593 ;; Delete preceding blank lines, and this one too if it's the only one.
594 (if thisblank
595 (progn
596 (beginning-of-line)
597 (if singleblank (forward-line 1))
598 (delete-region (point)
599 (if (re-search-backward "[^ \t\n]" nil t)
600 (progn (forward-line 1) (point))
601 (point-min)))))
602 ;; Delete following blank lines, unless the current line is blank
603 ;; and there are no following blank lines.
604 (if (not (and thisblank singleblank))
605 (save-excursion
606 (end-of-line)
607 (forward-line 1)
608 (delete-region (point)
609 (if (re-search-forward "[^ \t\n]" nil t)
610 (progn (beginning-of-line) (point))
611 (point-max)))))
612 ;; Handle the special case where point is followed by newline and eob.
613 ;; Delete the line, leaving point at eob.
614 (if (looking-at "^[ \t]*\n\\'")
615 (delete-region (point) (point-max)))))
617 (defun delete-trailing-whitespace ()
618 "Delete all the trailing whitespace across the current buffer.
619 All whitespace after the last non-whitespace character in a line is deleted.
620 This respects narrowing, created by \\[narrow-to-region] and friends.
621 A formfeed is not considered whitespace by this function."
622 (interactive "*")
623 (save-match-data
624 (save-excursion
625 (goto-char (point-min))
626 (while (re-search-forward "\\s-$" nil t)
627 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
628 ;; Don't delete formfeeds, even if they are considered whitespace.
629 (save-match-data
630 (if (looking-at ".*\f")
631 (goto-char (match-end 0))))
632 (delete-region (point) (match-end 0))))))
634 (defun newline-and-indent ()
635 "Insert a newline, then indent according to major mode.
636 Indentation is done using the value of `indent-line-function'.
637 In programming language modes, this is the same as TAB.
638 In some text modes, where TAB inserts a tab, this command indents to the
639 column specified by the function `current-left-margin'."
640 (interactive "*")
641 (delete-horizontal-space t)
642 (newline)
643 (indent-according-to-mode))
645 (defun reindent-then-newline-and-indent ()
646 "Reindent current line, insert newline, then indent the new line.
647 Indentation of both lines is done according to the current major mode,
648 which means calling the current value of `indent-line-function'.
649 In programming language modes, this is the same as TAB.
650 In some text modes, where TAB inserts a tab, this indents to the
651 column specified by the function `current-left-margin'."
652 (interactive "*")
653 (let ((pos (point)))
654 ;; Be careful to insert the newline before indenting the line.
655 ;; Otherwise, the indentation might be wrong.
656 (newline)
657 (save-excursion
658 (goto-char pos)
659 ;; We are at EOL before the call to indent-according-to-mode, and
660 ;; after it we usually are as well, but not always. We tried to
661 ;; address it with `save-excursion' but that uses a normal marker
662 ;; whereas we need `move after insertion', so we do the save/restore
663 ;; by hand.
664 (setq pos (copy-marker pos t))
665 (indent-according-to-mode)
666 (goto-char pos)
667 ;; Remove the trailing white-space after indentation because
668 ;; indentation may introduce the whitespace.
669 (delete-horizontal-space t))
670 (indent-according-to-mode)))
672 (defun quoted-insert (arg)
673 "Read next input character and insert it.
674 This is useful for inserting control characters.
675 With argument, insert ARG copies of the character.
677 If the first character you type after this command is an octal digit,
678 you should type a sequence of octal digits which specify a character code.
679 Any nondigit terminates the sequence. If the terminator is a RET,
680 it is discarded; any other terminator is used itself as input.
681 The variable `read-quoted-char-radix' specifies the radix for this feature;
682 set it to 10 or 16 to use decimal or hex instead of octal.
684 In overwrite mode, this function inserts the character anyway, and
685 does not handle octal digits specially. This means that if you use
686 overwrite as your normal editing mode, you can use this function to
687 insert characters when necessary.
689 In binary overwrite mode, this function does overwrite, and octal
690 digits are interpreted as a character code. This is intended to be
691 useful for editing binary files."
692 (interactive "*p")
693 (let* ((char
694 ;; Avoid "obsolete" warnings for translation-table-for-input.
695 (with-no-warnings
696 (let (translation-table-for-input input-method-function)
697 (if (or (not overwrite-mode)
698 (eq overwrite-mode 'overwrite-mode-binary))
699 (read-quoted-char)
700 (read-char))))))
701 ;; This used to assume character codes 0240 - 0377 stand for
702 ;; characters in some single-byte character set, and converted them
703 ;; to Emacs characters. But in 23.1 this feature is deprecated
704 ;; in favor of inserting the corresponding Unicode characters.
705 ;; (if (and enable-multibyte-characters
706 ;; (>= char ?\240)
707 ;; (<= char ?\377))
708 ;; (setq char (unibyte-char-to-multibyte char)))
709 (if (> arg 0)
710 (if (eq overwrite-mode 'overwrite-mode-binary)
711 (delete-char arg)))
712 (while (> arg 0)
713 (insert-and-inherit char)
714 (setq arg (1- arg)))))
716 (defun forward-to-indentation (&optional arg)
717 "Move forward ARG lines and position at first nonblank character."
718 (interactive "^p")
719 (forward-line (or arg 1))
720 (skip-chars-forward " \t"))
722 (defun backward-to-indentation (&optional arg)
723 "Move backward ARG lines and position at first nonblank character."
724 (interactive "^p")
725 (forward-line (- (or arg 1)))
726 (skip-chars-forward " \t"))
728 (defun back-to-indentation ()
729 "Move point to the first non-whitespace character on this line."
730 (interactive "^")
731 (beginning-of-line 1)
732 (skip-syntax-forward " " (line-end-position))
733 ;; Move back over chars that have whitespace syntax but have the p flag.
734 (backward-prefix-chars))
736 (defun fixup-whitespace ()
737 "Fixup white space between objects around point.
738 Leave one space or none, according to the context."
739 (interactive "*")
740 (save-excursion
741 (delete-horizontal-space)
742 (if (or (looking-at "^\\|\\s)")
743 (save-excursion (forward-char -1)
744 (looking-at "$\\|\\s(\\|\\s'")))
746 (insert ?\s))))
748 (defun delete-horizontal-space (&optional backward-only)
749 "Delete all spaces and tabs around point.
750 If BACKWARD-ONLY is non-nil, only delete them before point."
751 (interactive "*P")
752 (let ((orig-pos (point)))
753 (delete-region
754 (if backward-only
755 orig-pos
756 (progn
757 (skip-chars-forward " \t")
758 (constrain-to-field nil orig-pos t)))
759 (progn
760 (skip-chars-backward " \t")
761 (constrain-to-field nil orig-pos)))))
763 (defun just-one-space (&optional n)
764 "Delete all spaces and tabs around point, leaving one space (or N spaces).
765 If N is negative, delete newlines as well."
766 (interactive "*p")
767 (unless n (setq n 1))
768 (let ((orig-pos (point))
769 (skip-characters (if (< n 0) " \t\n\r" " \t"))
770 (n (abs n)))
771 (skip-chars-backward skip-characters)
772 (constrain-to-field nil orig-pos)
773 (dotimes (i (or n 1))
774 (if (= (following-char) ?\s)
775 (forward-char 1)
776 (insert ?\s)))
777 (delete-region
778 (point)
779 (progn
780 (skip-chars-forward skip-characters)
781 (constrain-to-field nil orig-pos t)))))
783 (defun beginning-of-buffer (&optional arg)
784 "Move point to the beginning of the buffer.
785 With numeric arg N, put point N/10 of the way from the beginning.
786 If the buffer is narrowed, this command uses the beginning of the
787 accessible part of the buffer.
789 If Transient Mark mode is disabled, leave mark at previous
790 position, unless a \\[universal-argument] prefix is supplied.
792 Don't use this command in Lisp programs!
793 \(goto-char (point-min)) is faster."
794 (interactive "^P")
795 (or (consp arg)
796 (region-active-p)
797 (push-mark))
798 (let ((size (- (point-max) (point-min))))
799 (goto-char (if (and arg (not (consp arg)))
800 (+ (point-min)
801 (if (> size 10000)
802 ;; Avoid overflow for large buffer sizes!
803 (* (prefix-numeric-value arg)
804 (/ size 10))
805 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
806 (point-min))))
807 (if (and arg (not (consp arg))) (forward-line 1)))
809 (defun end-of-buffer (&optional arg)
810 "Move point to the end of the buffer.
811 With numeric arg N, put point N/10 of the way from the end.
812 If the buffer is narrowed, this command uses the end of the
813 accessible part of the buffer.
815 If Transient Mark mode is disabled, leave mark at previous
816 position, unless a \\[universal-argument] prefix is supplied.
818 Don't use this command in Lisp programs!
819 \(goto-char (point-max)) is faster."
820 (interactive "^P")
821 (or (consp arg) (region-active-p) (push-mark))
822 (let ((size (- (point-max) (point-min))))
823 (goto-char (if (and arg (not (consp arg)))
824 (- (point-max)
825 (if (> size 10000)
826 ;; Avoid overflow for large buffer sizes!
827 (* (prefix-numeric-value arg)
828 (/ size 10))
829 (/ (* size (prefix-numeric-value arg)) 10)))
830 (point-max))))
831 ;; If we went to a place in the middle of the buffer,
832 ;; adjust it to the beginning of a line.
833 (cond ((and arg (not (consp arg))) (forward-line 1))
834 ((> (point) (window-end nil t))
835 ;; If the end of the buffer is not already on the screen,
836 ;; then scroll specially to put it near, but not at, the bottom.
837 (overlay-recenter (point))
838 (recenter -3))))
840 (defcustom delete-active-region t
841 "Whether single-char deletion commands delete an active region.
842 This has an effect only if Transient Mark mode is enabled, and
843 affects `delete-forward-char' and `delete-backward-char', though
844 not `delete-char'.
846 If the value is the symbol `kill', the active region is killed
847 instead of deleted."
848 :type '(choice (const :tag "Delete active region" t)
849 (const :tag "Kill active region" kill)
850 (const :tag "Do ordinary deletion" nil))
851 :group 'editing
852 :version "24.1")
854 (defun delete-backward-char (n &optional killflag)
855 "Delete the previous N characters (following if N is negative).
856 If Transient Mark mode is enabled, the mark is active, and N is 1,
857 delete the text in the region and deactivate the mark instead.
858 To disable this, set `delete-active-region' to nil.
860 Optional second arg KILLFLAG, if non-nil, means to kill (save in
861 kill ring) instead of delete. Interactively, N is the prefix
862 arg, and KILLFLAG is set if N is explicitly specified.
864 In Overwrite mode, single character backward deletion may replace
865 tabs with spaces so as to back over columns, unless point is at
866 the end of the line."
867 (interactive "p\nP")
868 (unless (integerp n)
869 (signal 'wrong-type-argument (list 'integerp n)))
870 (cond ((and (use-region-p)
871 delete-active-region
872 (= n 1))
873 ;; If a region is active, kill or delete it.
874 (if (eq delete-active-region 'kill)
875 (kill-region (region-beginning) (region-end))
876 (delete-region (region-beginning) (region-end))))
877 ;; In Overwrite mode, maybe untabify while deleting
878 ((null (or (null overwrite-mode)
879 (<= n 0)
880 (memq (char-before) '(?\t ?\n))
881 (eobp)
882 (eq (char-after) ?\n)))
883 (let* ((ocol (current-column))
884 (val (delete-char (- n) killflag)))
885 (save-excursion
886 (insert-char ?\s (- ocol (current-column)) nil))))
887 ;; Otherwise, do simple deletion.
888 (t (delete-char (- n) killflag))))
890 (defun delete-forward-char (n &optional killflag)
891 "Delete the following N characters (previous if N is negative).
892 If Transient Mark mode is enabled, the mark is active, and N is 1,
893 delete the text in the region and deactivate the mark instead.
894 To disable this, set `delete-active-region' to nil.
896 Optional second arg KILLFLAG non-nil means to kill (save in kill
897 ring) instead of delete. Interactively, N is the prefix arg, and
898 KILLFLAG is set if N was explicitly specified."
899 (interactive "p\nP")
900 (unless (integerp n)
901 (signal 'wrong-type-argument (list 'integerp n)))
902 (cond ((and (use-region-p)
903 delete-active-region
904 (= n 1))
905 ;; If a region is active, kill or delete it.
906 (if (eq delete-active-region 'kill)
907 (kill-region (region-beginning) (region-end))
908 (delete-region (region-beginning) (region-end))))
909 ;; Otherwise, do simple deletion.
910 (t (delete-char n killflag))))
912 (defun mark-whole-buffer ()
913 "Put point at beginning and mark at end of buffer.
914 You probably should not use this function in Lisp programs;
915 it is usually a mistake for a Lisp function to use any subroutine
916 that uses or sets the mark."
917 (interactive)
918 (push-mark (point))
919 (push-mark (point-max) nil t)
920 (goto-char (point-min)))
923 ;; Counting lines, one way or another.
925 (defun goto-line (line &optional buffer)
926 "Goto LINE, counting from line 1 at beginning of buffer.
927 Normally, move point in the current buffer, and leave mark at the
928 previous position. With just \\[universal-argument] as argument,
929 move point in the most recently selected other buffer, and switch to it.
931 If there's a number in the buffer at point, it is the default for LINE.
933 This function is usually the wrong thing to use in a Lisp program.
934 What you probably want instead is something like:
935 (goto-char (point-min)) (forward-line (1- N))
936 If at all possible, an even better solution is to use char counts
937 rather than line counts."
938 (interactive
939 (if (and current-prefix-arg (not (consp current-prefix-arg)))
940 (list (prefix-numeric-value current-prefix-arg))
941 ;; Look for a default, a number in the buffer at point.
942 (let* ((default
943 (save-excursion
944 (skip-chars-backward "0-9")
945 (if (looking-at "[0-9]")
946 (buffer-substring-no-properties
947 (point)
948 (progn (skip-chars-forward "0-9")
949 (point))))))
950 ;; Decide if we're switching buffers.
951 (buffer
952 (if (consp current-prefix-arg)
953 (other-buffer (current-buffer) t)))
954 (buffer-prompt
955 (if buffer
956 (concat " in " (buffer-name buffer))
957 "")))
958 ;; Read the argument, offering that number (if any) as default.
959 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
960 "Goto line%s: ")
961 buffer-prompt
962 default)
963 nil nil t
964 'minibuffer-history
965 default)
966 buffer))))
967 ;; Switch to the desired buffer, one way or another.
968 (if buffer
969 (let ((window (get-buffer-window buffer)))
970 (if window (select-window window)
971 (switch-to-buffer-other-window buffer))))
972 ;; Leave mark at previous position
973 (or (region-active-p) (push-mark))
974 ;; Move to the specified line number in that buffer.
975 (save-restriction
976 (widen)
977 (goto-char (point-min))
978 (if (eq selective-display t)
979 (re-search-forward "[\n\C-m]" nil 'end (1- line))
980 (forward-line (1- line)))))
982 (defun count-words-region (start end)
983 "Print the number of words in the region.
984 When called interactively, the word count is printed in echo area."
985 (interactive "r")
986 (let ((count 0))
987 (save-excursion
988 (save-restriction
989 (narrow-to-region start end)
990 (goto-char (point-min))
991 (while (forward-word 1)
992 (setq count (1+ count)))))
993 (if (interactive-p)
994 (message "Region has %d words" count))
995 count))
997 (defun count-lines-region (start end)
998 "Print number of lines and characters in the region."
999 (interactive "r")
1000 (message "Region has %d lines, %d characters"
1001 (count-lines start end) (- end start)))
1003 (defun what-line ()
1004 "Print the current buffer line number and narrowed line number of point."
1005 (interactive)
1006 (let ((start (point-min))
1007 (n (line-number-at-pos)))
1008 (if (= start 1)
1009 (message "Line %d" n)
1010 (save-excursion
1011 (save-restriction
1012 (widen)
1013 (message "line %d (narrowed line %d)"
1014 (+ n (line-number-at-pos start) -1) n))))))
1016 (defun count-lines (start end)
1017 "Return number of lines between START and END.
1018 This is usually the number of newlines between them,
1019 but can be one more if START is not equal to END
1020 and the greater of them is not at the start of a line."
1021 (save-excursion
1022 (save-restriction
1023 (narrow-to-region start end)
1024 (goto-char (point-min))
1025 (if (eq selective-display t)
1026 (save-match-data
1027 (let ((done 0))
1028 (while (re-search-forward "[\n\C-m]" nil t 40)
1029 (setq done (+ 40 done)))
1030 (while (re-search-forward "[\n\C-m]" nil t 1)
1031 (setq done (+ 1 done)))
1032 (goto-char (point-max))
1033 (if (and (/= start end)
1034 (not (bolp)))
1035 (1+ done)
1036 done)))
1037 (- (buffer-size) (forward-line (buffer-size)))))))
1039 (defun line-number-at-pos (&optional pos)
1040 "Return (narrowed) buffer line number at position POS.
1041 If POS is nil, use current buffer location.
1042 Counting starts at (point-min), so the value refers
1043 to the contents of the accessible portion of the buffer."
1044 (let ((opoint (or pos (point))) start)
1045 (save-excursion
1046 (goto-char (point-min))
1047 (setq start (point))
1048 (goto-char opoint)
1049 (forward-line 0)
1050 (1+ (count-lines start (point))))))
1052 (defun what-cursor-position (&optional detail)
1053 "Print info on cursor position (on screen and within buffer).
1054 Also describe the character after point, and give its character code
1055 in octal, decimal and hex.
1057 For a non-ASCII multibyte character, also give its encoding in the
1058 buffer's selected coding system if the coding system encodes the
1059 character safely. If the character is encoded into one byte, that
1060 code is shown in hex. If the character is encoded into more than one
1061 byte, just \"...\" is shown.
1063 In addition, with prefix argument, show details about that character
1064 in *Help* buffer. See also the command `describe-char'."
1065 (interactive "P")
1066 (let* ((char (following-char))
1067 (beg (point-min))
1068 (end (point-max))
1069 (pos (point))
1070 (total (buffer-size))
1071 (percent (if (> total 50000)
1072 ;; Avoid overflow from multiplying by 100!
1073 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
1074 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
1075 (hscroll (if (= (window-hscroll) 0)
1077 (format " Hscroll=%d" (window-hscroll))))
1078 (col (current-column)))
1079 (if (= pos end)
1080 (if (or (/= beg 1) (/= end (1+ total)))
1081 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1082 pos total percent beg end col hscroll)
1083 (message "point=%d of %d (EOB) column=%d%s"
1084 pos total col hscroll))
1085 (let ((coding buffer-file-coding-system)
1086 encoded encoding-msg display-prop under-display)
1087 (if (or (not coding)
1088 (eq (coding-system-type coding) t))
1089 (setq coding (default-value 'buffer-file-coding-system)))
1090 (if (eq (char-charset char) 'eight-bit)
1091 (setq encoding-msg
1092 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1093 ;; Check if the character is displayed with some `display'
1094 ;; text property. In that case, set under-display to the
1095 ;; buffer substring covered by that property.
1096 (setq display-prop (get-text-property pos 'display))
1097 (if display-prop
1098 (let ((to (or (next-single-property-change pos 'display)
1099 (point-max))))
1100 (if (< to (+ pos 4))
1101 (setq under-display "")
1102 (setq under-display "..."
1103 to (+ pos 4)))
1104 (setq under-display
1105 (concat (buffer-substring-no-properties pos to)
1106 under-display)))
1107 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1108 (setq encoding-msg
1109 (if display-prop
1110 (if (not (stringp display-prop))
1111 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1112 char char char under-display)
1113 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1114 char char char under-display display-prop))
1115 (if encoded
1116 (format "(%d, #o%o, #x%x, file %s)"
1117 char char char
1118 (if (> (length encoded) 1)
1119 "..."
1120 (encoded-string-description encoded coding)))
1121 (format "(%d, #o%o, #x%x)" char char char)))))
1122 (if detail
1123 ;; We show the detailed information about CHAR.
1124 (describe-char (point)))
1125 (if (or (/= beg 1) (/= end (1+ total)))
1126 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1127 (if (< char 256)
1128 (single-key-description char)
1129 (buffer-substring-no-properties (point) (1+ (point))))
1130 encoding-msg pos total percent beg end col hscroll)
1131 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
1132 (if enable-multibyte-characters
1133 (if (< char 128)
1134 (single-key-description char)
1135 (buffer-substring-no-properties (point) (1+ (point))))
1136 (single-key-description char))
1137 encoding-msg pos total percent col hscroll))))))
1139 ;; Initialize read-expression-map. It is defined at C level.
1140 (let ((m (make-sparse-keymap)))
1141 (define-key m "\M-\t" 'lisp-complete-symbol)
1142 (set-keymap-parent m minibuffer-local-map)
1143 (setq read-expression-map m))
1145 (defvar minibuffer-completing-symbol nil
1146 "Non-nil means completing a Lisp symbol in the minibuffer.")
1148 (defvar minibuffer-default nil
1149 "The current default value or list of default values in the minibuffer.
1150 The functions `read-from-minibuffer' and `completing-read' bind
1151 this variable locally.")
1153 (defcustom eval-expression-print-level 4
1154 "Value for `print-level' while printing value in `eval-expression'.
1155 A value of nil means no limit."
1156 :group 'lisp
1157 :type '(choice (const :tag "No Limit" nil) integer)
1158 :version "21.1")
1160 (defcustom eval-expression-print-length 12
1161 "Value for `print-length' while printing value in `eval-expression'.
1162 A value of nil means no limit."
1163 :group 'lisp
1164 :type '(choice (const :tag "No Limit" nil) integer)
1165 :version "21.1")
1167 (defcustom eval-expression-debug-on-error t
1168 "If non-nil set `debug-on-error' to t in `eval-expression'.
1169 If nil, don't change the value of `debug-on-error'."
1170 :group 'lisp
1171 :type 'boolean
1172 :version "21.1")
1174 (defun eval-expression-print-format (value)
1175 "Format VALUE as a result of evaluated expression.
1176 Return a formatted string which is displayed in the echo area
1177 in addition to the value printed by prin1 in functions which
1178 display the result of expression evaluation."
1179 (if (and (integerp value)
1180 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1181 (eq this-command last-command)
1182 (if (boundp 'edebug-active) edebug-active)))
1183 (let ((char-string
1184 (if (or (if (boundp 'edebug-active) edebug-active)
1185 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1186 (prin1-char value))))
1187 (if char-string
1188 (format " (#o%o, #x%x, %s)" value value char-string)
1189 (format " (#o%o, #x%x)" value value)))))
1191 ;; We define this, rather than making `eval' interactive,
1192 ;; for the sake of completion of names like eval-region, eval-buffer.
1193 (defun eval-expression (eval-expression-arg
1194 &optional eval-expression-insert-value)
1195 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1196 Value is also consed on to front of the variable `values'.
1197 Optional argument EVAL-EXPRESSION-INSERT-VALUE non-nil (interactively,
1198 with prefix argument) means insert the result into the current buffer
1199 instead of printing it in the echo area. Truncates long output
1200 according to the value of the variables `eval-expression-print-length'
1201 and `eval-expression-print-level'.
1203 If `eval-expression-debug-on-error' is non-nil, which is the default,
1204 this command arranges for all errors to enter the debugger."
1205 (interactive
1206 (list (let ((minibuffer-completing-symbol t))
1207 (read-from-minibuffer "Eval: "
1208 nil read-expression-map t
1209 'read-expression-history))
1210 current-prefix-arg))
1212 (if (null eval-expression-debug-on-error)
1213 (setq values (cons (eval eval-expression-arg) values))
1214 (let ((old-value (make-symbol "t")) new-value)
1215 ;; Bind debug-on-error to something unique so that we can
1216 ;; detect when evaled code changes it.
1217 (let ((debug-on-error old-value))
1218 (setq values (cons (eval eval-expression-arg) values))
1219 (setq new-value debug-on-error))
1220 ;; If evaled code has changed the value of debug-on-error,
1221 ;; propagate that change to the global binding.
1222 (unless (eq old-value new-value)
1223 (setq debug-on-error new-value))))
1225 (let ((print-length eval-expression-print-length)
1226 (print-level eval-expression-print-level))
1227 (if eval-expression-insert-value
1228 (with-no-warnings
1229 (let ((standard-output (current-buffer)))
1230 (prin1 (car values))))
1231 (prog1
1232 (prin1 (car values) t)
1233 (let ((str (eval-expression-print-format (car values))))
1234 (if str (princ str t)))))))
1236 (defun edit-and-eval-command (prompt command)
1237 "Prompting with PROMPT, let user edit COMMAND and eval result.
1238 COMMAND is a Lisp expression. Let user edit that expression in
1239 the minibuffer, then read and evaluate the result."
1240 (let ((command
1241 (let ((print-level nil)
1242 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1243 (unwind-protect
1244 (read-from-minibuffer prompt
1245 (prin1-to-string command)
1246 read-expression-map t
1247 'command-history)
1248 ;; If command was added to command-history as a string,
1249 ;; get rid of that. We want only evaluable expressions there.
1250 (if (stringp (car command-history))
1251 (setq command-history (cdr command-history)))))))
1253 ;; If command to be redone does not match front of history,
1254 ;; add it to the history.
1255 (or (equal command (car command-history))
1256 (setq command-history (cons command command-history)))
1257 (eval command)))
1259 (defun repeat-complex-command (arg)
1260 "Edit and re-evaluate last complex command, or ARGth from last.
1261 A complex command is one which used the minibuffer.
1262 The command is placed in the minibuffer as a Lisp form for editing.
1263 The result is executed, repeating the command as changed.
1264 If the command has been changed or is not the most recent previous
1265 command it is added to the front of the command history.
1266 You can use the minibuffer history commands \
1267 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1268 to get different commands to edit and resubmit."
1269 (interactive "p")
1270 (let ((elt (nth (1- arg) command-history))
1271 newcmd)
1272 (if elt
1273 (progn
1274 (setq newcmd
1275 (let ((print-level nil)
1276 (minibuffer-history-position arg)
1277 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1278 (unwind-protect
1279 (read-from-minibuffer
1280 "Redo: " (prin1-to-string elt) read-expression-map t
1281 (cons 'command-history arg))
1283 ;; If command was added to command-history as a
1284 ;; string, get rid of that. We want only
1285 ;; evaluable expressions there.
1286 (if (stringp (car command-history))
1287 (setq command-history (cdr command-history))))))
1289 ;; If command to be redone does not match front of history,
1290 ;; add it to the history.
1291 (or (equal newcmd (car command-history))
1292 (setq command-history (cons newcmd command-history)))
1293 (eval newcmd))
1294 (if command-history
1295 (error "Argument %d is beyond length of command history" arg)
1296 (error "There are no previous complex commands to repeat")))))
1298 (defun read-extended-command ()
1299 "Read command name to invoke in `execute-extended-command'."
1300 (minibuffer-with-setup-hook
1301 (lambda ()
1302 (set (make-local-variable 'minibuffer-default-add-function)
1303 (lambda ()
1304 ;; Get a command name at point in the original buffer
1305 ;; to propose it after M-n.
1306 (with-current-buffer (window-buffer (minibuffer-selected-window))
1307 (and (commandp (function-called-at-point))
1308 (format "%S" (function-called-at-point)))))))
1309 ;; Read a string, completing from and restricting to the set of
1310 ;; all defined commands. Don't provide any initial input.
1311 ;; Save the command read on the extended-command history list.
1312 (completing-read
1313 (concat (cond
1314 ((eq current-prefix-arg '-) "- ")
1315 ((and (consp current-prefix-arg)
1316 (eq (car current-prefix-arg) 4)) "C-u ")
1317 ((and (consp current-prefix-arg)
1318 (integerp (car current-prefix-arg)))
1319 (format "%d " (car current-prefix-arg)))
1320 ((integerp current-prefix-arg)
1321 (format "%d " current-prefix-arg)))
1322 ;; This isn't strictly correct if `execute-extended-command'
1323 ;; is bound to anything else (e.g. [menu]).
1324 ;; It could use (key-description (this-single-command-keys)),
1325 ;; but actually a prompt other than "M-x" would be confusing,
1326 ;; because "M-x" is a well-known prompt to read a command
1327 ;; and it serves as a shorthand for "Extended command: ".
1328 "M-x ")
1329 obarray 'commandp t nil 'extended-command-history)))
1332 (defvar minibuffer-history nil
1333 "Default minibuffer history list.
1334 This is used for all minibuffer input
1335 except when an alternate history list is specified.
1337 Maximum length of the history list is determined by the value
1338 of `history-length', which see.")
1339 (defvar minibuffer-history-sexp-flag nil
1340 "Control whether history list elements are expressions or strings.
1341 If the value of this variable equals current minibuffer depth,
1342 they are expressions; otherwise they are strings.
1343 \(That convention is designed to do the right thing for
1344 recursive uses of the minibuffer.)")
1345 (setq minibuffer-history-variable 'minibuffer-history)
1346 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1347 (defvar minibuffer-history-search-history nil)
1349 (defvar minibuffer-text-before-history nil
1350 "Text that was in this minibuffer before any history commands.
1351 This is nil if there have not yet been any history commands
1352 in this use of the minibuffer.")
1354 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1356 (defun minibuffer-history-initialize ()
1357 (setq minibuffer-text-before-history nil))
1359 (defun minibuffer-avoid-prompt (new old)
1360 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1361 (constrain-to-field nil (point-max)))
1363 (defcustom minibuffer-history-case-insensitive-variables nil
1364 "Minibuffer history variables for which matching should ignore case.
1365 If a history variable is a member of this list, then the
1366 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1367 commands ignore case when searching it, regardless of `case-fold-search'."
1368 :type '(repeat variable)
1369 :group 'minibuffer)
1371 (defun previous-matching-history-element (regexp n)
1372 "Find the previous history element that matches REGEXP.
1373 \(Previous history elements refer to earlier actions.)
1374 With prefix argument N, search for Nth previous match.
1375 If N is negative, find the next or Nth next match.
1376 Normally, history elements are matched case-insensitively if
1377 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1378 makes the search case-sensitive.
1379 See also `minibuffer-history-case-insensitive-variables'."
1380 (interactive
1381 (let* ((enable-recursive-minibuffers t)
1382 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1384 minibuffer-local-map
1386 'minibuffer-history-search-history
1387 (car minibuffer-history-search-history))))
1388 ;; Use the last regexp specified, by default, if input is empty.
1389 (list (if (string= regexp "")
1390 (if minibuffer-history-search-history
1391 (car minibuffer-history-search-history)
1392 (error "No previous history search regexp"))
1393 regexp)
1394 (prefix-numeric-value current-prefix-arg))))
1395 (unless (zerop n)
1396 (if (and (zerop minibuffer-history-position)
1397 (null minibuffer-text-before-history))
1398 (setq minibuffer-text-before-history
1399 (minibuffer-contents-no-properties)))
1400 (let ((history (symbol-value minibuffer-history-variable))
1401 (case-fold-search
1402 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1403 ;; On some systems, ignore case for file names.
1404 (if (memq minibuffer-history-variable
1405 minibuffer-history-case-insensitive-variables)
1407 ;; Respect the user's setting for case-fold-search:
1408 case-fold-search)
1409 nil))
1410 prevpos
1411 match-string
1412 match-offset
1413 (pos minibuffer-history-position))
1414 (while (/= n 0)
1415 (setq prevpos pos)
1416 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1417 (when (= pos prevpos)
1418 (error (if (= pos 1)
1419 "No later matching history item"
1420 "No earlier matching history item")))
1421 (setq match-string
1422 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1423 (let ((print-level nil))
1424 (prin1-to-string (nth (1- pos) history)))
1425 (nth (1- pos) history)))
1426 (setq match-offset
1427 (if (< n 0)
1428 (and (string-match regexp match-string)
1429 (match-end 0))
1430 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1431 (match-beginning 1))))
1432 (when match-offset
1433 (setq n (+ n (if (< n 0) 1 -1)))))
1434 (setq minibuffer-history-position pos)
1435 (goto-char (point-max))
1436 (delete-minibuffer-contents)
1437 (insert match-string)
1438 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1439 (if (memq (car (car command-history)) '(previous-matching-history-element
1440 next-matching-history-element))
1441 (setq command-history (cdr command-history))))
1443 (defun next-matching-history-element (regexp n)
1444 "Find the next history element that matches REGEXP.
1445 \(The next history element refers to a more recent action.)
1446 With prefix argument N, search for Nth next match.
1447 If N is negative, find the previous or Nth previous match.
1448 Normally, history elements are matched case-insensitively if
1449 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1450 makes the search case-sensitive."
1451 (interactive
1452 (let* ((enable-recursive-minibuffers t)
1453 (regexp (read-from-minibuffer "Next element matching (regexp): "
1455 minibuffer-local-map
1457 'minibuffer-history-search-history
1458 (car minibuffer-history-search-history))))
1459 ;; Use the last regexp specified, by default, if input is empty.
1460 (list (if (string= regexp "")
1461 (if minibuffer-history-search-history
1462 (car minibuffer-history-search-history)
1463 (error "No previous history search regexp"))
1464 regexp)
1465 (prefix-numeric-value current-prefix-arg))))
1466 (previous-matching-history-element regexp (- n)))
1468 (defvar minibuffer-temporary-goal-position nil)
1470 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1471 "Function run by `goto-history-element' before consuming default values.
1472 This is useful to dynamically add more elements to the list of default values
1473 when `goto-history-element' reaches the end of this list.
1474 Before calling this function `goto-history-element' sets the variable
1475 `minibuffer-default-add-done' to t, so it will call this function only
1476 once. In special cases, when this function needs to be called more
1477 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1478 overriding the setting of this variable to t in `goto-history-element'.")
1480 (defvar minibuffer-default-add-done nil
1481 "When nil, add more elements to the end of the list of default values.
1482 The value nil causes `goto-history-element' to add more elements to
1483 the list of defaults when it reaches the end of this list. It does
1484 this by calling a function defined by `minibuffer-default-add-function'.")
1486 (make-variable-buffer-local 'minibuffer-default-add-done)
1488 (defun minibuffer-default-add-completions ()
1489 "Return a list of all completions without the default value.
1490 This function is used to add all elements of the completion table to
1491 the end of the list of defaults just after the default value."
1492 (let ((def minibuffer-default)
1493 (all (all-completions ""
1494 minibuffer-completion-table
1495 minibuffer-completion-predicate)))
1496 (if (listp def)
1497 (append def all)
1498 (cons def (delete def all)))))
1500 (defun goto-history-element (nabs)
1501 "Puts element of the minibuffer history in the minibuffer.
1502 The argument NABS specifies the absolute history position."
1503 (interactive "p")
1504 (when (and (not minibuffer-default-add-done)
1505 (functionp minibuffer-default-add-function)
1506 (< nabs (- (if (listp minibuffer-default)
1507 (length minibuffer-default)
1508 1))))
1509 (setq minibuffer-default-add-done t
1510 minibuffer-default (funcall minibuffer-default-add-function)))
1511 (let ((minimum (if minibuffer-default
1512 (- (if (listp minibuffer-default)
1513 (length minibuffer-default)
1516 elt minibuffer-returned-to-present)
1517 (if (and (zerop minibuffer-history-position)
1518 (null minibuffer-text-before-history))
1519 (setq minibuffer-text-before-history
1520 (minibuffer-contents-no-properties)))
1521 (if (< nabs minimum)
1522 (if minibuffer-default
1523 (error "End of defaults; no next item")
1524 (error "End of history; no default available")))
1525 (if (> nabs (length (symbol-value minibuffer-history-variable)))
1526 (error "Beginning of history; no preceding item"))
1527 (unless (memq last-command '(next-history-element
1528 previous-history-element))
1529 (let ((prompt-end (minibuffer-prompt-end)))
1530 (set (make-local-variable 'minibuffer-temporary-goal-position)
1531 (cond ((<= (point) prompt-end) prompt-end)
1532 ((eobp) nil)
1533 (t (point))))))
1534 (goto-char (point-max))
1535 (delete-minibuffer-contents)
1536 (setq minibuffer-history-position nabs)
1537 (cond ((< nabs 0)
1538 (setq elt (if (listp minibuffer-default)
1539 (nth (1- (abs nabs)) minibuffer-default)
1540 minibuffer-default)))
1541 ((= nabs 0)
1542 (setq elt (or minibuffer-text-before-history ""))
1543 (setq minibuffer-returned-to-present t)
1544 (setq minibuffer-text-before-history nil))
1545 (t (setq elt (nth (1- minibuffer-history-position)
1546 (symbol-value minibuffer-history-variable)))))
1547 (insert
1548 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1549 (not minibuffer-returned-to-present))
1550 (let ((print-level nil))
1551 (prin1-to-string elt))
1552 elt))
1553 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
1555 (defun next-history-element (n)
1556 "Puts next element of the minibuffer history in the minibuffer.
1557 With argument N, it uses the Nth following element."
1558 (interactive "p")
1559 (or (zerop n)
1560 (goto-history-element (- minibuffer-history-position n))))
1562 (defun previous-history-element (n)
1563 "Puts previous element of the minibuffer history in the minibuffer.
1564 With argument N, it uses the Nth previous element."
1565 (interactive "p")
1566 (or (zerop n)
1567 (goto-history-element (+ minibuffer-history-position n))))
1569 (defun next-complete-history-element (n)
1570 "Get next history element which completes the minibuffer before the point.
1571 The contents of the minibuffer after the point are deleted, and replaced
1572 by the new completion."
1573 (interactive "p")
1574 (let ((point-at-start (point)))
1575 (next-matching-history-element
1576 (concat
1577 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1579 ;; next-matching-history-element always puts us at (point-min).
1580 ;; Move to the position we were at before changing the buffer contents.
1581 ;; This is still sensical, because the text before point has not changed.
1582 (goto-char point-at-start)))
1584 (defun previous-complete-history-element (n)
1586 Get previous history element which completes the minibuffer before the point.
1587 The contents of the minibuffer after the point are deleted, and replaced
1588 by the new completion."
1589 (interactive "p")
1590 (next-complete-history-element (- n)))
1592 ;; For compatibility with the old subr of the same name.
1593 (defun minibuffer-prompt-width ()
1594 "Return the display width of the minibuffer prompt.
1595 Return 0 if current buffer is not a minibuffer."
1596 ;; Return the width of everything before the field at the end of
1597 ;; the buffer; this should be 0 for normal buffers.
1598 (1- (minibuffer-prompt-end)))
1600 ;; isearch minibuffer history
1601 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
1603 (defvar minibuffer-history-isearch-message-overlay)
1604 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
1606 (defun minibuffer-history-isearch-setup ()
1607 "Set up a minibuffer for using isearch to search the minibuffer history.
1608 Intended to be added to `minibuffer-setup-hook'."
1609 (set (make-local-variable 'isearch-search-fun-function)
1610 'minibuffer-history-isearch-search)
1611 (set (make-local-variable 'isearch-message-function)
1612 'minibuffer-history-isearch-message)
1613 (set (make-local-variable 'isearch-wrap-function)
1614 'minibuffer-history-isearch-wrap)
1615 (set (make-local-variable 'isearch-push-state-function)
1616 'minibuffer-history-isearch-push-state)
1617 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
1619 (defun minibuffer-history-isearch-end ()
1620 "Clean up the minibuffer after terminating isearch in the minibuffer."
1621 (if minibuffer-history-isearch-message-overlay
1622 (delete-overlay minibuffer-history-isearch-message-overlay)))
1624 (defun minibuffer-history-isearch-search ()
1625 "Return the proper search function, for isearch in minibuffer history."
1626 (cond
1627 (isearch-word
1628 (if isearch-forward 'word-search-forward 'word-search-backward))
1630 (lambda (string bound noerror)
1631 (let ((search-fun
1632 ;; Use standard functions to search within minibuffer text
1633 (cond
1634 (isearch-regexp
1635 (if isearch-forward 're-search-forward 're-search-backward))
1637 (if isearch-forward 'search-forward 'search-backward))))
1638 found)
1639 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1640 ;; searching forward. Lazy-highlight calls this lambda with the
1641 ;; bound arg, so skip the minibuffer prompt.
1642 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
1643 (goto-char (minibuffer-prompt-end)))
1645 ;; 1. First try searching in the initial minibuffer text
1646 (funcall search-fun string
1647 (if isearch-forward bound (minibuffer-prompt-end))
1648 noerror)
1649 ;; 2. If the above search fails, start putting next/prev history
1650 ;; elements in the minibuffer successively, and search the string
1651 ;; in them. Do this only when bound is nil (i.e. not while
1652 ;; lazy-highlighting search strings in the current minibuffer text).
1653 (unless bound
1654 (condition-case nil
1655 (progn
1656 (while (not found)
1657 (cond (isearch-forward
1658 (next-history-element 1)
1659 (goto-char (minibuffer-prompt-end)))
1661 (previous-history-element 1)
1662 (goto-char (point-max))))
1663 (setq isearch-barrier (point) isearch-opoint (point))
1664 ;; After putting the next/prev history element, search
1665 ;; the string in them again, until next-history-element
1666 ;; or previous-history-element raises an error at the
1667 ;; beginning/end of history.
1668 (setq found (funcall search-fun string
1669 (unless isearch-forward
1670 ;; For backward search, don't search
1671 ;; in the minibuffer prompt
1672 (minibuffer-prompt-end))
1673 noerror)))
1674 ;; Return point of the new search result
1675 (point))
1676 ;; Return nil when next(prev)-history-element fails
1677 (error nil)))))))))
1679 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
1680 "Display the minibuffer history search prompt.
1681 If there are no search errors, this function displays an overlay with
1682 the isearch prompt which replaces the original minibuffer prompt.
1683 Otherwise, it displays the standard isearch message returned from
1684 `isearch-message'."
1685 (if (not (and (minibufferp) isearch-success (not isearch-error)))
1686 ;; Use standard function `isearch-message' when not in the minibuffer,
1687 ;; or search fails, or has an error (like incomplete regexp).
1688 ;; This function overwrites minibuffer text with isearch message,
1689 ;; so it's possible to see what is wrong in the search string.
1690 (isearch-message c-q-hack ellipsis)
1691 ;; Otherwise, put the overlay with the standard isearch prompt over
1692 ;; the initial minibuffer prompt.
1693 (if (overlayp minibuffer-history-isearch-message-overlay)
1694 (move-overlay minibuffer-history-isearch-message-overlay
1695 (point-min) (minibuffer-prompt-end))
1696 (setq minibuffer-history-isearch-message-overlay
1697 (make-overlay (point-min) (minibuffer-prompt-end)))
1698 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
1699 (overlay-put minibuffer-history-isearch-message-overlay
1700 'display (isearch-message-prefix c-q-hack ellipsis))
1701 ;; And clear any previous isearch message.
1702 (message "")))
1704 (defun minibuffer-history-isearch-wrap ()
1705 "Wrap the minibuffer history search when search fails.
1706 Move point to the first history element for a forward search,
1707 or to the last history element for a backward search."
1708 (unless isearch-word
1709 ;; When `minibuffer-history-isearch-search' fails on reaching the
1710 ;; beginning/end of the history, wrap the search to the first/last
1711 ;; minibuffer history element.
1712 (if isearch-forward
1713 (goto-history-element (length (symbol-value minibuffer-history-variable)))
1714 (goto-history-element 0))
1715 (setq isearch-success t))
1716 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
1718 (defun minibuffer-history-isearch-push-state ()
1719 "Save a function restoring the state of minibuffer history search.
1720 Save `minibuffer-history-position' to the additional state parameter
1721 in the search status stack."
1722 `(lambda (cmd)
1723 (minibuffer-history-isearch-pop-state cmd ,minibuffer-history-position)))
1725 (defun minibuffer-history-isearch-pop-state (cmd hist-pos)
1726 "Restore the minibuffer history search state.
1727 Go to the history element by the absolute history position HIST-POS."
1728 (goto-history-element hist-pos))
1731 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1732 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
1734 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1735 "Table mapping redo records to the corresponding undo one.
1736 A redo record for undo-in-region maps to t.
1737 A redo record for ordinary undo maps to the following (earlier) undo.")
1739 (defvar undo-in-region nil
1740 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1742 (defvar undo-no-redo nil
1743 "If t, `undo' doesn't go through redo entries.")
1745 (defvar pending-undo-list nil
1746 "Within a run of consecutive undo commands, list remaining to be undone.
1747 If t, we undid all the way to the end of it.")
1749 (defun undo (&optional arg)
1750 "Undo some previous changes.
1751 Repeat this command to undo more changes.
1752 A numeric ARG serves as a repeat count.
1754 In Transient Mark mode when the mark is active, only undo changes within
1755 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1756 as an argument limits undo to changes within the current region."
1757 (interactive "*P")
1758 ;; Make last-command indicate for the next command that this was an undo.
1759 ;; That way, another undo will undo more.
1760 ;; If we get to the end of the undo history and get an error,
1761 ;; another undo command will find the undo history empty
1762 ;; and will get another error. To begin undoing the undos,
1763 ;; you must type some other command.
1764 (let ((modified (buffer-modified-p))
1765 (recent-save (recent-auto-save-p))
1766 message)
1767 ;; If we get an error in undo-start,
1768 ;; the next command should not be a "consecutive undo".
1769 ;; So set `this-command' to something other than `undo'.
1770 (setq this-command 'undo-start)
1772 (unless (and (eq last-command 'undo)
1773 (or (eq pending-undo-list t)
1774 ;; If something (a timer or filter?) changed the buffer
1775 ;; since the previous command, don't continue the undo seq.
1776 (let ((list buffer-undo-list))
1777 (while (eq (car list) nil)
1778 (setq list (cdr list)))
1779 ;; If the last undo record made was made by undo
1780 ;; it shows nothing else happened in between.
1781 (gethash list undo-equiv-table))))
1782 (setq undo-in-region
1783 (or (region-active-p) (and arg (not (numberp arg)))))
1784 (if undo-in-region
1785 (undo-start (region-beginning) (region-end))
1786 (undo-start))
1787 ;; get rid of initial undo boundary
1788 (undo-more 1))
1789 ;; If we got this far, the next command should be a consecutive undo.
1790 (setq this-command 'undo)
1791 ;; Check to see whether we're hitting a redo record, and if
1792 ;; so, ask the user whether she wants to skip the redo/undo pair.
1793 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1794 (or (eq (selected-window) (minibuffer-window))
1795 (setq message (if undo-in-region
1796 (if equiv "Redo in region!" "Undo in region!")
1797 (if equiv "Redo!" "Undo!"))))
1798 (when (and (consp equiv) undo-no-redo)
1799 ;; The equiv entry might point to another redo record if we have done
1800 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1801 (while (let ((next (gethash equiv undo-equiv-table)))
1802 (if next (setq equiv next))))
1803 (setq pending-undo-list equiv)))
1804 (undo-more
1805 (if (numberp arg)
1806 (prefix-numeric-value arg)
1808 ;; Record the fact that the just-generated undo records come from an
1809 ;; undo operation--that is, they are redo records.
1810 ;; In the ordinary case (not within a region), map the redo
1811 ;; record to the following undos.
1812 ;; I don't know how to do that in the undo-in-region case.
1813 (let ((list buffer-undo-list))
1814 ;; Strip any leading undo boundaries there might be, like we do
1815 ;; above when checking.
1816 (while (eq (car list) nil)
1817 (setq list (cdr list)))
1818 (puthash list (if undo-in-region t pending-undo-list)
1819 undo-equiv-table))
1820 ;; Don't specify a position in the undo record for the undo command.
1821 ;; Instead, undoing this should move point to where the change is.
1822 (let ((tail buffer-undo-list)
1823 (prev nil))
1824 (while (car tail)
1825 (when (integerp (car tail))
1826 (let ((pos (car tail)))
1827 (if prev
1828 (setcdr prev (cdr tail))
1829 (setq buffer-undo-list (cdr tail)))
1830 (setq tail (cdr tail))
1831 (while (car tail)
1832 (if (eq pos (car tail))
1833 (if prev
1834 (setcdr prev (cdr tail))
1835 (setq buffer-undo-list (cdr tail)))
1836 (setq prev tail))
1837 (setq tail (cdr tail)))
1838 (setq tail nil)))
1839 (setq prev tail tail (cdr tail))))
1840 ;; Record what the current undo list says,
1841 ;; so the next command can tell if the buffer was modified in between.
1842 (and modified (not (buffer-modified-p))
1843 (delete-auto-save-file-if-necessary recent-save))
1844 ;; Display a message announcing success.
1845 (if message
1846 (message "%s" message))))
1848 (defun buffer-disable-undo (&optional buffer)
1849 "Make BUFFER stop keeping undo information.
1850 No argument or nil as argument means do this for the current buffer."
1851 (interactive)
1852 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
1853 (setq buffer-undo-list t)))
1855 (defun undo-only (&optional arg)
1856 "Undo some previous changes.
1857 Repeat this command to undo more changes.
1858 A numeric ARG serves as a repeat count.
1859 Contrary to `undo', this will not redo a previous undo."
1860 (interactive "*p")
1861 (let ((undo-no-redo t)) (undo arg)))
1863 (defvar undo-in-progress nil
1864 "Non-nil while performing an undo.
1865 Some change-hooks test this variable to do something different.")
1867 (defun undo-more (n)
1868 "Undo back N undo-boundaries beyond what was already undone recently.
1869 Call `undo-start' to get ready to undo recent changes,
1870 then call `undo-more' one or more times to undo them."
1871 (or (listp pending-undo-list)
1872 (error (concat "No further undo information"
1873 (and undo-in-region " for region"))))
1874 (let ((undo-in-progress t))
1875 ;; Note: The following, while pulling elements off
1876 ;; `pending-undo-list' will call primitive change functions which
1877 ;; will push more elements onto `buffer-undo-list'.
1878 (setq pending-undo-list (primitive-undo n pending-undo-list))
1879 (if (null pending-undo-list)
1880 (setq pending-undo-list t))))
1882 ;; Deep copy of a list
1883 (defun undo-copy-list (list)
1884 "Make a copy of undo list LIST."
1885 (mapcar 'undo-copy-list-1 list))
1887 (defun undo-copy-list-1 (elt)
1888 (if (consp elt)
1889 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1890 elt))
1892 (defun undo-start (&optional beg end)
1893 "Set `pending-undo-list' to the front of the undo list.
1894 The next call to `undo-more' will undo the most recently made change.
1895 If BEG and END are specified, then only undo elements
1896 that apply to text between BEG and END are used; other undo elements
1897 are ignored. If BEG and END are nil, all undo elements are used."
1898 (if (eq buffer-undo-list t)
1899 (error "No undo information in this buffer"))
1900 (setq pending-undo-list
1901 (if (and beg end (not (= beg end)))
1902 (undo-make-selective-list (min beg end) (max beg end))
1903 buffer-undo-list)))
1905 (defvar undo-adjusted-markers)
1907 (defun undo-make-selective-list (start end)
1908 "Return a list of undo elements for the region START to END.
1909 The elements come from `buffer-undo-list', but we keep only
1910 the elements inside this region, and discard those outside this region.
1911 If we find an element that crosses an edge of this region,
1912 we stop and ignore all further elements."
1913 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1914 (undo-list (list nil))
1915 undo-adjusted-markers
1916 some-rejected
1917 undo-elt undo-elt temp-undo-list delta)
1918 (while undo-list-copy
1919 (setq undo-elt (car undo-list-copy))
1920 (let ((keep-this
1921 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1922 ;; This is a "was unmodified" element.
1923 ;; Keep it if we have kept everything thus far.
1924 (not some-rejected))
1926 (undo-elt-in-region undo-elt start end)))))
1927 (if keep-this
1928 (progn
1929 (setq end (+ end (cdr (undo-delta undo-elt))))
1930 ;; Don't put two nils together in the list
1931 (if (not (and (eq (car undo-list) nil)
1932 (eq undo-elt nil)))
1933 (setq undo-list (cons undo-elt undo-list))))
1934 (if (undo-elt-crosses-region undo-elt start end)
1935 (setq undo-list-copy nil)
1936 (setq some-rejected t)
1937 (setq temp-undo-list (cdr undo-list-copy))
1938 (setq delta (undo-delta undo-elt))
1940 (when (/= (cdr delta) 0)
1941 (let ((position (car delta))
1942 (offset (cdr delta)))
1944 ;; Loop down the earlier events adjusting their buffer
1945 ;; positions to reflect the fact that a change to the buffer
1946 ;; isn't being undone. We only need to process those element
1947 ;; types which undo-elt-in-region will return as being in
1948 ;; the region since only those types can ever get into the
1949 ;; output
1951 (while temp-undo-list
1952 (setq undo-elt (car temp-undo-list))
1953 (cond ((integerp undo-elt)
1954 (if (>= undo-elt position)
1955 (setcar temp-undo-list (- undo-elt offset))))
1956 ((atom undo-elt) nil)
1957 ((stringp (car undo-elt))
1958 ;; (TEXT . POSITION)
1959 (let ((text-pos (abs (cdr undo-elt)))
1960 (point-at-end (< (cdr undo-elt) 0 )))
1961 (if (>= text-pos position)
1962 (setcdr undo-elt (* (if point-at-end -1 1)
1963 (- text-pos offset))))))
1964 ((integerp (car undo-elt))
1965 ;; (BEGIN . END)
1966 (when (>= (car undo-elt) position)
1967 (setcar undo-elt (- (car undo-elt) offset))
1968 (setcdr undo-elt (- (cdr undo-elt) offset))))
1969 ((null (car undo-elt))
1970 ;; (nil PROPERTY VALUE BEG . END)
1971 (let ((tail (nthcdr 3 undo-elt)))
1972 (when (>= (car tail) position)
1973 (setcar tail (- (car tail) offset))
1974 (setcdr tail (- (cdr tail) offset))))))
1975 (setq temp-undo-list (cdr temp-undo-list))))))))
1976 (setq undo-list-copy (cdr undo-list-copy)))
1977 (nreverse undo-list)))
1979 (defun undo-elt-in-region (undo-elt start end)
1980 "Determine whether UNDO-ELT falls inside the region START ... END.
1981 If it crosses the edge, we return nil."
1982 (cond ((integerp undo-elt)
1983 (and (>= undo-elt start)
1984 (<= undo-elt end)))
1985 ((eq undo-elt nil)
1987 ((atom undo-elt)
1988 nil)
1989 ((stringp (car undo-elt))
1990 ;; (TEXT . POSITION)
1991 (and (>= (abs (cdr undo-elt)) start)
1992 (< (abs (cdr undo-elt)) end)))
1993 ((and (consp undo-elt) (markerp (car undo-elt)))
1994 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1995 ;; See if MARKER is inside the region.
1996 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1997 (unless alist-elt
1998 (setq alist-elt (cons (car undo-elt)
1999 (marker-position (car undo-elt))))
2000 (setq undo-adjusted-markers
2001 (cons alist-elt undo-adjusted-markers)))
2002 (and (cdr alist-elt)
2003 (>= (cdr alist-elt) start)
2004 (<= (cdr alist-elt) end))))
2005 ((null (car undo-elt))
2006 ;; (nil PROPERTY VALUE BEG . END)
2007 (let ((tail (nthcdr 3 undo-elt)))
2008 (and (>= (car tail) start)
2009 (<= (cdr tail) end))))
2010 ((integerp (car undo-elt))
2011 ;; (BEGIN . END)
2012 (and (>= (car undo-elt) start)
2013 (<= (cdr undo-elt) end)))))
2015 (defun undo-elt-crosses-region (undo-elt start end)
2016 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2017 This assumes we have already decided that UNDO-ELT
2018 is not *inside* the region START...END."
2019 (cond ((atom undo-elt) nil)
2020 ((null (car undo-elt))
2021 ;; (nil PROPERTY VALUE BEG . END)
2022 (let ((tail (nthcdr 3 undo-elt)))
2023 (and (< (car tail) end)
2024 (> (cdr tail) start))))
2025 ((integerp (car undo-elt))
2026 ;; (BEGIN . END)
2027 (and (< (car undo-elt) end)
2028 (> (cdr undo-elt) start)))))
2030 ;; Return the first affected buffer position and the delta for an undo element
2031 ;; delta is defined as the change in subsequent buffer positions if we *did*
2032 ;; the undo.
2033 (defun undo-delta (undo-elt)
2034 (if (consp undo-elt)
2035 (cond ((stringp (car undo-elt))
2036 ;; (TEXT . POSITION)
2037 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2038 ((integerp (car undo-elt))
2039 ;; (BEGIN . END)
2040 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2042 '(0 . 0)))
2043 '(0 . 0)))
2045 (defcustom undo-ask-before-discard nil
2046 "If non-nil ask about discarding undo info for the current command.
2047 Normally, Emacs discards the undo info for the current command if
2048 it exceeds `undo-outer-limit'. But if you set this option
2049 non-nil, it asks in the echo area whether to discard the info.
2050 If you answer no, there is a slight risk that Emacs might crash, so
2051 only do it if you really want to undo the command.
2053 This option is mainly intended for debugging. You have to be
2054 careful if you use it for other purposes. Garbage collection is
2055 inhibited while the question is asked, meaning that Emacs might
2056 leak memory. So you should make sure that you do not wait
2057 excessively long before answering the question."
2058 :type 'boolean
2059 :group 'undo
2060 :version "22.1")
2062 (defvar undo-extra-outer-limit nil
2063 "If non-nil, an extra level of size that's ok in an undo item.
2064 We don't ask the user about truncating the undo list until the
2065 current item gets bigger than this amount.
2067 This variable only matters if `undo-ask-before-discard' is non-nil.")
2068 (make-variable-buffer-local 'undo-extra-outer-limit)
2070 ;; When the first undo batch in an undo list is longer than
2071 ;; undo-outer-limit, this function gets called to warn the user that
2072 ;; the undo info for the current command was discarded. Garbage
2073 ;; collection is inhibited around the call, so it had better not do a
2074 ;; lot of consing.
2075 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2076 (defun undo-outer-limit-truncate (size)
2077 (if undo-ask-before-discard
2078 (when (or (null undo-extra-outer-limit)
2079 (> size undo-extra-outer-limit))
2080 ;; Don't ask the question again unless it gets even bigger.
2081 ;; This applies, in particular, if the user quits from the question.
2082 ;; Such a quit quits out of GC, but something else will call GC
2083 ;; again momentarily. It will call this function again,
2084 ;; but we don't want to ask the question again.
2085 (setq undo-extra-outer-limit (+ size 50000))
2086 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2087 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2088 (buffer-name) size)))
2089 (progn (setq buffer-undo-list nil)
2090 (setq undo-extra-outer-limit nil)
2092 nil))
2093 (display-warning '(undo discard-info)
2094 (concat
2095 (format "Buffer `%s' undo info was %d bytes long.\n"
2096 (buffer-name) size)
2097 "The undo info was discarded because it exceeded \
2098 `undo-outer-limit'.
2100 This is normal if you executed a command that made a huge change
2101 to the buffer. In that case, to prevent similar problems in the
2102 future, set `undo-outer-limit' to a value that is large enough to
2103 cover the maximum size of normal changes you expect a single
2104 command to make, but not so large that it might exceed the
2105 maximum memory allotted to Emacs.
2107 If you did not execute any such command, the situation is
2108 probably due to a bug and you should report it.
2110 You can disable the popping up of this buffer by adding the entry
2111 \(undo discard-info) to the user option `warning-suppress-types',
2112 which is defined in the `warnings' library.\n")
2113 :warning)
2114 (setq buffer-undo-list nil)
2117 (defvar shell-command-history nil
2118 "History list for some commands that read shell commands.
2120 Maximum length of the history list is determined by the value
2121 of `history-length', which see.")
2123 (defvar shell-command-switch (purecopy "-c")
2124 "Switch used to have the shell execute its command line argument.")
2126 (defvar shell-command-default-error-buffer nil
2127 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
2128 This buffer is used when `shell-command' or `shell-command-on-region'
2129 is run interactively. A value of nil means that output to stderr and
2130 stdout will be intermixed in the output stream.")
2132 (declare-function mailcap-file-default-commands "mailcap" (files))
2133 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2135 (defun minibuffer-default-add-shell-commands ()
2136 "Return a list of all commands associated with the current file.
2137 This function is used to add all related commands retrieved by `mailcap'
2138 to the end of the list of defaults just after the default value."
2139 (interactive)
2140 (let* ((filename (if (listp minibuffer-default)
2141 (car minibuffer-default)
2142 minibuffer-default))
2143 (commands (and filename (require 'mailcap nil t)
2144 (mailcap-file-default-commands (list filename)))))
2145 (setq commands (mapcar (lambda (command)
2146 (concat command " " filename))
2147 commands))
2148 (if (listp minibuffer-default)
2149 (append minibuffer-default commands)
2150 (cons minibuffer-default commands))))
2152 (defvar shell-delimiter-argument-list)
2153 (defvar shell-file-name-chars)
2154 (defvar shell-file-name-quote-list)
2156 (defun minibuffer-complete-shell-command ()
2157 "Dynamically complete shell command at point."
2158 (interactive)
2159 (require 'shell)
2160 (let ((comint-delimiter-argument-list shell-delimiter-argument-list)
2161 (comint-file-name-chars shell-file-name-chars)
2162 (comint-file-name-quote-list shell-file-name-quote-list))
2163 (run-hook-with-args-until-success 'shell-dynamic-complete-functions)))
2165 (defvar minibuffer-local-shell-command-map
2166 (let ((map (make-sparse-keymap)))
2167 (set-keymap-parent map minibuffer-local-map)
2168 (define-key map "\t" 'minibuffer-complete-shell-command)
2169 map)
2170 "Keymap used for completing shell commands in minibuffer.")
2172 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
2173 "Read a shell command from the minibuffer.
2174 The arguments are the same as the ones of `read-from-minibuffer',
2175 except READ and KEYMAP are missing and HIST defaults
2176 to `shell-command-history'."
2177 (minibuffer-with-setup-hook
2178 (lambda ()
2179 (set (make-local-variable 'minibuffer-default-add-function)
2180 'minibuffer-default-add-shell-commands))
2181 (apply 'read-from-minibuffer prompt initial-contents
2182 minibuffer-local-shell-command-map
2184 (or hist 'shell-command-history)
2185 args)))
2187 (defun async-shell-command (command &optional output-buffer error-buffer)
2188 "Execute string COMMAND asynchronously in background.
2190 Like `shell-command' but if COMMAND doesn't end in ampersand, adds `&'
2191 surrounded by whitespace and executes the command asynchronously.
2192 The output appears in the buffer `*Async Shell Command*'.
2194 In Elisp, you will often be better served by calling `start-process'
2195 directly, since it offers more control and does not impose the use of a
2196 shell (with its need to quote arguments)."
2197 (interactive
2198 (list
2199 (read-shell-command "Async shell command: " nil nil
2200 (and buffer-file-name
2201 (file-relative-name buffer-file-name)))
2202 current-prefix-arg
2203 shell-command-default-error-buffer))
2204 (unless (string-match "&[ \t]*\\'" command)
2205 (setq command (concat command " &")))
2206 (shell-command command output-buffer error-buffer))
2208 (defun shell-command (command &optional output-buffer error-buffer)
2209 "Execute string COMMAND in inferior shell; display output, if any.
2210 With prefix argument, insert the COMMAND's output at point.
2212 If COMMAND ends in ampersand, execute it asynchronously.
2213 The output appears in the buffer `*Async Shell Command*'.
2214 That buffer is in shell mode.
2216 Otherwise, COMMAND is executed synchronously. The output appears in
2217 the buffer `*Shell Command Output*'. If the output is short enough to
2218 display in the echo area (which is determined by the variables
2219 `resize-mini-windows' and `max-mini-window-height'), it is shown
2220 there, but it is nonetheless available in buffer `*Shell Command
2221 Output*' even though that buffer is not automatically displayed.
2223 To specify a coding system for converting non-ASCII characters
2224 in the shell command output, use \\[universal-coding-system-argument] \
2225 before this command.
2227 Noninteractive callers can specify coding systems by binding
2228 `coding-system-for-read' and `coding-system-for-write'.
2230 The optional second argument OUTPUT-BUFFER, if non-nil,
2231 says to put the output in some other buffer.
2232 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2233 If OUTPUT-BUFFER is not a buffer and not nil,
2234 insert output in current buffer. (This cannot be done asynchronously.)
2235 In either case, the buffer is first erased, and the output is
2236 inserted after point (leaving mark after it).
2238 If the command terminates without error, but generates output,
2239 and you did not specify \"insert it in the current buffer\",
2240 the output can be displayed in the echo area or in its buffer.
2241 If the output is short enough to display in the echo area
2242 \(determined by the variable `max-mini-window-height' if
2243 `resize-mini-windows' is non-nil), it is shown there.
2244 Otherwise,the buffer containing the output is displayed.
2246 If there is output and an error, and you did not specify \"insert it
2247 in the current buffer\", a message about the error goes at the end
2248 of the output.
2250 If there is no output, or if output is inserted in the current buffer,
2251 then `*Shell Command Output*' is deleted.
2253 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2254 or buffer name to which to direct the command's standard error output.
2255 If it is nil, error output is mingled with regular output.
2256 In an interactive call, the variable `shell-command-default-error-buffer'
2257 specifies the value of ERROR-BUFFER.
2259 In Elisp, you will often be better served by calling `call-process' or
2260 `start-process' directly, since it offers more control and does not impose
2261 the use of a shell (with its need to quote arguments)."
2263 (interactive
2264 (list
2265 (read-shell-command "Shell command: " nil nil
2266 (let ((filename
2267 (cond
2268 (buffer-file-name)
2269 ((eq major-mode 'dired-mode)
2270 (dired-get-filename nil t)))))
2271 (and filename (file-relative-name filename))))
2272 current-prefix-arg
2273 shell-command-default-error-buffer))
2274 ;; Look for a handler in case default-directory is a remote file name.
2275 (let ((handler
2276 (find-file-name-handler (directory-file-name default-directory)
2277 'shell-command)))
2278 (if handler
2279 (funcall handler 'shell-command command output-buffer error-buffer)
2280 (if (and output-buffer
2281 (not (or (bufferp output-buffer) (stringp output-buffer))))
2282 ;; Output goes in current buffer.
2283 (let ((error-file
2284 (if error-buffer
2285 (make-temp-file
2286 (expand-file-name "scor"
2287 (or small-temporary-file-directory
2288 temporary-file-directory)))
2289 nil)))
2290 (barf-if-buffer-read-only)
2291 (push-mark nil t)
2292 ;; We do not use -f for csh; we will not support broken use of
2293 ;; .cshrcs. Even the BSD csh manual says to use
2294 ;; "if ($?prompt) exit" before things which are not useful
2295 ;; non-interactively. Besides, if someone wants their other
2296 ;; aliases for shell commands then they can still have them.
2297 (call-process shell-file-name nil
2298 (if error-file
2299 (list t error-file)
2301 nil shell-command-switch command)
2302 (when (and error-file (file-exists-p error-file))
2303 (if (< 0 (nth 7 (file-attributes error-file)))
2304 (with-current-buffer (get-buffer-create error-buffer)
2305 (let ((pos-from-end (- (point-max) (point))))
2306 (or (bobp)
2307 (insert "\f\n"))
2308 ;; Do no formatting while reading error file,
2309 ;; because that can run a shell command, and we
2310 ;; don't want that to cause an infinite recursion.
2311 (format-insert-file error-file nil)
2312 ;; Put point after the inserted errors.
2313 (goto-char (- (point-max) pos-from-end)))
2314 (display-buffer (current-buffer))))
2315 (delete-file error-file))
2316 ;; This is like exchange-point-and-mark, but doesn't
2317 ;; activate the mark. It is cleaner to avoid activation,
2318 ;; even though the command loop would deactivate the mark
2319 ;; because we inserted text.
2320 (goto-char (prog1 (mark t)
2321 (set-marker (mark-marker) (point)
2322 (current-buffer)))))
2323 ;; Output goes in a separate buffer.
2324 ;; Preserve the match data in case called from a program.
2325 (save-match-data
2326 (if (string-match "[ \t]*&[ \t]*\\'" command)
2327 ;; Command ending with ampersand means asynchronous.
2328 (let ((buffer (get-buffer-create
2329 (or output-buffer "*Async Shell Command*")))
2330 (directory default-directory)
2331 proc)
2332 ;; Remove the ampersand.
2333 (setq command (substring command 0 (match-beginning 0)))
2334 ;; If will kill a process, query first.
2335 (setq proc (get-buffer-process buffer))
2336 (if proc
2337 (if (yes-or-no-p "A command is running. Kill it? ")
2338 (kill-process proc)
2339 (error "Shell command in progress")))
2340 (with-current-buffer buffer
2341 (setq buffer-read-only nil)
2342 ;; Setting buffer-read-only to nil doesn't suffice
2343 ;; if some text has a non-nil read-only property,
2344 ;; which comint sometimes adds for prompts.
2345 (let ((inhibit-read-only t))
2346 (erase-buffer))
2347 (display-buffer buffer)
2348 (setq default-directory directory)
2349 (setq proc (start-process "Shell" buffer shell-file-name
2350 shell-command-switch command))
2351 (setq mode-line-process '(":%s"))
2352 (require 'shell) (shell-mode)
2353 (set-process-sentinel proc 'shell-command-sentinel)
2354 ;; Use the comint filter for proper handling of carriage motion
2355 ;; (see `comint-inhibit-carriage-motion'),.
2356 (set-process-filter proc 'comint-output-filter)
2358 ;; Otherwise, command is executed synchronously.
2359 (shell-command-on-region (point) (point) command
2360 output-buffer nil error-buffer)))))))
2362 (defun display-message-or-buffer (message
2363 &optional buffer-name not-this-window frame)
2364 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2365 MESSAGE may be either a string or a buffer.
2367 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2368 the maximum height of the echo area, as defined by `max-mini-window-height'
2369 if `resize-mini-windows' is non-nil.
2371 Returns either the string shown in the echo area, or when a pop-up
2372 buffer is used, the window used to display it.
2374 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2375 name of the buffer used to display it in the case where a pop-up buffer
2376 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2377 string and it is displayed in the echo area, it is not specified whether
2378 the contents are inserted into the buffer anyway.
2380 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2381 and only used if a buffer is displayed."
2382 (cond ((and (stringp message) (not (string-match "\n" message)))
2383 ;; Trivial case where we can use the echo area
2384 (message "%s" message))
2385 ((and (stringp message)
2386 (= (string-match "\n" message) (1- (length message))))
2387 ;; Trivial case where we can just remove single trailing newline
2388 (message "%s" (substring message 0 (1- (length message)))))
2390 ;; General case
2391 (with-current-buffer
2392 (if (bufferp message)
2393 message
2394 (get-buffer-create (or buffer-name "*Message*")))
2396 (unless (bufferp message)
2397 (erase-buffer)
2398 (insert message))
2400 (let ((lines
2401 (if (= (buffer-size) 0)
2403 (count-screen-lines nil nil nil (minibuffer-window)))))
2404 (cond ((= lines 0))
2405 ((and (or (<= lines 1)
2406 (<= lines
2407 (if resize-mini-windows
2408 (cond ((floatp max-mini-window-height)
2409 (* (frame-height)
2410 max-mini-window-height))
2411 ((integerp max-mini-window-height)
2412 max-mini-window-height)
2415 1)))
2416 ;; Don't use the echo area if the output buffer is
2417 ;; already dispayed in the selected frame.
2418 (not (get-buffer-window (current-buffer))))
2419 ;; Echo area
2420 (goto-char (point-max))
2421 (when (bolp)
2422 (backward-char 1))
2423 (message "%s" (buffer-substring (point-min) (point))))
2425 ;; Buffer
2426 (goto-char (point-min))
2427 (display-buffer (current-buffer)
2428 not-this-window frame))))))))
2431 ;; We have a sentinel to prevent insertion of a termination message
2432 ;; in the buffer itself.
2433 (defun shell-command-sentinel (process signal)
2434 (if (memq (process-status process) '(exit signal))
2435 (message "%s: %s."
2436 (car (cdr (cdr (process-command process))))
2437 (substring signal 0 -1))))
2439 (defun shell-command-on-region (start end command
2440 &optional output-buffer replace
2441 error-buffer display-error-buffer)
2442 "Execute string COMMAND in inferior shell with region as input.
2443 Normally display output (if any) in temp buffer `*Shell Command Output*';
2444 Prefix arg means replace the region with it. Return the exit code of
2445 COMMAND.
2447 To specify a coding system for converting non-ASCII characters
2448 in the input and output to the shell command, use \\[universal-coding-system-argument]
2449 before this command. By default, the input (from the current buffer)
2450 is encoded in the same coding system that will be used to save the file,
2451 `buffer-file-coding-system'. If the output is going to replace the region,
2452 then it is decoded from that same coding system.
2454 The noninteractive arguments are START, END, COMMAND,
2455 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2456 Noninteractive callers can specify coding systems by binding
2457 `coding-system-for-read' and `coding-system-for-write'.
2459 If the command generates output, the output may be displayed
2460 in the echo area or in a buffer.
2461 If the output is short enough to display in the echo area
2462 \(determined by the variable `max-mini-window-height' if
2463 `resize-mini-windows' is non-nil), it is shown there. Otherwise
2464 it is displayed in the buffer `*Shell Command Output*'. The output
2465 is available in that buffer in both cases.
2467 If there is output and an error, a message about the error
2468 appears at the end of the output.
2470 If there is no output, or if output is inserted in the current buffer,
2471 then `*Shell Command Output*' is deleted.
2473 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2474 that says to put the output in some other buffer.
2475 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2476 If OUTPUT-BUFFER is not a buffer and not nil,
2477 insert output in the current buffer.
2478 In either case, the output is inserted after point (leaving mark after it).
2480 If REPLACE, the optional fifth argument, is non-nil, that means insert
2481 the output in place of text from START to END, putting point and mark
2482 around it.
2484 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2485 or buffer name to which to direct the command's standard error output.
2486 If it is nil, error output is mingled with regular output.
2487 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2488 were any errors. (This is always t, interactively.)
2489 In an interactive call, the variable `shell-command-default-error-buffer'
2490 specifies the value of ERROR-BUFFER."
2491 (interactive (let (string)
2492 (unless (mark)
2493 (error "The mark is not set now, so there is no region"))
2494 ;; Do this before calling region-beginning
2495 ;; and region-end, in case subprocess output
2496 ;; relocates them while we are in the minibuffer.
2497 (setq string (read-shell-command "Shell command on region: "))
2498 ;; call-interactively recognizes region-beginning and
2499 ;; region-end specially, leaving them in the history.
2500 (list (region-beginning) (region-end)
2501 string
2502 current-prefix-arg
2503 current-prefix-arg
2504 shell-command-default-error-buffer
2505 t)))
2506 (let ((error-file
2507 (if error-buffer
2508 (make-temp-file
2509 (expand-file-name "scor"
2510 (or small-temporary-file-directory
2511 temporary-file-directory)))
2512 nil))
2513 exit-status)
2514 (if (or replace
2515 (and output-buffer
2516 (not (or (bufferp output-buffer) (stringp output-buffer)))))
2517 ;; Replace specified region with output from command.
2518 (let ((swap (and replace (< start end))))
2519 ;; Don't muck with mark unless REPLACE says we should.
2520 (goto-char start)
2521 (and replace (push-mark (point) 'nomsg))
2522 (setq exit-status
2523 (call-process-region start end shell-file-name t
2524 (if error-file
2525 (list t error-file)
2527 nil shell-command-switch command))
2528 ;; It is rude to delete a buffer which the command is not using.
2529 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2530 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2531 ;; (kill-buffer shell-buffer)))
2532 ;; Don't muck with mark unless REPLACE says we should.
2533 (and replace swap (exchange-point-and-mark)))
2534 ;; No prefix argument: put the output in a temp buffer,
2535 ;; replacing its entire contents.
2536 (let ((buffer (get-buffer-create
2537 (or output-buffer "*Shell Command Output*"))))
2538 (unwind-protect
2539 (if (eq buffer (current-buffer))
2540 ;; If the input is the same buffer as the output,
2541 ;; delete everything but the specified region,
2542 ;; then replace that region with the output.
2543 (progn (setq buffer-read-only nil)
2544 (delete-region (max start end) (point-max))
2545 (delete-region (point-min) (min start end))
2546 (setq exit-status
2547 (call-process-region (point-min) (point-max)
2548 shell-file-name t
2549 (if error-file
2550 (list t error-file)
2552 nil shell-command-switch
2553 command)))
2554 ;; Clear the output buffer, then run the command with
2555 ;; output there.
2556 (let ((directory default-directory))
2557 (with-current-buffer buffer
2558 (setq buffer-read-only nil)
2559 (if (not output-buffer)
2560 (setq default-directory directory))
2561 (erase-buffer)))
2562 (setq exit-status
2563 (call-process-region start end shell-file-name nil
2564 (if error-file
2565 (list buffer error-file)
2566 buffer)
2567 nil shell-command-switch command)))
2568 ;; Report the output.
2569 (with-current-buffer buffer
2570 (setq mode-line-process
2571 (cond ((null exit-status)
2572 " - Error")
2573 ((stringp exit-status)
2574 (format " - Signal [%s]" exit-status))
2575 ((not (equal 0 exit-status))
2576 (format " - Exit [%d]" exit-status)))))
2577 (if (with-current-buffer buffer (> (point-max) (point-min)))
2578 ;; There's some output, display it
2579 (display-message-or-buffer buffer)
2580 ;; No output; error?
2581 (let ((output
2582 (if (and error-file
2583 (< 0 (nth 7 (file-attributes error-file))))
2584 "some error output"
2585 "no output")))
2586 (cond ((null exit-status)
2587 (message "(Shell command failed with error)"))
2588 ((equal 0 exit-status)
2589 (message "(Shell command succeeded with %s)"
2590 output))
2591 ((stringp exit-status)
2592 (message "(Shell command killed by signal %s)"
2593 exit-status))
2595 (message "(Shell command failed with code %d and %s)"
2596 exit-status output))))
2597 ;; Don't kill: there might be useful info in the undo-log.
2598 ;; (kill-buffer buffer)
2599 ))))
2601 (when (and error-file (file-exists-p error-file))
2602 (if (< 0 (nth 7 (file-attributes error-file)))
2603 (with-current-buffer (get-buffer-create error-buffer)
2604 (let ((pos-from-end (- (point-max) (point))))
2605 (or (bobp)
2606 (insert "\f\n"))
2607 ;; Do no formatting while reading error file,
2608 ;; because that can run a shell command, and we
2609 ;; don't want that to cause an infinite recursion.
2610 (format-insert-file error-file nil)
2611 ;; Put point after the inserted errors.
2612 (goto-char (- (point-max) pos-from-end)))
2613 (and display-error-buffer
2614 (display-buffer (current-buffer)))))
2615 (delete-file error-file))
2616 exit-status))
2618 (defun shell-command-to-string (command)
2619 "Execute shell command COMMAND and return its output as a string."
2620 (with-output-to-string
2621 (with-current-buffer
2622 standard-output
2623 (call-process shell-file-name nil t nil shell-command-switch command))))
2625 (defun process-file (program &optional infile buffer display &rest args)
2626 "Process files synchronously in a separate process.
2627 Similar to `call-process', but may invoke a file handler based on
2628 `default-directory'. The current working directory of the
2629 subprocess is `default-directory'.
2631 File names in INFILE and BUFFER are handled normally, but file
2632 names in ARGS should be relative to `default-directory', as they
2633 are passed to the process verbatim. \(This is a difference to
2634 `call-process' which does not support file handlers for INFILE
2635 and BUFFER.\)
2637 Some file handlers might not support all variants, for example
2638 they might behave as if DISPLAY was nil, regardless of the actual
2639 value passed."
2640 (let ((fh (find-file-name-handler default-directory 'process-file))
2641 lc stderr-file)
2642 (unwind-protect
2643 (if fh (apply fh 'process-file program infile buffer display args)
2644 (when infile (setq lc (file-local-copy infile)))
2645 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
2646 (make-temp-file "emacs")))
2647 (prog1
2648 (apply 'call-process program
2649 (or lc infile)
2650 (if stderr-file (list (car buffer) stderr-file) buffer)
2651 display args)
2652 (when stderr-file (copy-file stderr-file (cadr buffer)))))
2653 (when stderr-file (delete-file stderr-file))
2654 (when lc (delete-file lc)))))
2656 (defvar process-file-side-effects t
2657 "Whether a call of `process-file' changes remote files.
2659 Per default, this variable is always set to `t', meaning that a
2660 call of `process-file' could potentially change any file on a
2661 remote host. When set to `nil', a file handler could optimize
2662 its behaviour with respect to remote file attributes caching.
2664 This variable should never be changed by `setq'. Instead of, it
2665 shall be set only by let-binding.")
2667 (defun start-file-process (name buffer program &rest program-args)
2668 "Start a program in a subprocess. Return the process object for it.
2670 Similar to `start-process', but may invoke a file handler based on
2671 `default-directory'. See Info node `(elisp)Magic File Names'.
2673 This handler ought to run PROGRAM, perhaps on the local host,
2674 perhaps on a remote host that corresponds to `default-directory'.
2675 In the latter case, the local part of `default-directory' becomes
2676 the working directory of the process.
2678 PROGRAM and PROGRAM-ARGS might be file names. They are not
2679 objects of file handler invocation. File handlers might not
2680 support pty association, if PROGRAM is nil."
2681 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
2682 (if fh (apply fh 'start-file-process name buffer program program-args)
2683 (apply 'start-process name buffer program program-args))))
2686 (defvar universal-argument-map
2687 (let ((map (make-sparse-keymap)))
2688 (define-key map [t] 'universal-argument-other-key)
2689 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2690 (define-key map [switch-frame] nil)
2691 (define-key map [?\C-u] 'universal-argument-more)
2692 (define-key map [?-] 'universal-argument-minus)
2693 (define-key map [?0] 'digit-argument)
2694 (define-key map [?1] 'digit-argument)
2695 (define-key map [?2] 'digit-argument)
2696 (define-key map [?3] 'digit-argument)
2697 (define-key map [?4] 'digit-argument)
2698 (define-key map [?5] 'digit-argument)
2699 (define-key map [?6] 'digit-argument)
2700 (define-key map [?7] 'digit-argument)
2701 (define-key map [?8] 'digit-argument)
2702 (define-key map [?9] 'digit-argument)
2703 (define-key map [kp-0] 'digit-argument)
2704 (define-key map [kp-1] 'digit-argument)
2705 (define-key map [kp-2] 'digit-argument)
2706 (define-key map [kp-3] 'digit-argument)
2707 (define-key map [kp-4] 'digit-argument)
2708 (define-key map [kp-5] 'digit-argument)
2709 (define-key map [kp-6] 'digit-argument)
2710 (define-key map [kp-7] 'digit-argument)
2711 (define-key map [kp-8] 'digit-argument)
2712 (define-key map [kp-9] 'digit-argument)
2713 (define-key map [kp-subtract] 'universal-argument-minus)
2714 map)
2715 "Keymap used while processing \\[universal-argument].")
2717 (defvar universal-argument-num-events nil
2718 "Number of argument-specifying events read by `universal-argument'.
2719 `universal-argument-other-key' uses this to discard those events
2720 from (this-command-keys), and reread only the final command.")
2722 (defvar overriding-map-is-bound nil
2723 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2725 (defvar saved-overriding-map nil
2726 "The saved value of `overriding-terminal-local-map'.
2727 That variable gets restored to this value on exiting \"universal
2728 argument mode\".")
2730 (defun ensure-overriding-map-is-bound ()
2731 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2732 (unless overriding-map-is-bound
2733 (setq saved-overriding-map overriding-terminal-local-map)
2734 (setq overriding-terminal-local-map universal-argument-map)
2735 (setq overriding-map-is-bound t)))
2737 (defun restore-overriding-map ()
2738 "Restore `overriding-terminal-local-map' to its saved value."
2739 (setq overriding-terminal-local-map saved-overriding-map)
2740 (setq overriding-map-is-bound nil))
2742 (defun universal-argument ()
2743 "Begin a numeric argument for the following command.
2744 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2745 \\[universal-argument] following the digits or minus sign ends the argument.
2746 \\[universal-argument] without digits or minus sign provides 4 as argument.
2747 Repeating \\[universal-argument] without digits or minus sign
2748 multiplies the argument by 4 each time.
2749 For some commands, just \\[universal-argument] by itself serves as a flag
2750 which is different in effect from any particular numeric argument.
2751 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2752 (interactive)
2753 (setq prefix-arg (list 4))
2754 (setq universal-argument-num-events (length (this-command-keys)))
2755 (ensure-overriding-map-is-bound))
2757 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2758 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2759 (defun universal-argument-more (arg)
2760 (interactive "P")
2761 (if (consp arg)
2762 (setq prefix-arg (list (* 4 (car arg))))
2763 (if (eq arg '-)
2764 (setq prefix-arg (list -4))
2765 (setq prefix-arg arg)
2766 (restore-overriding-map)))
2767 (setq universal-argument-num-events (length (this-command-keys))))
2769 (defun negative-argument (arg)
2770 "Begin a negative numeric argument for the next command.
2771 \\[universal-argument] following digits or minus sign ends the argument."
2772 (interactive "P")
2773 (cond ((integerp arg)
2774 (setq prefix-arg (- arg)))
2775 ((eq arg '-)
2776 (setq prefix-arg nil))
2778 (setq prefix-arg '-)))
2779 (setq universal-argument-num-events (length (this-command-keys)))
2780 (ensure-overriding-map-is-bound))
2782 (defun digit-argument (arg)
2783 "Part of the numeric argument for the next command.
2784 \\[universal-argument] following digits or minus sign ends the argument."
2785 (interactive "P")
2786 (let* ((char (if (integerp last-command-event)
2787 last-command-event
2788 (get last-command-event 'ascii-character)))
2789 (digit (- (logand char ?\177) ?0)))
2790 (cond ((integerp arg)
2791 (setq prefix-arg (+ (* arg 10)
2792 (if (< arg 0) (- digit) digit))))
2793 ((eq arg '-)
2794 ;; Treat -0 as just -, so that -01 will work.
2795 (setq prefix-arg (if (zerop digit) '- (- digit))))
2797 (setq prefix-arg digit))))
2798 (setq universal-argument-num-events (length (this-command-keys)))
2799 (ensure-overriding-map-is-bound))
2801 ;; For backward compatibility, minus with no modifiers is an ordinary
2802 ;; command if digits have already been entered.
2803 (defun universal-argument-minus (arg)
2804 (interactive "P")
2805 (if (integerp arg)
2806 (universal-argument-other-key arg)
2807 (negative-argument arg)))
2809 ;; Anything else terminates the argument and is left in the queue to be
2810 ;; executed as a command.
2811 (defun universal-argument-other-key (arg)
2812 (interactive "P")
2813 (setq prefix-arg arg)
2814 (let* ((key (this-command-keys))
2815 (keylist (listify-key-sequence key)))
2816 (setq unread-command-events
2817 (append (nthcdr universal-argument-num-events keylist)
2818 unread-command-events)))
2819 (reset-this-command-lengths)
2820 (restore-overriding-map))
2822 ;; This function is here rather than in subr.el because it uses CL.
2823 (defmacro with-wrapper-hook (var args &rest body)
2824 "Run BODY wrapped with the VAR hook.
2825 VAR is a special hook: its functions are called with a first argument
2826 which is the \"original\" code (the BODY), so the hook function can wrap
2827 the original function, or call it any number of times (including not calling
2828 it at all). This is similar to an `around' advice.
2829 VAR is normally a symbol (a variable) in which case it is treated like
2830 a hook, with a buffer-local and a global part. But it can also be an
2831 arbitrary expression.
2832 ARGS is a list of variables which will be passed as additional arguments
2833 to each function, after the initial argument, and which the first argument
2834 expects to receive when called."
2835 (declare (indent 2) (debug t))
2836 ;; We need those two gensyms because CL's lexical scoping is not available
2837 ;; for function arguments :-(
2838 (let ((funs (make-symbol "funs"))
2839 (global (make-symbol "global"))
2840 (argssym (make-symbol "args")))
2841 ;; Since the hook is a wrapper, the loop has to be done via
2842 ;; recursion: a given hook function will call its parameter in order to
2843 ;; continue looping.
2844 `(labels ((runrestofhook (,funs ,global ,argssym)
2845 ;; `funs' holds the functions left on the hook and `global'
2846 ;; holds the functions left on the global part of the hook
2847 ;; (in case the hook is local).
2848 (lexical-let ((funs ,funs)
2849 (global ,global))
2850 (if (consp funs)
2851 (if (eq t (car funs))
2852 (runrestofhook
2853 (append global (cdr funs)) nil ,argssym)
2854 (apply (car funs)
2855 (lambda (&rest ,argssym)
2856 (runrestofhook (cdr funs) global ,argssym))
2857 ,argssym))
2858 ;; Once there are no more functions on the hook, run
2859 ;; the original body.
2860 (apply (lambda ,args ,@body) ,argssym)))))
2861 (runrestofhook ,var
2862 ;; The global part of the hook, if any.
2863 ,(if (symbolp var)
2864 `(if (local-variable-p ',var)
2865 (default-value ',var)))
2866 (list ,@args)))))
2868 (defvar filter-buffer-substring-functions nil
2869 "Wrapper hook around `filter-buffer-substring'.
2870 The functions on this special hook are called with 4 arguments:
2871 NEXT-FUN BEG END DELETE
2872 NEXT-FUN is a function of 3 arguments (BEG END DELETE)
2873 that performs the default operation. The other 3 arguments are like
2874 the ones passed to `filter-buffer-substring'.")
2876 (defvar buffer-substring-filters nil
2877 "List of filter functions for `filter-buffer-substring'.
2878 Each function must accept a single argument, a string, and return
2879 a string. The buffer substring is passed to the first function
2880 in the list, and the return value of each function is passed to
2881 the next. The return value of the last function is used as the
2882 return value of `filter-buffer-substring'.
2884 If this variable is nil, no filtering is performed.")
2885 (make-obsolete-variable 'buffer-substring-filters
2886 'filter-buffer-substring-functions "24.1")
2888 (defun filter-buffer-substring (beg end &optional delete)
2889 "Return the buffer substring between BEG and END, after filtering.
2890 The filtering is performed by `filter-buffer-substring-functions'.
2892 If DELETE is non-nil, the text between BEG and END is deleted
2893 from the buffer.
2895 This function should be used instead of `buffer-substring',
2896 `buffer-substring-no-properties', or `delete-and-extract-region'
2897 when you want to allow filtering to take place. For example,
2898 major or minor modes can use `filter-buffer-substring-functions' to
2899 extract characters that are special to a buffer, and should not
2900 be copied into other buffers."
2901 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
2902 (cond
2903 ((or delete buffer-substring-filters)
2904 (save-excursion
2905 (goto-char beg)
2906 (let ((string (if delete (delete-and-extract-region beg end)
2907 (buffer-substring beg end))))
2908 (dolist (filter buffer-substring-filters)
2909 (setq string (funcall filter string)))
2910 string)))
2912 (buffer-substring beg end)))))
2915 ;;;; Window system cut and paste hooks.
2917 (defvar interprogram-cut-function nil
2918 "Function to call to make a killed region available to other programs.
2920 Most window systems provide some sort of facility for cutting and
2921 pasting text between the windows of different programs.
2922 This variable holds a function that Emacs calls whenever text
2923 is put in the kill ring, to make the new kill available to other
2924 programs.
2926 The function takes one argument, TEXT, which is a string containing
2927 the text which should be made available.")
2929 (defvar interprogram-paste-function nil
2930 "Function to call to get text cut from other programs.
2932 Most window systems provide some sort of facility for cutting and
2933 pasting text between the windows of different programs.
2934 This variable holds a function that Emacs calls to obtain
2935 text that other programs have provided for pasting.
2937 The function should be called with no arguments. If the function
2938 returns nil, then no other program has provided such text, and the top
2939 of the Emacs kill ring should be used. If the function returns a
2940 string, then the caller of the function \(usually `current-kill')
2941 should put this string in the kill ring as the latest kill.
2943 This function may also return a list of strings if the window
2944 system supports multiple selections. The first string will be
2945 used as the pasted text, but the other will be placed in the
2946 kill ring for easy access via `yank-pop'.
2948 Note that the function should return a string only if a program other
2949 than Emacs has provided a string for pasting; if Emacs provided the
2950 most recent string, the function should return nil. If it is
2951 difficult to tell whether Emacs or some other program provided the
2952 current string, it is probably good enough to return nil if the string
2953 is equal (according to `string=') to the last text Emacs provided.")
2957 ;;;; The kill ring data structure.
2959 (defvar kill-ring nil
2960 "List of killed text sequences.
2961 Since the kill ring is supposed to interact nicely with cut-and-paste
2962 facilities offered by window systems, use of this variable should
2963 interact nicely with `interprogram-cut-function' and
2964 `interprogram-paste-function'. The functions `kill-new',
2965 `kill-append', and `current-kill' are supposed to implement this
2966 interaction; you may want to use them instead of manipulating the kill
2967 ring directly.")
2969 (defcustom kill-ring-max 60
2970 "Maximum length of kill ring before oldest elements are thrown away."
2971 :type 'integer
2972 :group 'killing)
2974 (defvar kill-ring-yank-pointer nil
2975 "The tail of the kill ring whose car is the last thing yanked.")
2977 (defcustom save-interprogram-paste-before-kill nil
2978 "Save clipboard strings into kill ring before replacing them.
2979 When one selects something in another program to paste it into Emacs,
2980 but kills something in Emacs before actually pasting it,
2981 this selection is gone unless this variable is non-nil,
2982 in which case the other program's selection is saved in the `kill-ring'
2983 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
2984 :type 'boolean
2985 :group 'killing
2986 :version "23.2")
2988 (defcustom kill-do-not-save-duplicates nil
2989 "Do not add a new string to `kill-ring' when it is the same as the last one."
2990 :type 'boolean
2991 :group 'killing
2992 :version "23.2")
2994 (defun kill-new (string &optional replace yank-handler)
2995 "Make STRING the latest kill in the kill ring.
2996 Set `kill-ring-yank-pointer' to point to it.
2997 If `interprogram-cut-function' is non-nil, apply it to STRING.
2998 Optional second argument REPLACE non-nil means that STRING will replace
2999 the front of the kill ring, rather than being added to the list.
3001 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3002 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3003 STRING.
3005 When the yank handler has a non-nil PARAM element, the original STRING
3006 argument is not used by `insert-for-yank'. However, since Lisp code
3007 may access and use elements from the kill ring directly, the STRING
3008 argument should still be a \"useful\" string for such uses."
3009 (if (> (length string) 0)
3010 (if yank-handler
3011 (put-text-property 0 (length string)
3012 'yank-handler yank-handler string))
3013 (if yank-handler
3014 (signal 'args-out-of-range
3015 (list string "yank-handler specified for empty string"))))
3016 (unless (and kill-do-not-save-duplicates
3017 (equal string (car kill-ring)))
3018 (if (fboundp 'menu-bar-update-yank-menu)
3019 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
3020 (when save-interprogram-paste-before-kill
3021 (let ((interprogram-paste (and interprogram-paste-function
3022 (funcall interprogram-paste-function))))
3023 (when interprogram-paste
3024 (dolist (s (if (listp interprogram-paste)
3025 (nreverse interprogram-paste)
3026 (list interprogram-paste)))
3027 (unless (and kill-do-not-save-duplicates
3028 (equal s (car kill-ring)))
3029 (push s kill-ring))))))
3030 (unless (and kill-do-not-save-duplicates
3031 (equal string (car kill-ring)))
3032 (if (and replace kill-ring)
3033 (setcar kill-ring string)
3034 (push string kill-ring)
3035 (if (> (length kill-ring) kill-ring-max)
3036 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
3037 (setq kill-ring-yank-pointer kill-ring)
3038 (if interprogram-cut-function
3039 (funcall interprogram-cut-function string)))
3040 (set-advertised-calling-convention
3041 'kill-new '(string &optional replace) "23.3")
3043 (defun kill-append (string before-p &optional yank-handler)
3044 "Append STRING to the end of the latest kill in the kill ring.
3045 If BEFORE-P is non-nil, prepend STRING to the kill.
3046 If `interprogram-cut-function' is set, pass the resulting kill to it."
3047 (let* ((cur (car kill-ring)))
3048 (kill-new (if before-p (concat string cur) (concat cur string))
3049 (or (= (length cur) 0)
3050 (equal yank-handler (get-text-property 0 'yank-handler cur)))
3051 yank-handler)))
3052 (set-advertised-calling-convention 'kill-append '(string before-p) "23.3")
3054 (defcustom yank-pop-change-selection nil
3055 "If non-nil, rotating the kill ring changes the window system selection."
3056 :type 'boolean
3057 :group 'killing
3058 :version "23.1")
3060 (defun current-kill (n &optional do-not-move)
3061 "Rotate the yanking point by N places, and then return that kill.
3062 If N is zero, `interprogram-paste-function' is set, and calling
3063 it returns a string or list of strings, then that string (or
3064 list) is added to the front of the kill ring and the string (or
3065 first string in the list) is returned as the latest kill.
3067 If N is not zero, and if `yank-pop-change-selection' is
3068 non-nil, use `interprogram-cut-function' to transfer the
3069 kill at the new yank point into the window system selection.
3071 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3072 move the yanking point; just return the Nth kill forward."
3074 (let ((interprogram-paste (and (= n 0)
3075 interprogram-paste-function
3076 (funcall interprogram-paste-function))))
3077 (if interprogram-paste
3078 (progn
3079 ;; Disable the interprogram cut function when we add the new
3080 ;; text to the kill ring, so Emacs doesn't try to own the
3081 ;; selection, with identical text.
3082 (let ((interprogram-cut-function nil))
3083 (if (listp interprogram-paste)
3084 (mapc 'kill-new (nreverse interprogram-paste))
3085 (kill-new interprogram-paste)))
3086 (car kill-ring))
3087 (or kill-ring (error "Kill ring is empty"))
3088 (let ((ARGth-kill-element
3089 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3090 (length kill-ring))
3091 kill-ring)))
3092 (unless do-not-move
3093 (setq kill-ring-yank-pointer ARGth-kill-element)
3094 (when (and yank-pop-change-selection
3095 (> n 0)
3096 interprogram-cut-function)
3097 (funcall interprogram-cut-function (car ARGth-kill-element))))
3098 (car ARGth-kill-element)))))
3102 ;;;; Commands for manipulating the kill ring.
3104 (defcustom kill-read-only-ok nil
3105 "Non-nil means don't signal an error for killing read-only text."
3106 :type 'boolean
3107 :group 'killing)
3109 (put 'text-read-only 'error-conditions
3110 '(text-read-only buffer-read-only error))
3111 (put 'text-read-only 'error-message (purecopy "Text is read-only"))
3113 (defun kill-region (beg end &optional yank-handler)
3114 "Kill (\"cut\") text between point and mark.
3115 This deletes the text from the buffer and saves it in the kill ring.
3116 The command \\[yank] can retrieve it from there.
3117 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3119 If you want to append the killed region to the last killed text,
3120 use \\[append-next-kill] before \\[kill-region].
3122 If the buffer is read-only, Emacs will beep and refrain from deleting
3123 the text, but put the text in the kill ring anyway. This means that
3124 you can use the killing commands to copy text from a read-only buffer.
3126 Lisp programs should use this function for killing text.
3127 (To delete text, use `delete-region'.)
3128 Supply two arguments, character positions indicating the stretch of text
3129 to be killed.
3130 Any command that calls this function is a \"kill command\".
3131 If the previous command was also a kill command,
3132 the text killed this time appends to the text killed last time
3133 to make one entry in the kill ring."
3134 ;; Pass point first, then mark, because the order matters
3135 ;; when calling kill-append.
3136 (interactive (list (point) (mark)))
3137 (unless (and beg end)
3138 (error "The mark is not set now, so there is no region"))
3139 (condition-case nil
3140 (let ((string (filter-buffer-substring beg end t)))
3141 (when string ;STRING is nil if BEG = END
3142 ;; Add that string to the kill ring, one way or another.
3143 (if (eq last-command 'kill-region)
3144 (kill-append string (< end beg) yank-handler)
3145 (kill-new string nil yank-handler)))
3146 (when (or string (eq last-command 'kill-region))
3147 (setq this-command 'kill-region))
3148 nil)
3149 ((buffer-read-only text-read-only)
3150 ;; The code above failed because the buffer, or some of the characters
3151 ;; in the region, are read-only.
3152 ;; We should beep, in case the user just isn't aware of this.
3153 ;; However, there's no harm in putting
3154 ;; the region's text in the kill ring, anyway.
3155 (copy-region-as-kill beg end)
3156 ;; Set this-command now, so it will be set even if we get an error.
3157 (setq this-command 'kill-region)
3158 ;; This should barf, if appropriate, and give us the correct error.
3159 (if kill-read-only-ok
3160 (progn (message "Read only text copied to kill ring") nil)
3161 ;; Signal an error if the buffer is read-only.
3162 (barf-if-buffer-read-only)
3163 ;; If the buffer isn't read-only, the text is.
3164 (signal 'text-read-only (list (current-buffer)))))))
3165 (set-advertised-calling-convention 'kill-region '(beg end) "23.3")
3167 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3168 ;; to get two copies of the text when the user accidentally types M-w and
3169 ;; then corrects it with the intended C-w.
3170 (defun copy-region-as-kill (beg end)
3171 "Save the region as if killed, but don't kill it.
3172 In Transient Mark mode, deactivate the mark.
3173 If `interprogram-cut-function' is non-nil, also save the text for a window
3174 system cut and paste.
3176 This command's old key binding has been given to `kill-ring-save'."
3177 (interactive "r")
3178 (if (eq last-command 'kill-region)
3179 (kill-append (filter-buffer-substring beg end) (< end beg))
3180 (kill-new (filter-buffer-substring beg end)))
3181 (setq deactivate-mark t)
3182 nil)
3184 (defun kill-ring-save (beg end)
3185 "Save the region as if killed, but don't kill it.
3186 In Transient Mark mode, deactivate the mark.
3187 If `interprogram-cut-function' is non-nil, also save the text for a window
3188 system cut and paste.
3190 If you want to append the killed line to the last killed text,
3191 use \\[append-next-kill] before \\[kill-ring-save].
3193 This command is similar to `copy-region-as-kill', except that it gives
3194 visual feedback indicating the extent of the region being copied."
3195 (interactive "r")
3196 (copy-region-as-kill beg end)
3197 ;; This use of called-interactively-p is correct
3198 ;; because the code it controls just gives the user visual feedback.
3199 (if (called-interactively-p 'interactive)
3200 (let ((other-end (if (= (point) beg) end beg))
3201 (opoint (point))
3202 ;; Inhibit quitting so we can make a quit here
3203 ;; look like a C-g typed as a command.
3204 (inhibit-quit t))
3205 (if (pos-visible-in-window-p other-end (selected-window))
3206 ;; Swap point-and-mark quickly so as to show the region that
3207 ;; was selected. Don't do it if the region is highlighted.
3208 (unless (and (region-active-p)
3209 (face-background 'region))
3210 ;; Swap point and mark.
3211 (set-marker (mark-marker) (point) (current-buffer))
3212 (goto-char other-end)
3213 (sit-for blink-matching-delay)
3214 ;; Swap back.
3215 (set-marker (mark-marker) other-end (current-buffer))
3216 (goto-char opoint)
3217 ;; If user quit, deactivate the mark
3218 ;; as C-g would as a command.
3219 (and quit-flag mark-active
3220 (deactivate-mark)))
3221 (let* ((killed-text (current-kill 0))
3222 (message-len (min (length killed-text) 40)))
3223 (if (= (point) beg)
3224 ;; Don't say "killed"; that is misleading.
3225 (message "Saved text until \"%s\""
3226 (substring killed-text (- message-len)))
3227 (message "Saved text from \"%s\""
3228 (substring killed-text 0 message-len))))))))
3230 (defun append-next-kill (&optional interactive)
3231 "Cause following command, if it kills, to append to previous kill.
3232 The argument is used for internal purposes; do not supply one."
3233 (interactive "p")
3234 ;; We don't use (interactive-p), since that breaks kbd macros.
3235 (if interactive
3236 (progn
3237 (setq this-command 'kill-region)
3238 (message "If the next command is a kill, it will append"))
3239 (setq last-command 'kill-region)))
3241 ;; Yanking.
3243 ;; This is actually used in subr.el but defcustom does not work there.
3244 (defcustom yank-excluded-properties
3245 '(read-only invisible intangible field mouse-face help-echo local-map keymap
3246 yank-handler follow-link fontified)
3247 "Text properties to discard when yanking.
3248 The value should be a list of text properties to discard or t,
3249 which means to discard all text properties."
3250 :type '(choice (const :tag "All" t) (repeat symbol))
3251 :group 'killing
3252 :version "22.1")
3254 (defvar yank-window-start nil)
3255 (defvar yank-undo-function nil
3256 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3257 Function is called with two parameters, START and END corresponding to
3258 the value of the mark and point; it is guaranteed that START <= END.
3259 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3261 (defun yank-pop (&optional arg)
3262 "Replace just-yanked stretch of killed text with a different stretch.
3263 This command is allowed only immediately after a `yank' or a `yank-pop'.
3264 At such a time, the region contains a stretch of reinserted
3265 previously-killed text. `yank-pop' deletes that text and inserts in its
3266 place a different stretch of killed text.
3268 With no argument, the previous kill is inserted.
3269 With argument N, insert the Nth previous kill.
3270 If N is negative, this is a more recent kill.
3272 The sequence of kills wraps around, so that after the oldest one
3273 comes the newest one.
3275 When this command inserts killed text into the buffer, it honors
3276 `yank-excluded-properties' and `yank-handler' as described in the
3277 doc string for `insert-for-yank-1', which see."
3278 (interactive "*p")
3279 (if (not (eq last-command 'yank))
3280 (error "Previous command was not a yank"))
3281 (setq this-command 'yank)
3282 (unless arg (setq arg 1))
3283 (let ((inhibit-read-only t)
3284 (before (< (point) (mark t))))
3285 (if before
3286 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3287 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
3288 (setq yank-undo-function nil)
3289 (set-marker (mark-marker) (point) (current-buffer))
3290 (insert-for-yank (current-kill arg))
3291 ;; Set the window start back where it was in the yank command,
3292 ;; if possible.
3293 (set-window-start (selected-window) yank-window-start t)
3294 (if before
3295 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3296 ;; It is cleaner to avoid activation, even though the command
3297 ;; loop would deactivate the mark because we inserted text.
3298 (goto-char (prog1 (mark t)
3299 (set-marker (mark-marker) (point) (current-buffer))))))
3300 nil)
3302 (defun yank (&optional arg)
3303 "Reinsert (\"paste\") the last stretch of killed text.
3304 More precisely, reinsert the stretch of killed text most recently
3305 killed OR yanked. Put point at end, and set mark at beginning.
3306 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
3307 With argument N, reinsert the Nth most recently killed stretch of killed
3308 text.
3310 When this command inserts killed text into the buffer, it honors
3311 `yank-excluded-properties' and `yank-handler' as described in the
3312 doc string for `insert-for-yank-1', which see.
3314 See also the command `yank-pop' (\\[yank-pop])."
3315 (interactive "*P")
3316 (setq yank-window-start (window-start))
3317 ;; If we don't get all the way thru, make last-command indicate that
3318 ;; for the following command.
3319 (setq this-command t)
3320 (push-mark (point))
3321 (insert-for-yank (current-kill (cond
3322 ((listp arg) 0)
3323 ((eq arg '-) -2)
3324 (t (1- arg)))))
3325 (if (consp arg)
3326 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3327 ;; It is cleaner to avoid activation, even though the command
3328 ;; loop would deactivate the mark because we inserted text.
3329 (goto-char (prog1 (mark t)
3330 (set-marker (mark-marker) (point) (current-buffer)))))
3331 ;; If we do get all the way thru, make this-command indicate that.
3332 (if (eq this-command t)
3333 (setq this-command 'yank))
3334 nil)
3336 (defun rotate-yank-pointer (arg)
3337 "Rotate the yanking point in the kill ring.
3338 With ARG, rotate that many kills forward (or backward, if negative)."
3339 (interactive "p")
3340 (current-kill arg))
3342 ;; Some kill commands.
3344 ;; Internal subroutine of delete-char
3345 (defun kill-forward-chars (arg)
3346 (if (listp arg) (setq arg (car arg)))
3347 (if (eq arg '-) (setq arg -1))
3348 (kill-region (point) (+ (point) arg)))
3350 ;; Internal subroutine of backward-delete-char
3351 (defun kill-backward-chars (arg)
3352 (if (listp arg) (setq arg (car arg)))
3353 (if (eq arg '-) (setq arg -1))
3354 (kill-region (point) (- (point) arg)))
3356 (defcustom backward-delete-char-untabify-method 'untabify
3357 "The method for untabifying when deleting backward.
3358 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3359 `hungry' -- delete all whitespace, both tabs and spaces;
3360 `all' -- delete all whitespace, including tabs, spaces and newlines;
3361 nil -- just delete one character."
3362 :type '(choice (const untabify) (const hungry) (const all) (const nil))
3363 :version "20.3"
3364 :group 'killing)
3366 (defun backward-delete-char-untabify (arg &optional killp)
3367 "Delete characters backward, changing tabs into spaces.
3368 The exact behavior depends on `backward-delete-char-untabify-method'.
3369 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3370 Interactively, ARG is the prefix arg (default 1)
3371 and KILLP is t if a prefix arg was specified."
3372 (interactive "*p\nP")
3373 (when (eq backward-delete-char-untabify-method 'untabify)
3374 (let ((count arg))
3375 (save-excursion
3376 (while (and (> count 0) (not (bobp)))
3377 (if (= (preceding-char) ?\t)
3378 (let ((col (current-column)))
3379 (forward-char -1)
3380 (setq col (- col (current-column)))
3381 (insert-char ?\s col)
3382 (delete-char 1)))
3383 (forward-char -1)
3384 (setq count (1- count))))))
3385 (delete-backward-char
3386 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3387 ((eq backward-delete-char-untabify-method 'all)
3388 " \t\n\r"))))
3389 (if skip
3390 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
3391 (point)))))
3392 (+ arg (if (zerop wh) 0 (1- wh))))
3393 arg))
3394 killp))
3396 (defun zap-to-char (arg char)
3397 "Kill up to and including ARGth occurrence of CHAR.
3398 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3399 Goes backward if ARG is negative; error if CHAR not found."
3400 (interactive "p\ncZap to char: ")
3401 ;; Avoid "obsolete" warnings for translation-table-for-input.
3402 (with-no-warnings
3403 (if (char-table-p translation-table-for-input)
3404 (setq char (or (aref translation-table-for-input char) char))))
3405 (kill-region (point) (progn
3406 (search-forward (char-to-string char) nil nil arg)
3407 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3408 (point))))
3410 ;; kill-line and its subroutines.
3412 (defcustom kill-whole-line nil
3413 "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
3414 :type 'boolean
3415 :group 'killing)
3417 (defun kill-line (&optional arg)
3418 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3419 With prefix argument ARG, kill that many lines from point.
3420 Negative arguments kill lines backward.
3421 With zero argument, kills the text before point on the current line.
3423 When calling from a program, nil means \"no arg\",
3424 a number counts as a prefix arg.
3426 To kill a whole line, when point is not at the beginning, type \
3427 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3429 If `kill-whole-line' is non-nil, then this command kills the whole line
3430 including its terminating newline, when used at the beginning of a line
3431 with no argument. As a consequence, you can always kill a whole line
3432 by typing \\[move-beginning-of-line] \\[kill-line].
3434 If you want to append the killed line to the last killed text,
3435 use \\[append-next-kill] before \\[kill-line].
3437 If the buffer is read-only, Emacs will beep and refrain from deleting
3438 the line, but put the line in the kill ring anyway. This means that
3439 you can use this command to copy text from a read-only buffer.
3440 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3441 even beep.)"
3442 (interactive "P")
3443 (kill-region (point)
3444 ;; It is better to move point to the other end of the kill
3445 ;; before killing. That way, in a read-only buffer, point
3446 ;; moves across the text that is copied to the kill ring.
3447 ;; The choice has no effect on undo now that undo records
3448 ;; the value of point from before the command was run.
3449 (progn
3450 (if arg
3451 (forward-visible-line (prefix-numeric-value arg))
3452 (if (eobp)
3453 (signal 'end-of-buffer nil))
3454 (let ((end
3455 (save-excursion
3456 (end-of-visible-line) (point))))
3457 (if (or (save-excursion
3458 ;; If trailing whitespace is visible,
3459 ;; don't treat it as nothing.
3460 (unless show-trailing-whitespace
3461 (skip-chars-forward " \t" end))
3462 (= (point) end))
3463 (and kill-whole-line (bolp)))
3464 (forward-visible-line 1)
3465 (goto-char end))))
3466 (point))))
3468 (defun kill-whole-line (&optional arg)
3469 "Kill current line.
3470 With prefix ARG, kill that many lines starting from the current line.
3471 If ARG is negative, kill backward. Also kill the preceding newline.
3472 \(This is meant to make \\[repeat] work well with negative arguments.\)
3473 If ARG is zero, kill current line but exclude the trailing newline."
3474 (interactive "p")
3475 (or arg (setq arg 1))
3476 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3477 (signal 'end-of-buffer nil))
3478 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3479 (signal 'beginning-of-buffer nil))
3480 (unless (eq last-command 'kill-region)
3481 (kill-new "")
3482 (setq last-command 'kill-region))
3483 (cond ((zerop arg)
3484 ;; We need to kill in two steps, because the previous command
3485 ;; could have been a kill command, in which case the text
3486 ;; before point needs to be prepended to the current kill
3487 ;; ring entry and the text after point appended. Also, we
3488 ;; need to use save-excursion to avoid copying the same text
3489 ;; twice to the kill ring in read-only buffers.
3490 (save-excursion
3491 (kill-region (point) (progn (forward-visible-line 0) (point))))
3492 (kill-region (point) (progn (end-of-visible-line) (point))))
3493 ((< arg 0)
3494 (save-excursion
3495 (kill-region (point) (progn (end-of-visible-line) (point))))
3496 (kill-region (point)
3497 (progn (forward-visible-line (1+ arg))
3498 (unless (bobp) (backward-char))
3499 (point))))
3501 (save-excursion
3502 (kill-region (point) (progn (forward-visible-line 0) (point))))
3503 (kill-region (point)
3504 (progn (forward-visible-line arg) (point))))))
3506 (defun forward-visible-line (arg)
3507 "Move forward by ARG lines, ignoring currently invisible newlines only.
3508 If ARG is negative, move backward -ARG lines.
3509 If ARG is zero, move to the beginning of the current line."
3510 (condition-case nil
3511 (if (> arg 0)
3512 (progn
3513 (while (> arg 0)
3514 (or (zerop (forward-line 1))
3515 (signal 'end-of-buffer nil))
3516 ;; If the newline we just skipped is invisible,
3517 ;; don't count it.
3518 (let ((prop
3519 (get-char-property (1- (point)) 'invisible)))
3520 (if (if (eq buffer-invisibility-spec t)
3521 prop
3522 (or (memq prop buffer-invisibility-spec)
3523 (assq prop buffer-invisibility-spec)))
3524 (setq arg (1+ arg))))
3525 (setq arg (1- arg)))
3526 ;; If invisible text follows, and it is a number of complete lines,
3527 ;; skip it.
3528 (let ((opoint (point)))
3529 (while (and (not (eobp))
3530 (let ((prop
3531 (get-char-property (point) 'invisible)))
3532 (if (eq buffer-invisibility-spec t)
3533 prop
3534 (or (memq prop buffer-invisibility-spec)
3535 (assq prop buffer-invisibility-spec)))))
3536 (goto-char
3537 (if (get-text-property (point) 'invisible)
3538 (or (next-single-property-change (point) 'invisible)
3539 (point-max))
3540 (next-overlay-change (point)))))
3541 (unless (bolp)
3542 (goto-char opoint))))
3543 (let ((first t))
3544 (while (or first (<= arg 0))
3545 (if first
3546 (beginning-of-line)
3547 (or (zerop (forward-line -1))
3548 (signal 'beginning-of-buffer nil)))
3549 ;; If the newline we just moved to is invisible,
3550 ;; don't count it.
3551 (unless (bobp)
3552 (let ((prop
3553 (get-char-property (1- (point)) 'invisible)))
3554 (unless (if (eq buffer-invisibility-spec t)
3555 prop
3556 (or (memq prop buffer-invisibility-spec)
3557 (assq prop buffer-invisibility-spec)))
3558 (setq arg (1+ arg)))))
3559 (setq first nil))
3560 ;; If invisible text follows, and it is a number of complete lines,
3561 ;; skip it.
3562 (let ((opoint (point)))
3563 (while (and (not (bobp))
3564 (let ((prop
3565 (get-char-property (1- (point)) 'invisible)))
3566 (if (eq buffer-invisibility-spec t)
3567 prop
3568 (or (memq prop buffer-invisibility-spec)
3569 (assq prop buffer-invisibility-spec)))))
3570 (goto-char
3571 (if (get-text-property (1- (point)) 'invisible)
3572 (or (previous-single-property-change (point) 'invisible)
3573 (point-min))
3574 (previous-overlay-change (point)))))
3575 (unless (bolp)
3576 (goto-char opoint)))))
3577 ((beginning-of-buffer end-of-buffer)
3578 nil)))
3580 (defun end-of-visible-line ()
3581 "Move to end of current visible line."
3582 (end-of-line)
3583 ;; If the following character is currently invisible,
3584 ;; skip all characters with that same `invisible' property value,
3585 ;; then find the next newline.
3586 (while (and (not (eobp))
3587 (save-excursion
3588 (skip-chars-forward "^\n")
3589 (let ((prop
3590 (get-char-property (point) 'invisible)))
3591 (if (eq buffer-invisibility-spec t)
3592 prop
3593 (or (memq prop buffer-invisibility-spec)
3594 (assq prop buffer-invisibility-spec))))))
3595 (skip-chars-forward "^\n")
3596 (if (get-text-property (point) 'invisible)
3597 (goto-char (next-single-property-change (point) 'invisible))
3598 (goto-char (next-overlay-change (point))))
3599 (end-of-line)))
3601 (defun insert-buffer (buffer)
3602 "Insert after point the contents of BUFFER.
3603 Puts mark after the inserted text.
3604 BUFFER may be a buffer or a buffer name.
3606 This function is meant for the user to run interactively.
3607 Don't call it from programs: use `insert-buffer-substring' instead!"
3608 (interactive
3609 (list
3610 (progn
3611 (barf-if-buffer-read-only)
3612 (read-buffer "Insert buffer: "
3613 (if (eq (selected-window) (next-window (selected-window)))
3614 (other-buffer (current-buffer))
3615 (window-buffer (next-window (selected-window))))
3616 t))))
3617 (push-mark
3618 (save-excursion
3619 (insert-buffer-substring (get-buffer buffer))
3620 (point)))
3621 nil)
3623 (defun append-to-buffer (buffer start end)
3624 "Append to specified buffer the text of the region.
3625 It is inserted into that buffer before its point.
3627 When calling from a program, give three arguments:
3628 BUFFER (or buffer name), START and END.
3629 START and END specify the portion of the current buffer to be copied."
3630 (interactive
3631 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3632 (region-beginning) (region-end)))
3633 (let* ((oldbuf (current-buffer))
3634 (append-to (get-buffer-create buffer))
3635 (windows (get-buffer-window-list append-to t t))
3636 point)
3637 (save-excursion
3638 (with-current-buffer append-to
3639 (setq point (point))
3640 (barf-if-buffer-read-only)
3641 (insert-buffer-substring oldbuf start end)
3642 (dolist (window windows)
3643 (when (= (window-point window) point)
3644 (set-window-point window (point))))))))
3646 (defun prepend-to-buffer (buffer start end)
3647 "Prepend to specified buffer the text of the region.
3648 It is inserted into that buffer after its point.
3650 When calling from a program, give three arguments:
3651 BUFFER (or buffer name), START and END.
3652 START and END specify the portion of the current buffer to be copied."
3653 (interactive "BPrepend to buffer: \nr")
3654 (let ((oldbuf (current-buffer)))
3655 (with-current-buffer (get-buffer-create buffer)
3656 (barf-if-buffer-read-only)
3657 (save-excursion
3658 (insert-buffer-substring oldbuf start end)))))
3660 (defun copy-to-buffer (buffer start end)
3661 "Copy to specified buffer the text of the region.
3662 It is inserted into that buffer, replacing existing text there.
3664 When calling from a program, give three arguments:
3665 BUFFER (or buffer name), START and END.
3666 START and END specify the portion of the current buffer to be copied."
3667 (interactive "BCopy to buffer: \nr")
3668 (let ((oldbuf (current-buffer)))
3669 (with-current-buffer (get-buffer-create buffer)
3670 (barf-if-buffer-read-only)
3671 (erase-buffer)
3672 (save-excursion
3673 (insert-buffer-substring oldbuf start end)))))
3675 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3676 (put 'mark-inactive 'error-message (purecopy "The mark is not active now"))
3678 (defvar activate-mark-hook nil
3679 "Hook run when the mark becomes active.
3680 It is also run at the end of a command, if the mark is active and
3681 it is possible that the region may have changed.")
3683 (defvar deactivate-mark-hook nil
3684 "Hook run when the mark becomes inactive.")
3686 (defun mark (&optional force)
3687 "Return this buffer's mark value as integer, or nil if never set.
3689 In Transient Mark mode, this function signals an error if
3690 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3691 or the argument FORCE is non-nil, it disregards whether the mark
3692 is active, and returns an integer or nil in the usual way.
3694 If you are using this in an editing command, you are most likely making
3695 a mistake; see the documentation of `set-mark'."
3696 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3697 (marker-position (mark-marker))
3698 (signal 'mark-inactive nil)))
3700 (defsubst deactivate-mark (&optional force)
3701 "Deactivate the mark by setting `mark-active' to nil.
3702 Unless FORCE is non-nil, this function does nothing if Transient
3703 Mark mode is disabled.
3704 This function also runs `deactivate-mark-hook'."
3705 (when (or transient-mark-mode force)
3706 (when (and (if (eq select-active-regions 'only)
3707 (eq (car-safe transient-mark-mode) 'only)
3708 select-active-regions)
3709 (region-active-p)
3710 (display-selections-p))
3711 ;; The var `saved-region-selection', if non-nil, is the text in
3712 ;; the region prior to the last command modifying the buffer.
3713 ;; Set the selection to that, or to the current region.
3714 (cond (saved-region-selection
3715 (x-set-selection 'PRIMARY saved-region-selection)
3716 (setq saved-region-selection nil))
3717 ((/= (region-beginning) (region-end))
3718 (x-set-selection 'PRIMARY
3719 (buffer-substring-no-properties
3720 (region-beginning)
3721 (region-end))))))
3722 (if (and (null force)
3723 (or (eq transient-mark-mode 'lambda)
3724 (and (eq (car-safe transient-mark-mode) 'only)
3725 (null (cdr transient-mark-mode)))))
3726 ;; When deactivating a temporary region, don't change
3727 ;; `mark-active' or run `deactivate-mark-hook'.
3728 (setq transient-mark-mode nil)
3729 (if (eq (car-safe transient-mark-mode) 'only)
3730 (setq transient-mark-mode (cdr transient-mark-mode)))
3731 (setq mark-active nil)
3732 (run-hooks 'deactivate-mark-hook))))
3734 (defun activate-mark ()
3735 "Activate the mark."
3736 (when (mark t)
3737 (setq mark-active t)
3738 (unless transient-mark-mode
3739 (setq transient-mark-mode 'lambda))))
3741 (defun set-mark (pos)
3742 "Set this buffer's mark to POS. Don't use this function!
3743 That is to say, don't use this function unless you want
3744 the user to see that the mark has moved, and you want the previous
3745 mark position to be lost.
3747 Normally, when a new mark is set, the old one should go on the stack.
3748 This is why most applications should use `push-mark', not `set-mark'.
3750 Novice Emacs Lisp programmers often try to use the mark for the wrong
3751 purposes. The mark saves a location for the user's convenience.
3752 Most editing commands should not alter the mark.
3753 To remember a location for internal use in the Lisp program,
3754 store it in a Lisp variable. Example:
3756 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3758 (if pos
3759 (progn
3760 (setq mark-active t)
3761 (run-hooks 'activate-mark-hook)
3762 (set-marker (mark-marker) pos (current-buffer)))
3763 ;; Normally we never clear mark-active except in Transient Mark mode.
3764 ;; But when we actually clear out the mark value too, we must
3765 ;; clear mark-active in any mode.
3766 (deactivate-mark t)
3767 (set-marker (mark-marker) nil)))
3769 (defcustom use-empty-active-region nil
3770 "Whether \"region-aware\" commands should act on empty regions.
3771 If nil, region-aware commands treat empty regions as inactive.
3772 If non-nil, region-aware commands treat the region as active as
3773 long as the mark is active, even if the region is empty.
3775 Region-aware commands are those that act on the region if it is
3776 active and Transient Mark mode is enabled, and on the text near
3777 point otherwise."
3778 :type 'boolean
3779 :version "23.1"
3780 :group 'editing-basics)
3782 (defun use-region-p ()
3783 "Return t if the region is active and it is appropriate to act on it.
3784 This is used by commands that act specially on the region under
3785 Transient Mark mode.
3787 The return value is t if Transient Mark mode is enabled and the
3788 mark is active; furthermore, if `use-empty-active-region' is nil,
3789 the region must not be empty. Otherwise, the return value is nil.
3791 For some commands, it may be appropriate to ignore the value of
3792 `use-empty-active-region'; in that case, use `region-active-p'."
3793 (and (region-active-p)
3794 (or use-empty-active-region (> (region-end) (region-beginning)))))
3796 (defun region-active-p ()
3797 "Return t if Transient Mark mode is enabled and the mark is active.
3799 Some commands act specially on the region when Transient Mark
3800 mode is enabled. Usually, such commands should use
3801 `use-region-p' instead of this function, because `use-region-p'
3802 also checks the value of `use-empty-active-region'."
3803 (and transient-mark-mode mark-active))
3805 (defvar mark-ring nil
3806 "The list of former marks of the current buffer, most recent first.")
3807 (make-variable-buffer-local 'mark-ring)
3808 (put 'mark-ring 'permanent-local t)
3810 (defcustom mark-ring-max 16
3811 "Maximum size of mark ring. Start discarding off end if gets this big."
3812 :type 'integer
3813 :group 'editing-basics)
3815 (defvar global-mark-ring nil
3816 "The list of saved global marks, most recent first.")
3818 (defcustom global-mark-ring-max 16
3819 "Maximum size of global mark ring. \
3820 Start discarding off end if gets this big."
3821 :type 'integer
3822 :group 'editing-basics)
3824 (defun pop-to-mark-command ()
3825 "Jump to mark, and pop a new position for mark off the ring.
3826 \(Does not affect global mark ring\)."
3827 (interactive)
3828 (if (null (mark t))
3829 (error "No mark set in this buffer")
3830 (if (= (point) (mark t))
3831 (message "Mark popped"))
3832 (goto-char (mark t))
3833 (pop-mark)))
3835 (defun push-mark-command (arg &optional nomsg)
3836 "Set mark at where point is.
3837 If no prefix ARG and mark is already set there, just activate it.
3838 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3839 (interactive "P")
3840 (let ((mark (marker-position (mark-marker))))
3841 (if (or arg (null mark) (/= mark (point)))
3842 (push-mark nil nomsg t)
3843 (setq mark-active t)
3844 (run-hooks 'activate-mark-hook)
3845 (unless nomsg
3846 (message "Mark activated")))))
3848 (defcustom set-mark-command-repeat-pop nil
3849 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3850 That means that C-u \\[set-mark-command] \\[set-mark-command]
3851 will pop the mark twice, and
3852 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3853 will pop the mark three times.
3855 A value of nil means \\[set-mark-command]'s behavior does not change
3856 after C-u \\[set-mark-command]."
3857 :type 'boolean
3858 :group 'editing-basics)
3860 (defcustom set-mark-default-inactive nil
3861 "If non-nil, setting the mark does not activate it.
3862 This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
3863 behave the same whether or not `transient-mark-mode' is enabled."
3864 :type 'boolean
3865 :group 'editing-basics
3866 :version "23.1")
3868 (defun set-mark-command (arg)
3869 "Set the mark where point is, or jump to the mark.
3870 Setting the mark also alters the region, which is the text
3871 between point and mark; this is the closest equivalent in
3872 Emacs to what some editors call the \"selection\".
3874 With no prefix argument, set the mark at point, and push the
3875 old mark position on local mark ring. Also push the old mark on
3876 global mark ring, if the previous mark was set in another buffer.
3878 When Transient Mark Mode is off, immediately repeating this
3879 command activates `transient-mark-mode' temporarily.
3881 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3882 jump to the mark, and set the mark from
3883 position popped off the local mark ring \(this does not affect the global
3884 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3885 mark ring \(see `pop-global-mark'\).
3887 If `set-mark-command-repeat-pop' is non-nil, repeating
3888 the \\[set-mark-command] command with no prefix argument pops the next position
3889 off the local (or global) mark ring and jumps there.
3891 With \\[universal-argument] \\[universal-argument] as prefix
3892 argument, unconditionally set mark where point is, even if
3893 `set-mark-command-repeat-pop' is non-nil.
3895 Novice Emacs Lisp programmers often try to use the mark for the wrong
3896 purposes. See the documentation of `set-mark' for more information."
3897 (interactive "P")
3898 (cond ((eq transient-mark-mode 'lambda)
3899 (setq transient-mark-mode nil))
3900 ((eq (car-safe transient-mark-mode) 'only)
3901 (deactivate-mark)))
3902 (cond
3903 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3904 (push-mark-command nil))
3905 ((not (eq this-command 'set-mark-command))
3906 (if arg
3907 (pop-to-mark-command)
3908 (push-mark-command t)))
3909 ((and set-mark-command-repeat-pop
3910 (eq last-command 'pop-to-mark-command))
3911 (setq this-command 'pop-to-mark-command)
3912 (pop-to-mark-command))
3913 ((and set-mark-command-repeat-pop
3914 (eq last-command 'pop-global-mark)
3915 (not arg))
3916 (setq this-command 'pop-global-mark)
3917 (pop-global-mark))
3918 (arg
3919 (setq this-command 'pop-to-mark-command)
3920 (pop-to-mark-command))
3921 ((eq last-command 'set-mark-command)
3922 (if (region-active-p)
3923 (progn
3924 (deactivate-mark)
3925 (message "Mark deactivated"))
3926 (activate-mark)
3927 (message "Mark activated")))
3929 (push-mark-command nil)
3930 (if set-mark-default-inactive (deactivate-mark)))))
3932 (defun push-mark (&optional location nomsg activate)
3933 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3934 If the last global mark pushed was not in the current buffer,
3935 also push LOCATION on the global mark ring.
3936 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3938 Novice Emacs Lisp programmers often try to use the mark for the wrong
3939 purposes. See the documentation of `set-mark' for more information.
3941 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
3942 (unless (null (mark t))
3943 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3944 (when (> (length mark-ring) mark-ring-max)
3945 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3946 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3947 (set-marker (mark-marker) (or location (point)) (current-buffer))
3948 ;; Now push the mark on the global mark ring.
3949 (if (and global-mark-ring
3950 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3951 ;; The last global mark pushed was in this same buffer.
3952 ;; Don't push another one.
3954 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3955 (when (> (length global-mark-ring) global-mark-ring-max)
3956 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3957 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3958 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3959 (message "Mark set"))
3960 (if (or activate (not transient-mark-mode))
3961 (set-mark (mark t)))
3962 nil)
3964 (defun pop-mark ()
3965 "Pop off mark ring into the buffer's actual mark.
3966 Does not set point. Does nothing if mark ring is empty."
3967 (when mark-ring
3968 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3969 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3970 (move-marker (car mark-ring) nil)
3971 (if (null (mark t)) (ding))
3972 (setq mark-ring (cdr mark-ring)))
3973 (deactivate-mark))
3975 (define-obsolete-function-alias
3976 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
3977 (defun exchange-point-and-mark (&optional arg)
3978 "Put the mark where point is now, and point where the mark is now.
3979 This command works even when the mark is not active,
3980 and it reactivates the mark.
3982 If Transient Mark mode is on, a prefix ARG deactivates the mark
3983 if it is active, and otherwise avoids reactivating it. If
3984 Transient Mark mode is off, a prefix ARG enables Transient Mark
3985 mode temporarily."
3986 (interactive "P")
3987 (let ((omark (mark t))
3988 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
3989 (if (null omark)
3990 (error "No mark set in this buffer"))
3991 (deactivate-mark)
3992 (set-mark (point))
3993 (goto-char omark)
3994 (if set-mark-default-inactive (deactivate-mark))
3995 (cond (temp-highlight
3996 (setq transient-mark-mode (cons 'only transient-mark-mode)))
3997 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
3998 (not (or arg (region-active-p))))
3999 (deactivate-mark))
4000 (t (activate-mark)))
4001 nil))
4003 (defcustom shift-select-mode t
4004 "When non-nil, shifted motion keys activate the mark momentarily.
4006 While the mark is activated in this way, any shift-translated point
4007 motion key extends the region, and if Transient Mark mode was off, it
4008 is temporarily turned on. Furthermore, the mark will be deactivated
4009 by any subsequent point motion key that was not shift-translated, or
4010 by any action that normally deactivates the mark in Transient Mark mode.
4012 See `this-command-keys-shift-translated' for the meaning of
4013 shift-translation."
4014 :type 'boolean
4015 :group 'editing-basics)
4017 (defun handle-shift-selection ()
4018 "Activate/deactivate mark depending on invocation thru shift translation.
4019 This function is called by `call-interactively' when a command
4020 with a `^' character in its `interactive' spec is invoked, before
4021 running the command itself.
4023 If `shift-select-mode' is enabled and the command was invoked
4024 through shift translation, set the mark and activate the region
4025 temporarily, unless it was already set in this way. See
4026 `this-command-keys-shift-translated' for the meaning of shift
4027 translation.
4029 Otherwise, if the region has been activated temporarily,
4030 deactivate it, and restore the variable `transient-mark-mode' to
4031 its earlier value."
4032 (cond ((and shift-select-mode this-command-keys-shift-translated)
4033 (unless (and mark-active
4034 (eq (car-safe transient-mark-mode) 'only))
4035 (setq transient-mark-mode
4036 (cons 'only
4037 (unless (eq transient-mark-mode 'lambda)
4038 transient-mark-mode)))
4039 (push-mark nil nil t)))
4040 ((eq (car-safe transient-mark-mode) 'only)
4041 (setq transient-mark-mode (cdr transient-mark-mode))
4042 (deactivate-mark))))
4044 (define-minor-mode transient-mark-mode
4045 "Toggle Transient Mark mode.
4046 With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
4048 In Transient Mark mode, when the mark is active, the region is highlighted.
4049 Changing the buffer \"deactivates\" the mark.
4050 So do certain other operations that set the mark
4051 but whose main purpose is something else--for example,
4052 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4054 You can also deactivate the mark by typing \\[keyboard-quit] or
4055 \\[keyboard-escape-quit].
4057 Many commands change their behavior when Transient Mark mode is in effect
4058 and the mark is active, by acting on the region instead of their usual
4059 default part of the buffer's text. Examples of such commands include
4060 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
4061 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4062 Invoke \\[apropos-documentation] and type \"transient\" or
4063 \"mark.*active\" at the prompt, to see the documentation of
4064 commands which are sensitive to the Transient Mark mode."
4065 :global t
4066 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4067 :variable transient-mark-mode)
4069 (defvar widen-automatically t
4070 "Non-nil means it is ok for commands to call `widen' when they want to.
4071 Some commands will do this in order to go to positions outside
4072 the current accessible part of the buffer.
4074 If `widen-automatically' is nil, these commands will do something else
4075 as a fallback, and won't change the buffer bounds.")
4077 (defvar non-essential nil
4078 "Whether the currently executing code is performing an essential task.
4079 This variable should be non-nil only when running code which should not
4080 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4081 user for a password when we are simply scanning a set of files in the
4082 background or displaying possible completions before the user even asked
4083 for it.")
4085 (defun pop-global-mark ()
4086 "Pop off global mark ring and jump to the top location."
4087 (interactive)
4088 ;; Pop entries which refer to non-existent buffers.
4089 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4090 (setq global-mark-ring (cdr global-mark-ring)))
4091 (or global-mark-ring
4092 (error "No global mark set"))
4093 (let* ((marker (car global-mark-ring))
4094 (buffer (marker-buffer marker))
4095 (position (marker-position marker)))
4096 (setq global-mark-ring (nconc (cdr global-mark-ring)
4097 (list (car global-mark-ring))))
4098 (set-buffer buffer)
4099 (or (and (>= position (point-min))
4100 (<= position (point-max)))
4101 (if widen-automatically
4102 (widen)
4103 (error "Global mark position is outside accessible part of buffer")))
4104 (goto-char position)
4105 (switch-to-buffer buffer)))
4107 (defcustom next-line-add-newlines nil
4108 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4109 :type 'boolean
4110 :version "21.1"
4111 :group 'editing-basics)
4113 (defun next-line (&optional arg try-vscroll)
4114 "Move cursor vertically down ARG lines.
4115 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4116 If there is no character in the target line exactly under the current column,
4117 the cursor is positioned after the character in that line which spans this
4118 column, or at the end of the line if it is not long enough.
4119 If there is no line in the buffer after this one, behavior depends on the
4120 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4121 to create a line, and moves the cursor to that line. Otherwise it moves the
4122 cursor to the end of the buffer.
4124 If the variable `line-move-visual' is non-nil, this command moves
4125 by display lines. Otherwise, it moves by buffer lines, without
4126 taking variable-width characters or continued lines into account.
4128 The command \\[set-goal-column] can be used to create
4129 a semipermanent goal column for this command.
4130 Then instead of trying to move exactly vertically (or as close as possible),
4131 this command moves to the specified goal column (or as close as possible).
4132 The goal column is stored in the variable `goal-column', which is nil
4133 when there is no goal column.
4135 If you are thinking of using this in a Lisp program, consider
4136 using `forward-line' instead. It is usually easier to use
4137 and more reliable (no dependence on goal column, etc.)."
4138 (interactive "^p\np")
4139 (or arg (setq arg 1))
4140 (if (and next-line-add-newlines (= arg 1))
4141 (if (save-excursion (end-of-line) (eobp))
4142 ;; When adding a newline, don't expand an abbrev.
4143 (let ((abbrev-mode nil))
4144 (end-of-line)
4145 (insert (if use-hard-newlines hard-newline "\n")))
4146 (line-move arg nil nil try-vscroll))
4147 (if (called-interactively-p 'interactive)
4148 (condition-case err
4149 (line-move arg nil nil try-vscroll)
4150 ((beginning-of-buffer end-of-buffer)
4151 (signal (car err) (cdr err))))
4152 (line-move arg nil nil try-vscroll)))
4153 nil)
4155 (defun previous-line (&optional arg try-vscroll)
4156 "Move cursor vertically up ARG lines.
4157 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4158 If there is no character in the target line exactly over the current column,
4159 the cursor is positioned after the character in that line which spans this
4160 column, or at the end of the line if it is not long enough.
4162 If the variable `line-move-visual' is non-nil, this command moves
4163 by display lines. Otherwise, it moves by buffer lines, without
4164 taking variable-width characters or continued lines into account.
4166 The command \\[set-goal-column] can be used to create
4167 a semipermanent goal column for this command.
4168 Then instead of trying to move exactly vertically (or as close as possible),
4169 this command moves to the specified goal column (or as close as possible).
4170 The goal column is stored in the variable `goal-column', which is nil
4171 when there is no goal column.
4173 If you are thinking of using this in a Lisp program, consider using
4174 `forward-line' with a negative argument instead. It is usually easier
4175 to use and more reliable (no dependence on goal column, etc.)."
4176 (interactive "^p\np")
4177 (or arg (setq arg 1))
4178 (if (called-interactively-p 'interactive)
4179 (condition-case err
4180 (line-move (- arg) nil nil try-vscroll)
4181 ((beginning-of-buffer end-of-buffer)
4182 (signal (car err) (cdr err))))
4183 (line-move (- arg) nil nil try-vscroll))
4184 nil)
4186 (defcustom track-eol nil
4187 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4188 This means moving to the end of each line moved onto.
4189 The beginning of a blank line does not count as the end of a line.
4190 This has no effect when `line-move-visual' is non-nil."
4191 :type 'boolean
4192 :group 'editing-basics)
4194 (defcustom goal-column nil
4195 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
4196 :type '(choice integer
4197 (const :tag "None" nil))
4198 :group 'editing-basics)
4199 (make-variable-buffer-local 'goal-column)
4201 (defvar temporary-goal-column 0
4202 "Current goal column for vertical motion.
4203 It is the column where point was at the start of the current run
4204 of vertical motion commands.
4206 When moving by visual lines via `line-move-visual', it is a cons
4207 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4208 divided by the default column width, and HSCROLL is the number of
4209 columns by which window is scrolled from left margin.
4211 When the `track-eol' feature is doing its job, the value is
4212 `most-positive-fixnum'.")
4214 (defcustom line-move-ignore-invisible t
4215 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
4216 Outline mode sets this."
4217 :type 'boolean
4218 :group 'editing-basics)
4220 (defcustom line-move-visual t
4221 "When non-nil, `line-move' moves point by visual lines.
4222 This movement is based on where the cursor is displayed on the
4223 screen, instead of relying on buffer contents alone. It takes
4224 into account variable-width characters and line continuation.
4225 If nil, `line-move' moves point by logical lines."
4226 :type 'boolean
4227 :group 'editing-basics
4228 :version "23.1")
4230 ;; Returns non-nil if partial move was done.
4231 (defun line-move-partial (arg noerror to-end)
4232 (if (< arg 0)
4233 ;; Move backward (up).
4234 ;; If already vscrolled, reduce vscroll
4235 (let ((vs (window-vscroll nil t)))
4236 (when (> vs (frame-char-height))
4237 (set-window-vscroll nil (- vs (frame-char-height)) t)))
4239 ;; Move forward (down).
4240 (let* ((lh (window-line-height -1))
4241 (vpos (nth 1 lh))
4242 (ypos (nth 2 lh))
4243 (rbot (nth 3 lh))
4244 py vs)
4245 (when (or (null lh)
4246 (>= rbot (frame-char-height))
4247 (<= ypos (- (frame-char-height))))
4248 (unless lh
4249 (let ((wend (pos-visible-in-window-p t nil t)))
4250 (setq rbot (nth 3 wend)
4251 vpos (nth 5 wend))))
4252 (cond
4253 ;; If last line of window is fully visible, move forward.
4254 ((or (null rbot) (= rbot 0))
4255 nil)
4256 ;; If cursor is not in the bottom scroll margin, move forward.
4257 ((and (> vpos 0)
4258 (< (setq py
4259 (or (nth 1 (window-line-height))
4260 (let ((ppos (posn-at-point)))
4261 (cdr (or (posn-actual-col-row ppos)
4262 (posn-col-row ppos))))))
4263 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
4264 nil)
4265 ;; When already vscrolled, we vscroll some more if we can,
4266 ;; or clear vscroll and move forward at end of tall image.
4267 ((> (setq vs (window-vscroll nil t)) 0)
4268 (when (> rbot 0)
4269 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
4270 ;; If cursor just entered the bottom scroll margin, move forward,
4271 ;; but also vscroll one line so redisplay wont recenter.
4272 ((and (> vpos 0)
4273 (= py (min (- (window-text-height) scroll-margin 1)
4274 (1- vpos))))
4275 (set-window-vscroll nil (frame-char-height) t)
4276 (line-move-1 arg noerror to-end)
4278 ;; If there are lines above the last line, scroll-up one line.
4279 ((> vpos 0)
4280 (scroll-up 1)
4282 ;; Finally, start vscroll.
4284 (set-window-vscroll nil (frame-char-height) t)))))))
4287 ;; This is like line-move-1 except that it also performs
4288 ;; vertical scrolling of tall images if appropriate.
4289 ;; That is not really a clean thing to do, since it mixes
4290 ;; scrolling with cursor motion. But so far we don't have
4291 ;; a cleaner solution to the problem of making C-n do something
4292 ;; useful given a tall image.
4293 (defun line-move (arg &optional noerror to-end try-vscroll)
4294 (unless (and auto-window-vscroll try-vscroll
4295 ;; Only vscroll for single line moves
4296 (= (abs arg) 1)
4297 ;; But don't vscroll in a keyboard macro.
4298 (not defining-kbd-macro)
4299 (not executing-kbd-macro)
4300 (line-move-partial arg noerror to-end))
4301 (set-window-vscroll nil 0 t)
4302 (if line-move-visual
4303 (line-move-visual arg noerror)
4304 (line-move-1 arg noerror to-end))))
4306 ;; Display-based alternative to line-move-1.
4307 ;; Arg says how many lines to move. The value is t if we can move the
4308 ;; specified number of lines.
4309 (defun line-move-visual (arg &optional noerror)
4310 (let ((opoint (point))
4311 (hscroll (window-hscroll))
4312 target-hscroll)
4313 ;; Check if the previous command was a line-motion command, or if
4314 ;; we were called from some other command.
4315 (if (and (consp temporary-goal-column)
4316 (memq last-command `(next-line previous-line ,this-command)))
4317 ;; If so, there's no need to reset `temporary-goal-column',
4318 ;; but we may need to hscroll.
4319 (if (or (/= (cdr temporary-goal-column) hscroll)
4320 (> (cdr temporary-goal-column) 0))
4321 (setq target-hscroll (cdr temporary-goal-column)))
4322 ;; Otherwise, we should reset `temporary-goal-column'.
4323 (let ((posn (posn-at-point)))
4324 (cond
4325 ;; Handle the `overflow-newline-into-fringe' case:
4326 ((eq (nth 1 posn) 'right-fringe)
4327 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
4328 ((car (posn-x-y posn))
4329 (setq temporary-goal-column
4330 (cons (/ (float (car (posn-x-y posn)))
4331 (frame-char-width)) hscroll))))))
4332 (if target-hscroll
4333 (set-window-hscroll (selected-window) target-hscroll))
4334 (or (and (= (vertical-motion
4335 (cons (or goal-column
4336 (if (consp temporary-goal-column)
4337 (car temporary-goal-column)
4338 temporary-goal-column))
4339 arg))
4340 arg)
4341 (or (>= arg 0)
4342 (/= (point) opoint)
4343 ;; If the goal column lies on a display string,
4344 ;; `vertical-motion' advances the cursor to the end
4345 ;; of the string. For arg < 0, this can cause the
4346 ;; cursor to get stuck. (Bug#3020).
4347 (= (vertical-motion arg) arg)))
4348 (unless noerror
4349 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
4350 nil)))))
4352 ;; This is the guts of next-line and previous-line.
4353 ;; Arg says how many lines to move.
4354 ;; The value is t if we can move the specified number of lines.
4355 (defun line-move-1 (arg &optional noerror to-end)
4356 ;; Don't run any point-motion hooks, and disregard intangibility,
4357 ;; for intermediate positions.
4358 (let ((inhibit-point-motion-hooks t)
4359 (opoint (point))
4360 (orig-arg arg))
4361 (if (consp temporary-goal-column)
4362 (setq temporary-goal-column (+ (car temporary-goal-column)
4363 (cdr temporary-goal-column))))
4364 (unwind-protect
4365 (progn
4366 (if (not (memq last-command '(next-line previous-line)))
4367 (setq temporary-goal-column
4368 (if (and track-eol (eolp)
4369 ;; Don't count beg of empty line as end of line
4370 ;; unless we just did explicit end-of-line.
4371 (or (not (bolp)) (eq last-command 'move-end-of-line)))
4372 most-positive-fixnum
4373 (current-column))))
4375 (if (not (or (integerp selective-display)
4376 line-move-ignore-invisible))
4377 ;; Use just newline characters.
4378 ;; Set ARG to 0 if we move as many lines as requested.
4379 (or (if (> arg 0)
4380 (progn (if (> arg 1) (forward-line (1- arg)))
4381 ;; This way of moving forward ARG lines
4382 ;; verifies that we have a newline after the last one.
4383 ;; It doesn't get confused by intangible text.
4384 (end-of-line)
4385 (if (zerop (forward-line 1))
4386 (setq arg 0)))
4387 (and (zerop (forward-line arg))
4388 (bolp)
4389 (setq arg 0)))
4390 (unless noerror
4391 (signal (if (< arg 0)
4392 'beginning-of-buffer
4393 'end-of-buffer)
4394 nil)))
4395 ;; Move by arg lines, but ignore invisible ones.
4396 (let (done)
4397 (while (and (> arg 0) (not done))
4398 ;; If the following character is currently invisible,
4399 ;; skip all characters with that same `invisible' property value.
4400 (while (and (not (eobp)) (invisible-p (point)))
4401 (goto-char (next-char-property-change (point))))
4402 ;; Move a line.
4403 ;; We don't use `end-of-line', since we want to escape
4404 ;; from field boundaries occurring exactly at point.
4405 (goto-char (constrain-to-field
4406 (let ((inhibit-field-text-motion t))
4407 (line-end-position))
4408 (point) t t
4409 'inhibit-line-move-field-capture))
4410 ;; If there's no invisibility here, move over the newline.
4411 (cond
4412 ((eobp)
4413 (if (not noerror)
4414 (signal 'end-of-buffer nil)
4415 (setq done t)))
4416 ((and (> arg 1) ;; Use vertical-motion for last move
4417 (not (integerp selective-display))
4418 (not (invisible-p (point))))
4419 ;; We avoid vertical-motion when possible
4420 ;; because that has to fontify.
4421 (forward-line 1))
4422 ;; Otherwise move a more sophisticated way.
4423 ((zerop (vertical-motion 1))
4424 (if (not noerror)
4425 (signal 'end-of-buffer nil)
4426 (setq done t))))
4427 (unless done
4428 (setq arg (1- arg))))
4429 ;; The logic of this is the same as the loop above,
4430 ;; it just goes in the other direction.
4431 (while (and (< arg 0) (not done))
4432 ;; For completely consistency with the forward-motion
4433 ;; case, we should call beginning-of-line here.
4434 ;; However, if point is inside a field and on a
4435 ;; continued line, the call to (vertical-motion -1)
4436 ;; below won't move us back far enough; then we return
4437 ;; to the same column in line-move-finish, and point
4438 ;; gets stuck -- cyd
4439 (forward-line 0)
4440 (cond
4441 ((bobp)
4442 (if (not noerror)
4443 (signal 'beginning-of-buffer nil)
4444 (setq done t)))
4445 ((and (< arg -1) ;; Use vertical-motion for last move
4446 (not (integerp selective-display))
4447 (not (invisible-p (1- (point)))))
4448 (forward-line -1))
4449 ((zerop (vertical-motion -1))
4450 (if (not noerror)
4451 (signal 'beginning-of-buffer nil)
4452 (setq done t))))
4453 (unless done
4454 (setq arg (1+ arg))
4455 (while (and ;; Don't move over previous invis lines
4456 ;; if our target is the middle of this line.
4457 (or (zerop (or goal-column temporary-goal-column))
4458 (< arg 0))
4459 (not (bobp)) (invisible-p (1- (point))))
4460 (goto-char (previous-char-property-change (point))))))))
4461 ;; This is the value the function returns.
4462 (= arg 0))
4464 (cond ((> arg 0)
4465 ;; If we did not move down as far as desired, at least go
4466 ;; to end of line. Be sure to call point-entered and
4467 ;; point-left-hooks.
4468 (let* ((npoint (prog1 (line-end-position)
4469 (goto-char opoint)))
4470 (inhibit-point-motion-hooks nil))
4471 (goto-char npoint)))
4472 ((< arg 0)
4473 ;; If we did not move up as far as desired,
4474 ;; at least go to beginning of line.
4475 (let* ((npoint (prog1 (line-beginning-position)
4476 (goto-char opoint)))
4477 (inhibit-point-motion-hooks nil))
4478 (goto-char npoint)))
4480 (line-move-finish (or goal-column temporary-goal-column)
4481 opoint (> orig-arg 0)))))))
4483 (defun line-move-finish (column opoint forward)
4484 (let ((repeat t))
4485 (while repeat
4486 ;; Set REPEAT to t to repeat the whole thing.
4487 (setq repeat nil)
4489 (let (new
4490 (old (point))
4491 (line-beg (line-beginning-position))
4492 (line-end
4493 ;; Compute the end of the line
4494 ;; ignoring effectively invisible newlines.
4495 (save-excursion
4496 ;; Like end-of-line but ignores fields.
4497 (skip-chars-forward "^\n")
4498 (while (and (not (eobp)) (invisible-p (point)))
4499 (goto-char (next-char-property-change (point)))
4500 (skip-chars-forward "^\n"))
4501 (point))))
4503 ;; Move to the desired column.
4504 (line-move-to-column (truncate column))
4506 ;; Corner case: suppose we start out in a field boundary in
4507 ;; the middle of a continued line. When we get to
4508 ;; line-move-finish, point is at the start of a new *screen*
4509 ;; line but the same text line; then line-move-to-column would
4510 ;; move us backwards. Test using C-n with point on the "x" in
4511 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4512 (and forward
4513 (< (point) old)
4514 (goto-char old))
4516 (setq new (point))
4518 ;; Process intangibility within a line.
4519 ;; With inhibit-point-motion-hooks bound to nil, a call to
4520 ;; goto-char moves point past intangible text.
4522 ;; However, inhibit-point-motion-hooks controls both the
4523 ;; intangibility and the point-entered/point-left hooks. The
4524 ;; following hack avoids calling the point-* hooks
4525 ;; unnecessarily. Note that we move *forward* past intangible
4526 ;; text when the initial and final points are the same.
4527 (goto-char new)
4528 (let ((inhibit-point-motion-hooks nil))
4529 (goto-char new)
4531 ;; If intangibility moves us to a different (later) place
4532 ;; in the same line, use that as the destination.
4533 (if (<= (point) line-end)
4534 (setq new (point))
4535 ;; If that position is "too late",
4536 ;; try the previous allowable position.
4537 ;; See if it is ok.
4538 (backward-char)
4539 (if (if forward
4540 ;; If going forward, don't accept the previous
4541 ;; allowable position if it is before the target line.
4542 (< line-beg (point))
4543 ;; If going backward, don't accept the previous
4544 ;; allowable position if it is still after the target line.
4545 (<= (point) line-end))
4546 (setq new (point))
4547 ;; As a last resort, use the end of the line.
4548 (setq new line-end))))
4550 ;; Now move to the updated destination, processing fields
4551 ;; as well as intangibility.
4552 (goto-char opoint)
4553 (let ((inhibit-point-motion-hooks nil))
4554 (goto-char
4555 ;; Ignore field boundaries if the initial and final
4556 ;; positions have the same `field' property, even if the
4557 ;; fields are non-contiguous. This seems to be "nicer"
4558 ;; behavior in many situations.
4559 (if (eq (get-char-property new 'field)
4560 (get-char-property opoint 'field))
4562 (constrain-to-field new opoint t t
4563 'inhibit-line-move-field-capture))))
4565 ;; If all this moved us to a different line,
4566 ;; retry everything within that new line.
4567 (when (or (< (point) line-beg) (> (point) line-end))
4568 ;; Repeat the intangibility and field processing.
4569 (setq repeat t))))))
4571 (defun line-move-to-column (col)
4572 "Try to find column COL, considering invisibility.
4573 This function works only in certain cases,
4574 because what we really need is for `move-to-column'
4575 and `current-column' to be able to ignore invisible text."
4576 (if (zerop col)
4577 (beginning-of-line)
4578 (move-to-column col))
4580 (when (and line-move-ignore-invisible
4581 (not (bolp)) (invisible-p (1- (point))))
4582 (let ((normal-location (point))
4583 (normal-column (current-column)))
4584 ;; If the following character is currently invisible,
4585 ;; skip all characters with that same `invisible' property value.
4586 (while (and (not (eobp))
4587 (invisible-p (point)))
4588 (goto-char (next-char-property-change (point))))
4589 ;; Have we advanced to a larger column position?
4590 (if (> (current-column) normal-column)
4591 ;; We have made some progress towards the desired column.
4592 ;; See if we can make any further progress.
4593 (line-move-to-column (+ (current-column) (- col normal-column)))
4594 ;; Otherwise, go to the place we originally found
4595 ;; and move back over invisible text.
4596 ;; that will get us to the same place on the screen
4597 ;; but with a more reasonable buffer position.
4598 (goto-char normal-location)
4599 (let ((line-beg (line-beginning-position)))
4600 (while (and (not (bolp)) (invisible-p (1- (point))))
4601 (goto-char (previous-char-property-change (point) line-beg))))))))
4603 (defun move-end-of-line (arg)
4604 "Move point to end of current line as displayed.
4605 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4606 If point reaches the beginning or end of buffer, it stops there.
4608 To ignore the effects of the `intangible' text or overlay
4609 property, bind `inhibit-point-motion-hooks' to t.
4610 If there is an image in the current line, this function
4611 disregards newlines that are part of the text on which the image
4612 rests."
4613 (interactive "^p")
4614 (or arg (setq arg 1))
4615 (let (done)
4616 (while (not done)
4617 (let ((newpos
4618 (save-excursion
4619 (let ((goal-column 0)
4620 (line-move-visual nil))
4621 (and (line-move arg t)
4622 ;; With bidi reordering, we may not be at bol,
4623 ;; so make sure we are.
4624 (skip-chars-backward "^\n")
4625 (not (bobp))
4626 (progn
4627 (while (and (not (bobp)) (invisible-p (1- (point))))
4628 (goto-char (previous-single-char-property-change
4629 (point) 'invisible)))
4630 (backward-char 1)))
4631 (point)))))
4632 (goto-char newpos)
4633 (if (and (> (point) newpos)
4634 (eq (preceding-char) ?\n))
4635 (backward-char 1)
4636 (if (and (> (point) newpos) (not (eobp))
4637 (not (eq (following-char) ?\n)))
4638 ;; If we skipped something intangible and now we're not
4639 ;; really at eol, keep going.
4640 (setq arg 1)
4641 (setq done t)))))))
4643 (defun move-beginning-of-line (arg)
4644 "Move point to beginning of current line as displayed.
4645 \(If there's an image in the line, this disregards newlines
4646 which are part of the text that the image rests on.)
4648 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4649 If point reaches the beginning or end of buffer, it stops there.
4650 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4651 (interactive "^p")
4652 (or arg (setq arg 1))
4654 (let ((orig (point))
4655 first-vis first-vis-field-value)
4657 ;; Move by lines, if ARG is not 1 (the default).
4658 (if (/= arg 1)
4659 (let ((line-move-visual nil))
4660 (line-move (1- arg) t)))
4662 ;; Move to beginning-of-line, ignoring fields and invisibles.
4663 (skip-chars-backward "^\n")
4664 (while (and (not (bobp)) (invisible-p (1- (point))))
4665 (goto-char (previous-char-property-change (point)))
4666 (skip-chars-backward "^\n"))
4668 ;; Now find first visible char in the line
4669 (while (and (not (eobp)) (invisible-p (point)))
4670 (goto-char (next-char-property-change (point))))
4671 (setq first-vis (point))
4673 ;; See if fields would stop us from reaching FIRST-VIS.
4674 (setq first-vis-field-value
4675 (constrain-to-field first-vis orig (/= arg 1) t nil))
4677 (goto-char (if (/= first-vis-field-value first-vis)
4678 ;; If yes, obey them.
4679 first-vis-field-value
4680 ;; Otherwise, move to START with attention to fields.
4681 ;; (It is possible that fields never matter in this case.)
4682 (constrain-to-field (point) orig
4683 (/= arg 1) t nil)))))
4686 ;; Many people have said they rarely use this feature, and often type
4687 ;; it by accident. Maybe it shouldn't even be on a key.
4688 (put 'set-goal-column 'disabled t)
4690 (defun set-goal-column (arg)
4691 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4692 Those commands will move to this position in the line moved to
4693 rather than trying to keep the same horizontal position.
4694 With a non-nil argument ARG, clears out the goal column
4695 so that \\[next-line] and \\[previous-line] resume vertical motion.
4696 The goal column is stored in the variable `goal-column'."
4697 (interactive "P")
4698 (if arg
4699 (progn
4700 (setq goal-column nil)
4701 (message "No goal column"))
4702 (setq goal-column (current-column))
4703 ;; The older method below can be erroneous if `set-goal-column' is bound
4704 ;; to a sequence containing %
4705 ;;(message (substitute-command-keys
4706 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4707 ;;goal-column)
4708 (message "%s"
4709 (concat
4710 (format "Goal column %d " goal-column)
4711 (substitute-command-keys
4712 "(use \\[set-goal-column] with an arg to unset it)")))
4715 nil)
4717 ;;; Editing based on visual lines, as opposed to logical lines.
4719 (defun end-of-visual-line (&optional n)
4720 "Move point to end of current visual line.
4721 With argument N not nil or 1, move forward N - 1 visual lines first.
4722 If point reaches the beginning or end of buffer, it stops there.
4723 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4724 (interactive "^p")
4725 (or n (setq n 1))
4726 (if (/= n 1)
4727 (let ((line-move-visual t))
4728 (line-move (1- n) t)))
4729 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
4730 ;; constrain to field boundaries, so we don't either.
4731 (vertical-motion (cons (window-width) 0)))
4733 (defun beginning-of-visual-line (&optional n)
4734 "Move point to beginning of current visual line.
4735 With argument N not nil or 1, move forward N - 1 visual lines first.
4736 If point reaches the beginning or end of buffer, it stops there.
4737 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4738 (interactive "^p")
4739 (or n (setq n 1))
4740 (let ((opoint (point)))
4741 (if (/= n 1)
4742 (let ((line-move-visual t))
4743 (line-move (1- n) t)))
4744 (vertical-motion 0)
4745 ;; Constrain to field boundaries, like `move-beginning-of-line'.
4746 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
4748 (defun kill-visual-line (&optional arg)
4749 "Kill the rest of the visual line.
4750 With prefix argument ARG, kill that many visual lines from point.
4751 If ARG is negative, kill visual lines backward.
4752 If ARG is zero, kill the text before point on the current visual
4753 line.
4755 If you want to append the killed line to the last killed text,
4756 use \\[append-next-kill] before \\[kill-line].
4758 If the buffer is read-only, Emacs will beep and refrain from deleting
4759 the line, but put the line in the kill ring anyway. This means that
4760 you can use this command to copy text from a read-only buffer.
4761 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4762 even beep.)"
4763 (interactive "P")
4764 ;; Like in `kill-line', it's better to move point to the other end
4765 ;; of the kill before killing.
4766 (let ((opoint (point))
4767 (kill-whole-line (and kill-whole-line (bolp))))
4768 (if arg
4769 (vertical-motion (prefix-numeric-value arg))
4770 (end-of-visual-line 1)
4771 (if (= (point) opoint)
4772 (vertical-motion 1)
4773 ;; Skip any trailing whitespace at the end of the visual line.
4774 ;; We used to do this only if `show-trailing-whitespace' is
4775 ;; nil, but that's wrong; the correct thing would be to check
4776 ;; whether the trailing whitespace is highlighted. But, it's
4777 ;; OK to just do this unconditionally.
4778 (skip-chars-forward " \t")))
4779 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
4780 (1+ (point))
4781 (point)))))
4783 (defun next-logical-line (&optional arg try-vscroll)
4784 "Move cursor vertically down ARG lines.
4785 This is identical to `next-line', except that it always moves
4786 by logical lines instead of visual lines, ignoring the value of
4787 the variable `line-move-visual'."
4788 (interactive "^p\np")
4789 (let ((line-move-visual nil))
4790 (with-no-warnings
4791 (next-line arg try-vscroll))))
4793 (defun previous-logical-line (&optional arg try-vscroll)
4794 "Move cursor vertically up ARG lines.
4795 This is identical to `previous-line', except that it always moves
4796 by logical lines instead of visual lines, ignoring the value of
4797 the variable `line-move-visual'."
4798 (interactive "^p\np")
4799 (let ((line-move-visual nil))
4800 (with-no-warnings
4801 (previous-line arg try-vscroll))))
4803 (defgroup visual-line nil
4804 "Editing based on visual lines."
4805 :group 'convenience
4806 :version "23.1")
4808 (defvar visual-line-mode-map
4809 (let ((map (make-sparse-keymap)))
4810 (define-key map [remap kill-line] 'kill-visual-line)
4811 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4812 (define-key map [remap move-end-of-line] 'end-of-visual-line)
4813 ;; These keybindings interfere with xterm function keys. Are
4814 ;; there any other suitable bindings?
4815 ;; (define-key map "\M-[" 'previous-logical-line)
4816 ;; (define-key map "\M-]" 'next-logical-line)
4817 map))
4819 (defcustom visual-line-fringe-indicators '(nil nil)
4820 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4821 The value should be a list of the form (LEFT RIGHT), where LEFT
4822 and RIGHT are symbols representing the bitmaps to display, to
4823 indicate wrapped lines, in the left and right fringes respectively.
4824 See also `fringe-indicator-alist'.
4825 The default is not to display fringe indicators for wrapped lines.
4826 This variable does not affect fringe indicators displayed for
4827 other purposes."
4828 :type '(list (choice (const :tag "Hide left indicator" nil)
4829 (const :tag "Left curly arrow" left-curly-arrow)
4830 (symbol :tag "Other bitmap"))
4831 (choice (const :tag "Hide right indicator" nil)
4832 (const :tag "Right curly arrow" right-curly-arrow)
4833 (symbol :tag "Other bitmap")))
4834 :set (lambda (symbol value)
4835 (dolist (buf (buffer-list))
4836 (with-current-buffer buf
4837 (when (and (boundp 'visual-line-mode)
4838 (symbol-value 'visual-line-mode))
4839 (setq fringe-indicator-alist
4840 (cons (cons 'continuation value)
4841 (assq-delete-all
4842 'continuation
4843 (copy-tree fringe-indicator-alist)))))))
4844 (set-default symbol value)))
4846 (defvar visual-line--saved-state nil)
4848 (define-minor-mode visual-line-mode
4849 "Redefine simple editing commands to act on visual lines, not logical lines.
4850 This also turns on `word-wrap' in the buffer."
4851 :keymap visual-line-mode-map
4852 :group 'visual-line
4853 :lighter " Wrap"
4854 (if visual-line-mode
4855 (progn
4856 (set (make-local-variable 'visual-line--saved-state) nil)
4857 ;; Save the local values of some variables, to be restored if
4858 ;; visual-line-mode is turned off.
4859 (dolist (var '(line-move-visual truncate-lines
4860 truncate-partial-width-windows
4861 word-wrap fringe-indicator-alist))
4862 (if (local-variable-p var)
4863 (push (cons var (symbol-value var))
4864 visual-line--saved-state)))
4865 (set (make-local-variable 'line-move-visual) t)
4866 (set (make-local-variable 'truncate-partial-width-windows) nil)
4867 (setq truncate-lines nil
4868 word-wrap t
4869 fringe-indicator-alist
4870 (cons (cons 'continuation visual-line-fringe-indicators)
4871 fringe-indicator-alist)))
4872 (kill-local-variable 'line-move-visual)
4873 (kill-local-variable 'word-wrap)
4874 (kill-local-variable 'truncate-lines)
4875 (kill-local-variable 'truncate-partial-width-windows)
4876 (kill-local-variable 'fringe-indicator-alist)
4877 (dolist (saved visual-line--saved-state)
4878 (set (make-local-variable (car saved)) (cdr saved)))
4879 (kill-local-variable 'visual-line--saved-state)))
4881 (defun turn-on-visual-line-mode ()
4882 (visual-line-mode 1))
4884 (define-globalized-minor-mode global-visual-line-mode
4885 visual-line-mode turn-on-visual-line-mode
4886 :lighter " vl")
4889 (defun transpose-chars (arg)
4890 "Interchange characters around point, moving forward one character.
4891 With prefix arg ARG, effect is to take character before point
4892 and drag it forward past ARG other characters (backward if ARG negative).
4893 If no argument and at end of line, the previous two chars are exchanged."
4894 (interactive "*P")
4895 (and (null arg) (eolp) (forward-char -1))
4896 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4898 (defun transpose-words (arg)
4899 "Interchange words around point, leaving point at end of them.
4900 With prefix arg ARG, effect is to take word before or around point
4901 and drag it forward past ARG other words (backward if ARG negative).
4902 If ARG is zero, the words around or after point and around or after mark
4903 are interchanged."
4904 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
4905 (interactive "*p")
4906 (transpose-subr 'forward-word arg))
4908 (defun transpose-sexps (arg)
4909 "Like \\[transpose-words] but applies to sexps.
4910 Does not work on a sexp that point is in the middle of
4911 if it is a list or string."
4912 (interactive "*p")
4913 (transpose-subr
4914 (lambda (arg)
4915 ;; Here we should try to simulate the behavior of
4916 ;; (cons (progn (forward-sexp x) (point))
4917 ;; (progn (forward-sexp (- x)) (point)))
4918 ;; Except that we don't want to rely on the second forward-sexp
4919 ;; putting us back to where we want to be, since forward-sexp-function
4920 ;; might do funny things like infix-precedence.
4921 (if (if (> arg 0)
4922 (looking-at "\\sw\\|\\s_")
4923 (and (not (bobp))
4924 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4925 ;; Jumping over a symbol. We might be inside it, mind you.
4926 (progn (funcall (if (> arg 0)
4927 'skip-syntax-backward 'skip-syntax-forward)
4928 "w_")
4929 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4930 ;; Otherwise, we're between sexps. Take a step back before jumping
4931 ;; to make sure we'll obey the same precedence no matter which direction
4932 ;; we're going.
4933 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4934 (cons (save-excursion (forward-sexp arg) (point))
4935 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4936 (not (zerop (funcall (if (> arg 0)
4937 'skip-syntax-forward
4938 'skip-syntax-backward)
4939 ".")))))
4940 (point)))))
4941 arg 'special))
4943 (defun transpose-lines (arg)
4944 "Exchange current line and previous line, leaving point after both.
4945 With argument ARG, takes previous line and moves it past ARG lines.
4946 With argument 0, interchanges line point is in with line mark is in."
4947 (interactive "*p")
4948 (transpose-subr (function
4949 (lambda (arg)
4950 (if (> arg 0)
4951 (progn
4952 ;; Move forward over ARG lines,
4953 ;; but create newlines if necessary.
4954 (setq arg (forward-line arg))
4955 (if (/= (preceding-char) ?\n)
4956 (setq arg (1+ arg)))
4957 (if (> arg 0)
4958 (newline arg)))
4959 (forward-line arg))))
4960 arg))
4962 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
4963 ;; which seems inconsistent with the ARG /= 0 case.
4964 ;; FIXME document SPECIAL.
4965 (defun transpose-subr (mover arg &optional special)
4966 "Subroutine to do the work of transposing objects.
4967 Works for lines, sentences, paragraphs, etc. MOVER is a function that
4968 moves forward by units of the given object (e.g. forward-sentence,
4969 forward-paragraph). If ARG is zero, exchanges the current object
4970 with the one containing mark. If ARG is an integer, moves the
4971 current object past ARG following (if ARG is positive) or
4972 preceding (if ARG is negative) objects, leaving point after the
4973 current object."
4974 (let ((aux (if special mover
4975 (lambda (x)
4976 (cons (progn (funcall mover x) (point))
4977 (progn (funcall mover (- x)) (point))))))
4978 pos1 pos2)
4979 (cond
4980 ((= arg 0)
4981 (save-excursion
4982 (setq pos1 (funcall aux 1))
4983 (goto-char (or (mark) (error "No mark set in this buffer")))
4984 (setq pos2 (funcall aux 1))
4985 (transpose-subr-1 pos1 pos2))
4986 (exchange-point-and-mark))
4987 ((> arg 0)
4988 (setq pos1 (funcall aux -1))
4989 (setq pos2 (funcall aux arg))
4990 (transpose-subr-1 pos1 pos2)
4991 (goto-char (car pos2)))
4993 (setq pos1 (funcall aux -1))
4994 (goto-char (car pos1))
4995 (setq pos2 (funcall aux arg))
4996 (transpose-subr-1 pos1 pos2)))))
4998 (defun transpose-subr-1 (pos1 pos2)
4999 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
5000 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
5001 (when (> (car pos1) (car pos2))
5002 (let ((swap pos1))
5003 (setq pos1 pos2 pos2 swap)))
5004 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
5005 (atomic-change-group
5006 (let (word2)
5007 ;; FIXME: We first delete the two pieces of text, so markers that
5008 ;; used to point to after the text end up pointing to before it :-(
5009 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
5010 (goto-char (car pos2))
5011 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
5012 (goto-char (car pos1))
5013 (insert word2))))
5015 (defun backward-word (&optional arg)
5016 "Move backward until encountering the beginning of a word.
5017 With argument ARG, do this that many times."
5018 (interactive "^p")
5019 (forward-word (- (or arg 1))))
5021 (defun mark-word (&optional arg allow-extend)
5022 "Set mark ARG words away from point.
5023 The place mark goes is the same place \\[forward-word] would
5024 move to with the same argument.
5025 Interactively, if this command is repeated
5026 or (in Transient Mark mode) if the mark is active,
5027 it marks the next ARG words after the ones already marked."
5028 (interactive "P\np")
5029 (cond ((and allow-extend
5030 (or (and (eq last-command this-command) (mark t))
5031 (region-active-p)))
5032 (setq arg (if arg (prefix-numeric-value arg)
5033 (if (< (mark) (point)) -1 1)))
5034 (set-mark
5035 (save-excursion
5036 (goto-char (mark))
5037 (forward-word arg)
5038 (point))))
5040 (push-mark
5041 (save-excursion
5042 (forward-word (prefix-numeric-value arg))
5043 (point))
5044 nil t))))
5046 (defun kill-word (arg)
5047 "Kill characters forward until encountering the end of a word.
5048 With argument ARG, do this that many times."
5049 (interactive "p")
5050 (kill-region (point) (progn (forward-word arg) (point))))
5052 (defun backward-kill-word (arg)
5053 "Kill characters backward until encountering the beginning of a word.
5054 With argument ARG, do this that many times."
5055 (interactive "p")
5056 (kill-word (- arg)))
5058 (defun current-word (&optional strict really-word)
5059 "Return the symbol or word that point is on (or a nearby one) as a string.
5060 The return value includes no text properties.
5061 If optional arg STRICT is non-nil, return nil unless point is within
5062 or adjacent to a symbol or word. In all cases the value can be nil
5063 if there is no word nearby.
5064 The function, belying its name, normally finds a symbol.
5065 If optional arg REALLY-WORD is non-nil, it finds just a word."
5066 (save-excursion
5067 (let* ((oldpoint (point)) (start (point)) (end (point))
5068 (syntaxes (if really-word "w" "w_"))
5069 (not-syntaxes (concat "^" syntaxes)))
5070 (skip-syntax-backward syntaxes) (setq start (point))
5071 (goto-char oldpoint)
5072 (skip-syntax-forward syntaxes) (setq end (point))
5073 (when (and (eq start oldpoint) (eq end oldpoint)
5074 ;; Point is neither within nor adjacent to a word.
5075 (not strict))
5076 ;; Look for preceding word in same line.
5077 (skip-syntax-backward not-syntaxes (line-beginning-position))
5078 (if (bolp)
5079 ;; No preceding word in same line.
5080 ;; Look for following word in same line.
5081 (progn
5082 (skip-syntax-forward not-syntaxes (line-end-position))
5083 (setq start (point))
5084 (skip-syntax-forward syntaxes)
5085 (setq end (point)))
5086 (setq end (point))
5087 (skip-syntax-backward syntaxes)
5088 (setq start (point))))
5089 ;; If we found something nonempty, return it as a string.
5090 (unless (= start end)
5091 (buffer-substring-no-properties start end)))))
5093 (defcustom fill-prefix nil
5094 "String for filling to insert at front of new line, or nil for none."
5095 :type '(choice (const :tag "None" nil)
5096 string)
5097 :group 'fill)
5098 (make-variable-buffer-local 'fill-prefix)
5099 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
5101 (defcustom auto-fill-inhibit-regexp nil
5102 "Regexp to match lines which should not be auto-filled."
5103 :type '(choice (const :tag "None" nil)
5104 regexp)
5105 :group 'fill)
5107 (defun do-auto-fill ()
5108 "The default value for `normal-auto-fill-function'.
5109 This is the default auto-fill function, some major modes use a different one.
5110 Returns t if it really did any work."
5111 (let (fc justify give-up
5112 (fill-prefix fill-prefix))
5113 (if (or (not (setq justify (current-justification)))
5114 (null (setq fc (current-fill-column)))
5115 (and (eq justify 'left)
5116 (<= (current-column) fc))
5117 (and auto-fill-inhibit-regexp
5118 (save-excursion (beginning-of-line)
5119 (looking-at auto-fill-inhibit-regexp))))
5120 nil ;; Auto-filling not required
5121 (if (memq justify '(full center right))
5122 (save-excursion (unjustify-current-line)))
5124 ;; Choose a fill-prefix automatically.
5125 (when (and adaptive-fill-mode
5126 (or (null fill-prefix) (string= fill-prefix "")))
5127 (let ((prefix
5128 (fill-context-prefix
5129 (save-excursion (backward-paragraph 1) (point))
5130 (save-excursion (forward-paragraph 1) (point)))))
5131 (and prefix (not (equal prefix ""))
5132 ;; Use auto-indentation rather than a guessed empty prefix.
5133 (not (and fill-indent-according-to-mode
5134 (string-match "\\`[ \t]*\\'" prefix)))
5135 (setq fill-prefix prefix))))
5137 (while (and (not give-up) (> (current-column) fc))
5138 ;; Determine where to split the line.
5139 (let* (after-prefix
5140 (fill-point
5141 (save-excursion
5142 (beginning-of-line)
5143 (setq after-prefix (point))
5144 (and fill-prefix
5145 (looking-at (regexp-quote fill-prefix))
5146 (setq after-prefix (match-end 0)))
5147 (move-to-column (1+ fc))
5148 (fill-move-to-break-point after-prefix)
5149 (point))))
5151 ;; See whether the place we found is any good.
5152 (if (save-excursion
5153 (goto-char fill-point)
5154 (or (bolp)
5155 ;; There is no use breaking at end of line.
5156 (save-excursion (skip-chars-forward " ") (eolp))
5157 ;; It is futile to split at the end of the prefix
5158 ;; since we would just insert the prefix again.
5159 (and after-prefix (<= (point) after-prefix))
5160 ;; Don't split right after a comment starter
5161 ;; since we would just make another comment starter.
5162 (and comment-start-skip
5163 (let ((limit (point)))
5164 (beginning-of-line)
5165 (and (re-search-forward comment-start-skip
5166 limit t)
5167 (eq (point) limit))))))
5168 ;; No good place to break => stop trying.
5169 (setq give-up t)
5170 ;; Ok, we have a useful place to break the line. Do it.
5171 (let ((prev-column (current-column)))
5172 ;; If point is at the fill-point, do not `save-excursion'.
5173 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5174 ;; point will end up before it rather than after it.
5175 (if (save-excursion
5176 (skip-chars-backward " \t")
5177 (= (point) fill-point))
5178 (default-indent-new-line t)
5179 (save-excursion
5180 (goto-char fill-point)
5181 (default-indent-new-line t)))
5182 ;; Now do justification, if required
5183 (if (not (eq justify 'left))
5184 (save-excursion
5185 (end-of-line 0)
5186 (justify-current-line justify nil t)))
5187 ;; If making the new line didn't reduce the hpos of
5188 ;; the end of the line, then give up now;
5189 ;; trying again will not help.
5190 (if (>= (current-column) prev-column)
5191 (setq give-up t))))))
5192 ;; Justify last line.
5193 (justify-current-line justify t t)
5194 t)))
5196 (defvar comment-line-break-function 'comment-indent-new-line
5197 "*Mode-specific function which line breaks and continues a comment.
5198 This function is called during auto-filling when a comment syntax
5199 is defined.
5200 The function should take a single optional argument, which is a flag
5201 indicating whether it should use soft newlines.")
5203 (defun default-indent-new-line (&optional soft)
5204 "Break line at point and indent.
5205 If a comment syntax is defined, call `comment-indent-new-line'.
5207 The inserted newline is marked hard if variable `use-hard-newlines' is true,
5208 unless optional argument SOFT is non-nil."
5209 (interactive)
5210 (if comment-start
5211 (funcall comment-line-break-function soft)
5212 ;; Insert the newline before removing empty space so that markers
5213 ;; get preserved better.
5214 (if soft (insert-and-inherit ?\n) (newline 1))
5215 (save-excursion (forward-char -1) (delete-horizontal-space))
5216 (delete-horizontal-space)
5218 (if (and fill-prefix (not adaptive-fill-mode))
5219 ;; Blindly trust a non-adaptive fill-prefix.
5220 (progn
5221 (indent-to-left-margin)
5222 (insert-before-markers-and-inherit fill-prefix))
5224 (cond
5225 ;; If there's an adaptive prefix, use it unless we're inside
5226 ;; a comment and the prefix is not a comment starter.
5227 (fill-prefix
5228 (indent-to-left-margin)
5229 (insert-and-inherit fill-prefix))
5230 ;; If we're not inside a comment, just try to indent.
5231 (t (indent-according-to-mode))))))
5233 (defvar normal-auto-fill-function 'do-auto-fill
5234 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
5235 Some major modes set this.")
5237 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
5238 ;; `functions' and `hooks' are usually unsafe to set, but setting
5239 ;; auto-fill-function to nil in a file-local setting is safe and
5240 ;; can be useful to prevent auto-filling.
5241 (put 'auto-fill-function 'safe-local-variable 'null)
5242 ;; FIXME: turn into a proper minor mode.
5243 ;; Add a global minor mode version of it.
5244 (define-minor-mode auto-fill-mode
5245 "Toggle Auto Fill mode.
5246 With ARG, turn Auto Fill mode on if and only if ARG is positive.
5247 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
5248 automatically breaks the line at a previous space.
5250 The value of `normal-auto-fill-function' specifies the function to use
5251 for `auto-fill-function' when turning Auto Fill mode on."
5252 :variable (eq auto-fill-function normal-auto-fill-function))
5254 ;; This holds a document string used to document auto-fill-mode.
5255 (defun auto-fill-function ()
5256 "Automatically break line at a previous space, in insertion of text."
5257 nil)
5259 (defun turn-on-auto-fill ()
5260 "Unconditionally turn on Auto Fill mode."
5261 (auto-fill-mode 1))
5263 (defun turn-off-auto-fill ()
5264 "Unconditionally turn off Auto Fill mode."
5265 (auto-fill-mode -1))
5267 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
5269 (defun set-fill-column (arg)
5270 "Set `fill-column' to specified argument.
5271 Use \\[universal-argument] followed by a number to specify a column.
5272 Just \\[universal-argument] as argument means to use the current column."
5273 (interactive
5274 (list (or current-prefix-arg
5275 ;; We used to use current-column silently, but C-x f is too easily
5276 ;; typed as a typo for C-x C-f, so we turned it into an error and
5277 ;; now an interactive prompt.
5278 (read-number "Set fill-column to: " (current-column)))))
5279 (if (consp arg)
5280 (setq arg (current-column)))
5281 (if (not (integerp arg))
5282 ;; Disallow missing argument; it's probably a typo for C-x C-f.
5283 (error "set-fill-column requires an explicit argument")
5284 (message "Fill column set to %d (was %d)" arg fill-column)
5285 (setq fill-column arg)))
5287 (defun set-selective-display (arg)
5288 "Set `selective-display' to ARG; clear it if no arg.
5289 When the value of `selective-display' is a number > 0,
5290 lines whose indentation is >= that value are not displayed.
5291 The variable `selective-display' has a separate value for each buffer."
5292 (interactive "P")
5293 (if (eq selective-display t)
5294 (error "selective-display already in use for marked lines"))
5295 (let ((current-vpos
5296 (save-restriction
5297 (narrow-to-region (point-min) (point))
5298 (goto-char (window-start))
5299 (vertical-motion (window-height)))))
5300 (setq selective-display
5301 (and arg (prefix-numeric-value arg)))
5302 (recenter current-vpos))
5303 (set-window-start (selected-window) (window-start (selected-window)))
5304 (princ "selective-display set to " t)
5305 (prin1 selective-display t)
5306 (princ "." t))
5308 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
5310 (defun toggle-truncate-lines (&optional arg)
5311 "Toggle whether to fold or truncate long lines for the current buffer.
5312 With prefix argument ARG, truncate long lines if ARG is positive,
5313 otherwise don't truncate them. Note that in side-by-side windows,
5314 this command has no effect if `truncate-partial-width-windows'
5315 is non-nil."
5316 (interactive "P")
5317 (setq truncate-lines
5318 (if (null arg)
5319 (not truncate-lines)
5320 (> (prefix-numeric-value arg) 0)))
5321 (force-mode-line-update)
5322 (unless truncate-lines
5323 (let ((buffer (current-buffer)))
5324 (walk-windows (lambda (window)
5325 (if (eq buffer (window-buffer window))
5326 (set-window-hscroll window 0)))
5327 nil t)))
5328 (message "Truncate long lines %s"
5329 (if truncate-lines "enabled" "disabled")))
5331 (defun toggle-word-wrap (&optional arg)
5332 "Toggle whether to use word-wrapping for continuation lines.
5333 With prefix argument ARG, wrap continuation lines at word boundaries
5334 if ARG is positive, otherwise wrap them at the right screen edge.
5335 This command toggles the value of `word-wrap'. It has no effect
5336 if long lines are truncated."
5337 (interactive "P")
5338 (setq word-wrap
5339 (if (null arg)
5340 (not word-wrap)
5341 (> (prefix-numeric-value arg) 0)))
5342 (force-mode-line-update)
5343 (message "Word wrapping %s"
5344 (if word-wrap "enabled" "disabled")))
5346 (defvar overwrite-mode-textual (purecopy " Ovwrt")
5347 "The string displayed in the mode line when in overwrite mode.")
5348 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
5349 "The string displayed in the mode line when in binary overwrite mode.")
5351 (define-minor-mode overwrite-mode
5352 "Toggle overwrite mode.
5353 With prefix argument ARG, turn overwrite mode on if ARG is positive,
5354 otherwise turn it off. In overwrite mode, printing characters typed
5355 in replace existing text on a one-for-one basis, rather than pushing
5356 it to the right. At the end of a line, such characters extend the line.
5357 Before a tab, such characters insert until the tab is filled in.
5358 \\[quoted-insert] still inserts characters in overwrite mode; this
5359 is supposed to make it easier to insert characters when necessary."
5360 :variable (eq overwrite-mode 'overwrite-mode-textual))
5362 (define-minor-mode binary-overwrite-mode
5363 "Toggle binary overwrite mode.
5364 With prefix argument ARG, turn binary overwrite mode on if ARG is
5365 positive, otherwise turn it off. In binary overwrite mode, printing
5366 characters typed in replace existing text. Newlines are not treated
5367 specially, so typing at the end of a line joins the line to the next,
5368 with the typed character between them. Typing before a tab character
5369 simply replaces the tab with the character typed. \\[quoted-insert]
5370 replaces the text at the cursor, just as ordinary typing characters do.
5372 Note that binary overwrite mode is not its own minor mode; it is a
5373 specialization of overwrite mode, entered by setting the
5374 `overwrite-mode' variable to `overwrite-mode-binary'."
5375 :variable (eq overwrite-mode 'overwrite-mode-binary))
5377 (define-minor-mode line-number-mode
5378 "Toggle Line Number mode.
5379 With ARG, turn Line Number mode on if ARG is positive, otherwise
5380 turn it off. When Line Number mode is enabled, the line number
5381 appears in the mode line.
5383 Line numbers do not appear for very large buffers and buffers
5384 with very long lines; see variables `line-number-display-limit'
5385 and `line-number-display-limit-width'."
5386 :init-value t :global t :group 'mode-line)
5388 (define-minor-mode column-number-mode
5389 "Toggle Column Number mode.
5390 With ARG, turn Column Number mode on if ARG is positive,
5391 otherwise turn it off. When Column Number mode is enabled, the
5392 column number appears in the mode line."
5393 :global t :group 'mode-line)
5395 (define-minor-mode size-indication-mode
5396 "Toggle Size Indication mode.
5397 With ARG, turn Size Indication mode on if ARG is positive,
5398 otherwise turn it off. When Size Indication mode is enabled, the
5399 size of the accessible part of the buffer appears in the mode line."
5400 :global t :group 'mode-line)
5402 (define-minor-mode auto-save-mode
5403 "Toggle auto-saving of contents of current buffer.
5404 With prefix argument ARG, turn auto-saving on if positive, else off."
5405 :variable ((and buffer-auto-save-file-name
5406 ;; If auto-save is off because buffer has shrunk,
5407 ;; then toggling should turn it on.
5408 (>= buffer-saved-size 0))
5409 . (lambda (val)
5410 (setq buffer-auto-save-file-name
5411 (cond
5412 ((null val) nil)
5413 ((and buffer-file-name auto-save-visited-file-name
5414 (not buffer-read-only))
5415 buffer-file-name)
5416 (t (make-auto-save-file-name))))))
5417 ;; If -1 was stored here, to temporarily turn off saving,
5418 ;; turn it back on.
5419 (and (< buffer-saved-size 0)
5420 (setq buffer-saved-size 0)))
5422 (defgroup paren-blinking nil
5423 "Blinking matching of parens and expressions."
5424 :prefix "blink-matching-"
5425 :group 'paren-matching)
5427 (defcustom blink-matching-paren t
5428 "Non-nil means show matching open-paren when close-paren is inserted."
5429 :type 'boolean
5430 :group 'paren-blinking)
5432 (defcustom blink-matching-paren-on-screen t
5433 "Non-nil means show matching open-paren when it is on screen.
5434 If nil, don't show it (but the open-paren can still be shown
5435 when it is off screen).
5437 This variable has no effect if `blink-matching-paren' is nil.
5438 \(In that case, the open-paren is never shown.)
5439 It is also ignored if `show-paren-mode' is enabled."
5440 :type 'boolean
5441 :group 'paren-blinking)
5443 (defcustom blink-matching-paren-distance (* 100 1024)
5444 "If non-nil, maximum distance to search backwards for matching open-paren.
5445 If nil, search stops at the beginning of the accessible portion of the buffer."
5446 :version "23.2" ; 25->100k
5447 :type '(choice (const nil) integer)
5448 :group 'paren-blinking)
5450 (defcustom blink-matching-delay 1
5451 "Time in seconds to delay after showing a matching paren."
5452 :type 'number
5453 :group 'paren-blinking)
5455 (defcustom blink-matching-paren-dont-ignore-comments nil
5456 "If nil, `blink-matching-paren' ignores comments.
5457 More precisely, when looking for the matching parenthesis,
5458 it skips the contents of comments that end before point."
5459 :type 'boolean
5460 :group 'paren-blinking)
5462 (defun blink-matching-check-mismatch (start end)
5463 "Return whether or not START...END are matching parens.
5464 END is the current point and START is the blink position.
5465 START might be nil if no matching starter was found.
5466 Returns non-nil if we find there is a mismatch."
5467 (let* ((end-syntax (syntax-after (1- end)))
5468 (matching-paren (and (consp end-syntax)
5469 (eq (syntax-class end-syntax) 5)
5470 (cdr end-syntax))))
5471 ;; For self-matched chars like " and $, we can't know when they're
5472 ;; mismatched or unmatched, so we can only do it for parens.
5473 (when matching-paren
5474 (not (and start
5476 (eq (char-after start) matching-paren)
5477 ;; The cdr might hold a new paren-class info rather than
5478 ;; a matching-char info, in which case the two CDRs
5479 ;; should match.
5480 (eq matching-paren (cdr-safe (syntax-after start)))))))))
5482 (defvar blink-matching-check-function #'blink-matching-check-mismatch
5483 "Function to check parentheses mismatches.
5484 The function takes two arguments (START and END) where START is the
5485 position just before the opening token and END is the position right after.
5486 START can be nil, if it was not found.
5487 The function should return non-nil if the two tokens do not match.")
5489 (defun blink-matching-open ()
5490 "Move cursor momentarily to the beginning of the sexp before point."
5491 (interactive)
5492 (when (and (not (bobp))
5493 blink-matching-paren)
5494 (let* ((oldpos (point))
5495 (message-log-max nil) ; Don't log messages about paren matching.
5496 (blinkpos
5497 (save-excursion
5498 (save-restriction
5499 (if blink-matching-paren-distance
5500 (narrow-to-region
5501 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5502 (- (point) blink-matching-paren-distance))
5503 oldpos))
5504 (let ((parse-sexp-ignore-comments
5505 (and parse-sexp-ignore-comments
5506 (not blink-matching-paren-dont-ignore-comments))))
5507 (condition-case ()
5508 (progn
5509 (forward-sexp -1)
5510 ;; backward-sexp skips backward over prefix chars,
5511 ;; so move back to the matching paren.
5512 (while (and (< (point) (1- oldpos))
5513 (let ((code (syntax-after (point))))
5514 (or (eq (syntax-class code) 6)
5515 (eq (logand 1048576 (car code))
5516 1048576))))
5517 (forward-char 1))
5518 (point))
5519 (error nil))))))
5520 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
5521 (cond
5522 (mismatch
5523 (if blinkpos
5524 (if (minibufferp)
5525 (minibuffer-message " [Mismatched parentheses]")
5526 (message "Mismatched parentheses"))
5527 (if (minibufferp)
5528 (minibuffer-message " [Unmatched parenthesis]")
5529 (message "Unmatched parenthesis"))))
5530 ((not blinkpos) nil)
5531 ((pos-visible-in-window-p blinkpos)
5532 ;; Matching open within window, temporarily move to blinkpos but only
5533 ;; if `blink-matching-paren-on-screen' is non-nil.
5534 (and blink-matching-paren-on-screen
5535 (not show-paren-mode)
5536 (save-excursion
5537 (goto-char blinkpos)
5538 (sit-for blink-matching-delay))))
5540 (save-excursion
5541 (goto-char blinkpos)
5542 (let ((open-paren-line-string
5543 ;; Show what precedes the open in its line, if anything.
5544 (cond
5545 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5546 (buffer-substring (line-beginning-position)
5547 (1+ blinkpos)))
5548 ;; Show what follows the open in its line, if anything.
5549 ((save-excursion
5550 (forward-char 1)
5551 (skip-chars-forward " \t")
5552 (not (eolp)))
5553 (buffer-substring blinkpos
5554 (line-end-position)))
5555 ;; Otherwise show the previous nonblank line,
5556 ;; if there is one.
5557 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5558 (concat
5559 (buffer-substring (progn
5560 (skip-chars-backward "\n \t")
5561 (line-beginning-position))
5562 (progn (end-of-line)
5563 (skip-chars-backward " \t")
5564 (point)))
5565 ;; Replace the newline and other whitespace with `...'.
5566 "..."
5567 (buffer-substring blinkpos (1+ blinkpos))))
5568 ;; There is nothing to show except the char itself.
5569 (t (buffer-substring blinkpos (1+ blinkpos))))))
5570 (message "Matches %s"
5571 (substring-no-properties open-paren-line-string)))))))))
5573 (defvar blink-paren-function 'blink-matching-open
5574 "Function called, if non-nil, whenever a close parenthesis is inserted.
5575 More precisely, a char with closeparen syntax is self-inserted.")
5577 (defun blink-paren-post-self-insert-function ()
5578 (when (and (eq (char-before) last-command-event) ; Sanity check.
5579 (memq (char-syntax last-command-event) '(?\) ?\$))
5580 blink-paren-function
5581 (not executing-kbd-macro)
5582 (not noninteractive)
5583 ;; Verify an even number of quoting characters precede the close.
5584 (= 1 (logand 1 (- (point)
5585 (save-excursion
5586 (forward-char -1)
5587 (skip-syntax-backward "/\\")
5588 (point))))))
5589 (funcall blink-paren-function)))
5591 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
5592 ;; Most likely, this hook is nil, so this arg doesn't matter,
5593 ;; but I use it as a reminder that this function usually
5594 ;; likes to be run after others since it does `sit-for'.
5595 'append)
5597 ;; This executes C-g typed while Emacs is waiting for a command.
5598 ;; Quitting out of a program does not go through here;
5599 ;; that happens in the QUIT macro at the C code level.
5600 (defun keyboard-quit ()
5601 "Signal a `quit' condition.
5602 During execution of Lisp code, this character causes a quit directly.
5603 At top-level, as an editor command, this simply beeps."
5604 (interactive)
5605 ;; Avoid adding the region to the window selection.
5606 (setq saved-region-selection nil)
5607 (let (select-active-regions)
5608 (deactivate-mark))
5609 (if (fboundp 'kmacro-keyboard-quit)
5610 (kmacro-keyboard-quit))
5611 (setq defining-kbd-macro nil)
5612 (signal 'quit nil))
5614 (defvar buffer-quit-function nil
5615 "Function to call to \"quit\" the current buffer, or nil if none.
5616 \\[keyboard-escape-quit] calls this function when its more local actions
5617 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5619 (defun keyboard-escape-quit ()
5620 "Exit the current \"mode\" (in a generalized sense of the word).
5621 This command can exit an interactive command such as `query-replace',
5622 can clear out a prefix argument or a region,
5623 can get out of the minibuffer or other recursive edit,
5624 cancel the use of the current buffer (for special-purpose buffers),
5625 or go back to just one window (by deleting all but the selected window)."
5626 (interactive)
5627 (cond ((eq last-command 'mode-exited) nil)
5628 ((region-active-p)
5629 (deactivate-mark))
5630 ((> (minibuffer-depth) 0)
5631 (abort-recursive-edit))
5632 (current-prefix-arg
5633 nil)
5634 ((> (recursion-depth) 0)
5635 (exit-recursive-edit))
5636 (buffer-quit-function
5637 (funcall buffer-quit-function))
5638 ((not (one-window-p t))
5639 (delete-other-windows))
5640 ((string-match "^ \\*" (buffer-name (current-buffer)))
5641 (bury-buffer))))
5643 (defun play-sound-file (file &optional volume device)
5644 "Play sound stored in FILE.
5645 VOLUME and DEVICE correspond to the keywords of the sound
5646 specification for `play-sound'."
5647 (interactive "fPlay sound file: ")
5648 (let ((sound (list :file file)))
5649 (if volume
5650 (plist-put sound :volume volume))
5651 (if device
5652 (plist-put sound :device device))
5653 (push 'sound sound)
5654 (play-sound sound)))
5657 (defcustom read-mail-command 'rmail
5658 "Your preference for a mail reading package.
5659 This is used by some keybindings which support reading mail.
5660 See also `mail-user-agent' concerning sending mail."
5661 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
5662 (function-item :tag "Gnus" :format "%t\n" gnus)
5663 (function-item :tag "Emacs interface to MH"
5664 :format "%t\n" mh-rmail)
5665 (function :tag "Other"))
5666 :version "21.1"
5667 :group 'mail)
5669 (defcustom mail-user-agent 'message-user-agent
5670 "Your preference for a mail composition package.
5671 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
5672 outgoing email message. This variable lets you specify which
5673 mail-sending package you prefer.
5675 Valid values include:
5677 `message-user-agent' -- use the Message package.
5678 See Info node `(message)'.
5679 `sendmail-user-agent' -- use the Mail package.
5680 See Info node `(emacs)Sending Mail'.
5681 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5682 See Info node `(mh-e)'.
5683 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5684 paraphernalia, particularly the Gcc: header for
5685 archiving.
5687 Additional valid symbols may be available; check with the author of
5688 your package for details. The function should return non-nil if it
5689 succeeds.
5691 See also `read-mail-command' concerning reading mail."
5692 :type '(radio (function-item :tag "Message package"
5693 :format "%t\n"
5694 message-user-agent)
5695 (function-item :tag "Mail package"
5696 :format "%t\n"
5697 sendmail-user-agent)
5698 (function-item :tag "Emacs interface to MH"
5699 :format "%t\n"
5700 mh-e-user-agent)
5701 (function-item :tag "Message with full Gnus features"
5702 :format "%t\n"
5703 gnus-user-agent)
5704 (function :tag "Other"))
5705 :version "23.2" ; sendmail->message
5706 :group 'mail)
5708 (defcustom compose-mail-user-agent-warnings t
5709 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
5710 If the value of `mail-user-agent' is the default, and the user
5711 appears to have customizations applying to the old default,
5712 `compose-mail' issues a warning."
5713 :type 'boolean
5714 :version "23.2"
5715 :group 'mail)
5717 (defun rfc822-goto-eoh ()
5718 ;; Go to header delimiter line in a mail message, following RFC822 rules
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 'switch-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 'switch-to-buffer-other-frame yank-action send-actions
5805 return-action))
5808 (defvar set-variable-value-history nil
5809 "History of values entered with `set-variable'.
5811 Maximum length of the history list is determined by the value
5812 of `history-length', which see.")
5814 (defun set-variable (variable value &optional make-local)
5815 "Set VARIABLE to VALUE. VALUE is a Lisp object.
5816 VARIABLE should be a user option variable name, a Lisp variable
5817 meant to be customized by users. You should enter VALUE in Lisp syntax,
5818 so if you want VALUE to be a string, you must surround it with doublequotes.
5819 VALUE is used literally, not evaluated.
5821 If VARIABLE has a `variable-interactive' property, that is used as if
5822 it were the arg to `interactive' (which see) to interactively read VALUE.
5824 If VARIABLE has been defined with `defcustom', then the type information
5825 in the definition is used to check that VALUE is valid.
5827 With a prefix argument, set VARIABLE to VALUE buffer-locally."
5828 (interactive
5829 (let* ((default-var (variable-at-point))
5830 (var (if (user-variable-p default-var)
5831 (read-variable (format "Set variable (default %s): " default-var)
5832 default-var)
5833 (read-variable "Set variable: ")))
5834 (minibuffer-help-form '(describe-variable var))
5835 (prop (get var 'variable-interactive))
5836 (obsolete (car (get var 'byte-obsolete-variable)))
5837 (prompt (format "Set %s %s to value: " var
5838 (cond ((local-variable-p var)
5839 "(buffer-local)")
5840 ((or current-prefix-arg
5841 (local-variable-if-set-p var))
5842 "buffer-locally")
5843 (t "globally"))))
5844 (val (progn
5845 (when obsolete
5846 (message (concat "`%S' is obsolete; "
5847 (if (symbolp obsolete) "use `%S' instead" "%s"))
5848 var obsolete)
5849 (sit-for 3))
5850 (if prop
5851 ;; Use VAR's `variable-interactive' property
5852 ;; as an interactive spec for prompting.
5853 (call-interactively `(lambda (arg)
5854 (interactive ,prop)
5855 arg))
5856 (read
5857 (read-string prompt nil
5858 'set-variable-value-history
5859 (format "%S" (symbol-value var))))))))
5860 (list var val current-prefix-arg)))
5862 (and (custom-variable-p variable)
5863 (not (get variable 'custom-type))
5864 (custom-load-symbol variable))
5865 (let ((type (get variable 'custom-type)))
5866 (when type
5867 ;; Match with custom type.
5868 (require 'cus-edit)
5869 (setq type (widget-convert type))
5870 (unless (widget-apply type :match value)
5871 (error "Value `%S' does not match type %S of %S"
5872 value (car type) variable))))
5874 (if make-local
5875 (make-local-variable variable))
5877 (set variable value)
5879 ;; Force a thorough redisplay for the case that the variable
5880 ;; has an effect on the display, like `tab-width' has.
5881 (force-mode-line-update))
5883 ;; Define the major mode for lists of completions.
5885 (defvar completion-list-mode-map
5886 (let ((map (make-sparse-keymap)))
5887 (define-key map [mouse-2] 'mouse-choose-completion)
5888 (define-key map [follow-link] 'mouse-face)
5889 (define-key map [down-mouse-2] nil)
5890 (define-key map "\C-m" 'choose-completion)
5891 (define-key map "\e\e\e" 'delete-completion-window)
5892 (define-key map [left] 'previous-completion)
5893 (define-key map [right] 'next-completion)
5894 (define-key map "q" 'quit-window)
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 (let ((same-window-regexps nil)
6432 (same-window-buffer-names))
6433 (pop-to-buffer new)))
6434 new))
6437 (defun clone-indirect-buffer (newname display-flag &optional norecord)
6438 "Create an indirect buffer that is a twin copy of the current buffer.
6440 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
6441 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6442 or if not called with a prefix arg, NEWNAME defaults to the current
6443 buffer's name. The name is modified by adding a `<N>' suffix to it
6444 or by incrementing the N in an existing suffix. Trying to clone a
6445 buffer whose major mode symbol has a non-nil `no-clone-indirect'
6446 property results in an error.
6448 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
6449 This is always done when called interactively.
6451 Optional third arg NORECORD non-nil means do not put this buffer at the
6452 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 norecord))
6471 buffer))
6474 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6475 "Like `clone-indirect-buffer' but display in another window."
6476 (interactive
6477 (progn
6478 (if (get major-mode 'no-clone-indirect)
6479 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6480 (list (if current-prefix-arg
6481 (read-buffer "Name of indirect buffer: " (current-buffer)))
6482 t)))
6483 (let ((pop-up-windows t))
6484 (clone-indirect-buffer newname display-flag norecord)))
6487 ;;; Handling of Backspace and Delete keys.
6489 (defcustom normal-erase-is-backspace 'maybe
6490 "Set the default behavior of the Delete and Backspace keys.
6492 If set to t, Delete key deletes forward and Backspace key deletes
6493 backward.
6495 If set to nil, both Delete and Backspace keys delete backward.
6497 If set to 'maybe (which is the default), Emacs automatically
6498 selects a behavior. On window systems, the behavior depends on
6499 the keyboard used. If the keyboard has both a Backspace key and
6500 a Delete key, and both are mapped to their usual meanings, the
6501 option's default value is set to t, so that Backspace can be used
6502 to delete backward, and Delete can be used to delete forward.
6504 If not running under a window system, customizing this option
6505 accomplishes a similar effect by mapping C-h, which is usually
6506 generated by the Backspace key, to DEL, and by mapping DEL to C-d
6507 via `keyboard-translate'. The former functionality of C-h is
6508 available on the F1 key. You should probably not use this
6509 setting if you don't have both Backspace, Delete and F1 keys.
6511 Setting this variable with setq doesn't take effect. Programmatically,
6512 call `normal-erase-is-backspace-mode' (which see) instead."
6513 :type '(choice (const :tag "Off" nil)
6514 (const :tag "Maybe" maybe)
6515 (other :tag "On" t))
6516 :group 'editing-basics
6517 :version "21.1"
6518 :set (lambda (symbol value)
6519 ;; The fboundp is because of a problem with :set when
6520 ;; dumping Emacs. It doesn't really matter.
6521 (if (fboundp 'normal-erase-is-backspace-mode)
6522 (normal-erase-is-backspace-mode (or value 0))
6523 (set-default symbol value))))
6525 (defun normal-erase-is-backspace-setup-frame (&optional frame)
6526 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6527 (unless frame (setq frame (selected-frame)))
6528 (with-selected-frame frame
6529 (unless (terminal-parameter nil 'normal-erase-is-backspace)
6530 (normal-erase-is-backspace-mode
6531 (if (if (eq normal-erase-is-backspace 'maybe)
6532 (and (not noninteractive)
6533 (or (memq system-type '(ms-dos windows-nt))
6534 (memq window-system '(ns))
6535 (and (memq window-system '(x))
6536 (fboundp 'x-backspace-delete-keys-p)
6537 (x-backspace-delete-keys-p))
6538 ;; If the terminal Emacs is running on has erase char
6539 ;; set to ^H, use the Backspace key for deleting
6540 ;; backward, and the Delete key for deleting forward.
6541 (and (null window-system)
6542 (eq tty-erase-char ?\^H))))
6543 normal-erase-is-backspace)
6544 1 0)))))
6546 (define-minor-mode normal-erase-is-backspace-mode
6547 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6549 With numeric ARG, turn the mode on if and only if ARG is positive.
6551 On window systems, when this mode is on, Delete is mapped to C-d
6552 and Backspace is mapped to DEL; when this mode is off, both
6553 Delete and Backspace are mapped to DEL. (The remapping goes via
6554 `local-function-key-map', so binding Delete or Backspace in the
6555 global or local keymap will override that.)
6557 In addition, on window systems, the bindings of C-Delete, M-Delete,
6558 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6559 the global keymap in accordance with the functionality of Delete and
6560 Backspace. For example, if Delete is remapped to C-d, which deletes
6561 forward, C-Delete is bound to `kill-word', but if Delete is remapped
6562 to DEL, which deletes backward, C-Delete is bound to
6563 `backward-kill-word'.
6565 If not running on a window system, a similar effect is accomplished by
6566 remapping C-h (normally produced by the Backspace key) and DEL via
6567 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6568 to C-d; if it's off, the keys are not remapped.
6570 When not running on a window system, and this mode is turned on, the
6571 former functionality of C-h is available on the F1 key. You should
6572 probably not turn on this mode on a text-only terminal if you don't
6573 have both Backspace, Delete and F1 keys.
6575 See also `normal-erase-is-backspace'."
6576 :variable (eq (terminal-parameter
6577 nil 'normal-erase-is-backspace) 1)
6578 (let ((enabled (eq 1 (terminal-parameter
6579 nil 'normal-erase-is-backspace))))
6581 (cond ((or (memq window-system '(x w32 ns pc))
6582 (memq system-type '(ms-dos windows-nt)))
6583 (let* ((bindings
6584 `(([M-delete] [M-backspace])
6585 ([C-M-delete] [C-M-backspace])
6586 ([?\e C-delete] [?\e C-backspace])))
6587 (old-state (lookup-key local-function-key-map [delete])))
6589 (if enabled
6590 (progn
6591 (define-key local-function-key-map [delete] [deletechar])
6592 (define-key local-function-key-map [kp-delete] [?\C-d])
6593 (define-key local-function-key-map [backspace] [?\C-?])
6594 (dolist (b bindings)
6595 ;; Not sure if input-decode-map is really right, but
6596 ;; keyboard-translate-table (used below) only works
6597 ;; for integer events, and key-translation-table is
6598 ;; global (like the global-map, used earlier).
6599 (define-key input-decode-map (car b) nil)
6600 (define-key input-decode-map (cadr b) nil)))
6601 (define-key local-function-key-map [delete] [?\C-?])
6602 (define-key local-function-key-map [kp-delete] [?\C-?])
6603 (define-key local-function-key-map [backspace] [?\C-?])
6604 (dolist (b bindings)
6605 (define-key input-decode-map (car b) (cadr b))
6606 (define-key input-decode-map (cadr b) (car b))))))
6608 (if enabled
6609 (progn
6610 (keyboard-translate ?\C-h ?\C-?)
6611 (keyboard-translate ?\C-? ?\C-d))
6612 (keyboard-translate ?\C-h ?\C-h)
6613 (keyboard-translate ?\C-? ?\C-?))))
6615 (if (called-interactively-p 'interactive)
6616 (message "Delete key deletes %s"
6617 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
6618 "forward" "backward")))))
6620 (defvar vis-mode-saved-buffer-invisibility-spec nil
6621 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
6623 (define-minor-mode visible-mode
6624 "Toggle Visible mode.
6625 With argument ARG turn Visible mode on if ARG is positive, otherwise
6626 turn it off.
6628 Enabling Visible mode makes all invisible text temporarily visible.
6629 Disabling Visible mode turns off that effect. Visible mode works by
6630 saving the value of `buffer-invisibility-spec' and setting it to nil."
6631 :lighter " Vis"
6632 :group 'editing-basics
6633 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6634 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6635 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
6636 (when visible-mode
6637 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6638 buffer-invisibility-spec)
6639 (setq buffer-invisibility-spec nil)))
6641 ;; Partial application of functions (similar to "currying").
6642 ;; This function is here rather than in subr.el because it uses CL.
6643 (defun apply-partially (fun &rest args)
6644 "Return a function that is a partial application of FUN to ARGS.
6645 ARGS is a list of the first N arguments to pass to FUN.
6646 The result is a new function which does the same as FUN, except that
6647 the first N arguments are fixed at the values with which this function
6648 was called."
6649 (lexical-let ((fun fun) (args1 args))
6650 (lambda (&rest args2) (apply fun (append args1 args2)))))
6652 ;; Minibuffer prompt stuff.
6654 ;(defun minibuffer-prompt-modification (start end)
6655 ; (error "You cannot modify the prompt"))
6658 ;(defun minibuffer-prompt-insertion (start end)
6659 ; (let ((inhibit-modification-hooks t))
6660 ; (delete-region start end)
6661 ; ;; Discard undo information for the text insertion itself
6662 ; ;; and for the text deletion.above.
6663 ; (when (consp buffer-undo-list)
6664 ; (setq buffer-undo-list (cddr buffer-undo-list)))
6665 ; (message "You cannot modify the prompt")))
6668 ;(setq minibuffer-prompt-properties
6669 ; (list 'modification-hooks '(minibuffer-prompt-modification)
6670 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
6674 ;;;; Problematic external packages.
6676 ;; rms says this should be done by specifying symbols that define
6677 ;; versions together with bad values. This is therefore not as
6678 ;; flexible as it could be. See the thread:
6679 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6680 (defconst bad-packages-alist
6681 ;; Not sure exactly which semantic versions have problems.
6682 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
6683 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
6684 "The version of `semantic' loaded does not work in Emacs 22.
6685 It can cause constant high CPU load.
6686 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
6687 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6688 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6689 ;; provided the `CUA-mode' feature. Since this is no longer true,
6690 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6691 (CUA-mode t nil
6692 "CUA-mode is now part of the standard GNU Emacs distribution,
6693 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6695 You have loaded an older version of CUA-mode which does not work
6696 correctly with this version of Emacs. You should remove the old
6697 version and use the one distributed with Emacs."))
6698 "Alist of packages known to cause problems in this version of Emacs.
6699 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6700 PACKAGE is either a regular expression to match file names, or a
6701 symbol (a feature name); see the documentation of
6702 `after-load-alist', to which this variable adds functions.
6703 SYMBOL is either the name of a string variable, or `t'. Upon
6704 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6705 warning using STRING as the message.")
6707 (defun bad-package-check (package)
6708 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6709 (condition-case nil
6710 (let* ((list (assoc package bad-packages-alist))
6711 (symbol (nth 1 list)))
6712 (and list
6713 (boundp symbol)
6714 (or (eq symbol t)
6715 (and (stringp (setq symbol (eval symbol)))
6716 (string-match-p (nth 2 list) symbol)))
6717 (display-warning package (nth 3 list) :warning)))
6718 (error nil)))
6720 (mapc (lambda (elem)
6721 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6722 bad-packages-alist)
6725 (provide 'simple)
6727 ;;; simple.el ends here