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