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