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