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