1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985-1987, 1993-2011 Free Software Foundation, Inc.
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/>.
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
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" ())
37 (defvar compilation-current-error
)
38 (defvar compilation-context-lines
)
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."
53 "Killing and yanking commands."
56 (defgroup paren-matching nil
57 "Highlight (un)matching of parens and expressions."
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
))
73 (while (and (not found
) list
)
75 (if (and (not (eq buffer 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
))))
81 (setq list
(cdr 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
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
)
101 (defun next-buffer ()
102 "Switch to the next buffer in cyclic order."
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."
111 (switch-to-buffer (last-buffer (current-buffer) t
)))
114 ;;; next-error support framework
116 (defgroup next-error nil
117 "`next-error' support framework."
122 '((t (:inherit region
)))
123 "Face used to highlight next error locus."
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
))
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
))
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
))
164 (defcustom next-error-hook nil
165 "List of hook functions run by `next-error' after visiting source file."
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
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
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
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
247 (delq nil
(mapcar (lambda (w)
248 (if (next-error-buffer-p
251 extra-test-inclusive extra-test-exclusive
)
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
)
265 ;; 4. Look for any acceptable buffer.
266 (let ((buffers (buffer-list)))
268 (not (next-error-buffer-p
269 (car buffers
) avoid-current
270 extra-test-inclusive extra-test-exclusive
)))
271 (setq buffers
(cdr buffers
)))
273 ;; 5. Use the current buffer as a last resort if it qualifies,
274 ;; even despite AVOID-CURRENT.
276 (next-error-buffer-p (current-buffer) nil
277 extra-test-inclusive extra-test-exclusive
)
279 (message "This is the only buffer with error message locations")
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'."
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."
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."
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."
362 (let ((next-error-highlight next-error-highlight-no-select
))
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."
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
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))
395 (let ((compilation-context-lines nil
))
396 (setq compilation-current-error
(point))
397 (next-error-no-select 0))
403 (defun fundamental-mode ()
404 "Major mode not specialized for anything in particular.
405 Other major modes are defined by comparison with this one."
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
)
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
)
437 "Keymap used for programming modes.")
439 (defun prog-indent-sexp ()
440 "Indent the expression after point."
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."
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
)))
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
))
475 ;; Do the rest in post-self-insert-hook, because we want to do it
476 ;; *before* other functions on that hook.
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.
485 (goto-char beforepos
)
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
495 (move-to-left-margin nil t
)))))
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
)))
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
)))))
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."
520 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
521 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
523 ;; Don't expand an abbrev before point.
529 (if do-left-margin
(indent-to (current-left-margin)))
530 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
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."
543 (skip-chars-forward " \t")
544 (let* ((col (current-column))
546 ;; What prefix should we check for (nil means don't).
547 (prefix (cond ((stringp arg
) arg
)
550 ;; Does this line start with it?
551 (have-prfx (and prefix
554 (looking-at (regexp-quote prefix
))))))
556 (if have-prfx
(insert-and-inherit prefix
))
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."
566 (if arg
(forward-line 1))
567 (if (eq (preceding-char) ?
\n)
569 (delete-region (point) (1- (point)))
570 ;; If the second line started with the fill prefix,
571 ;; delete the prefix.
573 (<= (+ (point) (length fill-prefix
)) (point-max))
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."
587 (let (thisblank singleblank
)
590 (setq thisblank
(looking-at "[ \t]*$"))
591 ;; Set singleblank if there is just one blank line here.
594 (not (looking-at "[ \t]*\n[ \t]*$"))
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.
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))
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
))
613 (delete-region (point)
614 (if (re-search-forward "[^ \t\n]" nil t
)
615 (progn (beginning-of-line) (point))
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."
629 (barf-if-buffer-read-only)
631 (list (region-beginning) (region-end))
635 (let ((end-marker (copy-marker (or end
(point-max))))
636 (start (or start
(point-min))))
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.
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'.
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'."
656 (delete-horizontal-space t
)
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'."
669 ;; Be careful to insert the newline before indenting the line.
670 ;; Otherwise, the indentation might be wrong.
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
679 (setq pos
(copy-marker pos t
))
680 (indent-according-to-mode)
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."
709 ;; Avoid "obsolete" warnings for translation-table-for-input.
711 (let (translation-table-for-input input-method-function
)
712 (if (or (not overwrite-mode
)
713 (eq overwrite-mode
'overwrite-mode-binary
))
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
723 ;; (setq char (unibyte-char-to-multibyte char)))
725 (if (eq overwrite-mode
'overwrite-mode-binary
)
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."
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."
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."
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."
756 (delete-horizontal-space)
757 (if (or (looking-at "^\\|\\s)")
758 (save-excursion (forward-char -
1)
759 (looking-at "$\\|\\s(\\|\\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."
767 (let ((orig-pos (point)))
772 (skip-chars-forward " \t")
773 (constrain-to-field nil orig-pos t
)))
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."
782 (unless n
(setq n
1))
783 (let ((orig-pos (point))
784 (skip-characters (if (< n
0) " \t\n\r" " \t"))
786 (skip-chars-backward skip-characters
)
787 (constrain-to-field nil orig-pos
)
789 (if (= (following-char) ?\s
)
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."
813 (let ((size (- (point-max) (point-min))))
814 (goto-char (if (and arg
(not (consp arg
)))
817 ;; Avoid overflow for large buffer sizes!
818 (* (prefix-numeric-value arg
)
820 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
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."
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
)))
841 ;; Avoid overflow for large buffer sizes!
842 (* (prefix-numeric-value arg
)
844 (/ (* size
(prefix-numeric-value arg
)) 10)))
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))
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
861 If the value is the symbol `kill', the active region is killed
863 :type
'(choice (const :tag
"Delete active region" t
)
864 (const :tag
"Kill active region" kill
)
865 (const :tag
"Do ordinary deletion" nil
))
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."
884 (signal 'wrong-type-argument
(list 'integerp n
)))
885 (cond ((and (use-region-p)
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
)
895 (memq (char-before) '(?
\t ?
\n))
897 (eq (char-after) ?
\n)))
898 (let ((ocol (current-column)))
899 (delete-char (- n
) killflag
)
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."
916 (signal 'wrong-type-argument
(list 'integerp n
)))
917 (cond ((and (use-region-p)
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."
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."
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.
959 (skip-chars-backward "0-9")
960 (if (looking-at "[0-9]")
961 (buffer-substring-no-properties
963 (progn (skip-chars-forward "0-9")
965 ;; Decide if we're switching buffers.
967 (if (consp current-prefix-arg
)
968 (other-buffer (current-buffer) t
)))
971 (concat " in " (buffer-name buffer
))
973 ;; Read the argument, offering that number (if any) as default.
974 (list (read-from-minibuffer (format (if default
"Goto line%s (%s): "
982 ;; Switch to the desired buffer, one way or another.
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.
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."
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
))
1012 (defun count-lines-region (start end
)
1013 "Print number of lines and characters in the region."
1015 (message "Region has %d lines, %d characters"
1016 (count-lines start end
) (- end start
)))
1019 "Print the current buffer line number and narrowed line number of point."
1021 (let ((start (point-min))
1022 (n (line-number-at-pos)))
1024 (message "Line %d" n
)
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."
1038 (narrow-to-region start end
)
1039 (goto-char (point-min))
1040 (if (eq selective-display t
)
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
)
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
)
1061 (goto-char (point-min))
1062 (setq start
(point))
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'."
1081 (let* ((char (following-char))
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)))
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
)
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
))
1113 (let ((to (or (next-single-property-change pos
'display
)
1115 (if (< to
(+ pos
4))
1116 (setq under-display
"")
1117 (setq under-display
"..."
1120 (concat (buffer-substring-no-properties pos to
)
1122 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
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
))
1131 (format "(%d, #o%o, #x%x, file %s)"
1133 (if (> (length encoded
) 1)
1135 (encoded-string-description encoded coding
)))
1136 (format "(%d, #o%o, #x%x)" char char char
)))))
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"
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
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 ;; Might as well bind TAB to completion, since inserting a TAB char is much
1158 ;; too rarely useful.
1159 (define-key m
"\t" 'lisp-complete-symbol
)
1160 (set-keymap-parent m minibuffer-local-map
)
1161 (setq read-expression-map m
))
1163 (defvar minibuffer-completing-symbol nil
1164 "Non-nil means completing a Lisp symbol in the minibuffer.")
1166 (defvar minibuffer-default nil
1167 "The current default value or list of default values in the minibuffer.
1168 The functions `read-from-minibuffer' and `completing-read' bind
1169 this variable locally.")
1171 (defcustom eval-expression-print-level
4
1172 "Value for `print-level' while printing value in `eval-expression'.
1173 A value of nil means no limit."
1175 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1178 (defcustom eval-expression-print-length
12
1179 "Value for `print-length' while printing value in `eval-expression'.
1180 A value of nil means no limit."
1182 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1185 (defcustom eval-expression-debug-on-error t
1186 "If non-nil set `debug-on-error' to t in `eval-expression'.
1187 If nil, don't change the value of `debug-on-error'."
1192 (defun eval-expression-print-format (value)
1193 "Format VALUE as a result of evaluated expression.
1194 Return a formatted string which is displayed in the echo area
1195 in addition to the value printed by prin1 in functions which
1196 display the result of expression evaluation."
1197 (if (and (integerp value
)
1198 (or (not (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1199 (eq this-command last-command
)
1200 (if (boundp 'edebug-active
) edebug-active
)))
1202 (if (or (if (boundp 'edebug-active
) edebug-active
)
1203 (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1204 (prin1-char value
))))
1206 (format " (#o%o, #x%x, %s)" value value char-string
)
1207 (format " (#o%o, #x%x)" value value
)))))
1209 ;; We define this, rather than making `eval' interactive,
1210 ;; for the sake of completion of names like eval-region, eval-buffer.
1211 (defun eval-expression (eval-expression-arg
1212 &optional eval-expression-insert-value
)
1213 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1214 Value is also consed on to front of the variable `values'.
1215 Optional argument EVAL-EXPRESSION-INSERT-VALUE non-nil (interactively,
1216 with prefix argument) means insert the result into the current buffer
1217 instead of printing it in the echo area. Truncates long output
1218 according to the value of the variables `eval-expression-print-length'
1219 and `eval-expression-print-level'.
1221 If `eval-expression-debug-on-error' is non-nil, which is the default,
1222 this command arranges for all errors to enter the debugger."
1224 (list (let ((minibuffer-completing-symbol t
))
1225 (read-from-minibuffer "Eval: "
1226 nil read-expression-map t
1227 'read-expression-history
))
1228 current-prefix-arg
))
1230 (if (null eval-expression-debug-on-error
)
1231 (push (eval eval-expression-arg lexical-binding
) values
)
1232 (let ((old-value (make-symbol "t")) new-value
)
1233 ;; Bind debug-on-error to something unique so that we can
1234 ;; detect when evaled code changes it.
1235 (let ((debug-on-error old-value
))
1236 (push (eval eval-expression-arg lexical-binding
) values
)
1237 (setq new-value debug-on-error
))
1238 ;; If evaled code has changed the value of debug-on-error,
1239 ;; propagate that change to the global binding.
1240 (unless (eq old-value new-value
)
1241 (setq debug-on-error new-value
))))
1243 (let ((print-length eval-expression-print-length
)
1244 (print-level eval-expression-print-level
))
1245 (if eval-expression-insert-value
1247 (let ((standard-output (current-buffer)))
1248 (prin1 (car values
))))
1250 (prin1 (car values
) t
)
1251 (let ((str (eval-expression-print-format (car values
))))
1252 (if str
(princ str t
)))))))
1254 (defun edit-and-eval-command (prompt command
)
1255 "Prompting with PROMPT, let user edit COMMAND and eval result.
1256 COMMAND is a Lisp expression. Let user edit that expression in
1257 the minibuffer, then read and evaluate the result."
1259 (let ((print-level nil
)
1260 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1262 (read-from-minibuffer prompt
1263 (prin1-to-string command
)
1264 read-expression-map t
1266 ;; If command was added to command-history as a string,
1267 ;; get rid of that. We want only evaluable expressions there.
1268 (if (stringp (car command-history
))
1269 (setq command-history
(cdr command-history
)))))))
1271 ;; If command to be redone does not match front of history,
1272 ;; add it to the history.
1273 (or (equal command
(car command-history
))
1274 (setq command-history
(cons command command-history
)))
1277 (defun repeat-complex-command (arg)
1278 "Edit and re-evaluate last complex command, or ARGth from last.
1279 A complex command is one which used the minibuffer.
1280 The command is placed in the minibuffer as a Lisp form for editing.
1281 The result is executed, repeating the command as changed.
1282 If the command has been changed or is not the most recent previous
1283 command it is added to the front of the command history.
1284 You can use the minibuffer history commands \
1285 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1286 to get different commands to edit and resubmit."
1288 (let ((elt (nth (1- arg
) command-history
))
1293 (let ((print-level nil
)
1294 (minibuffer-history-position arg
)
1295 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1297 (read-from-minibuffer
1298 "Redo: " (prin1-to-string elt
) read-expression-map t
1299 (cons 'command-history arg
))
1301 ;; If command was added to command-history as a
1302 ;; string, get rid of that. We want only
1303 ;; evaluable expressions there.
1304 (if (stringp (car command-history
))
1305 (setq command-history
(cdr command-history
))))))
1307 ;; If command to be redone does not match front of history,
1308 ;; add it to the history.
1309 (or (equal newcmd
(car command-history
))
1310 (setq command-history
(cons newcmd command-history
)))
1313 (error "Argument %d is beyond length of command history" arg
)
1314 (error "There are no previous complex commands to repeat")))))
1316 (defun read-extended-command ()
1317 "Read command name to invoke in `execute-extended-command'."
1318 (minibuffer-with-setup-hook
1320 (set (make-local-variable 'minibuffer-default-add-function
)
1322 ;; Get a command name at point in the original buffer
1323 ;; to propose it after M-n.
1324 (with-current-buffer (window-buffer (minibuffer-selected-window))
1325 (and (commandp (function-called-at-point))
1326 (format "%S" (function-called-at-point)))))))
1327 ;; Read a string, completing from and restricting to the set of
1328 ;; all defined commands. Don't provide any initial input.
1329 ;; Save the command read on the extended-command history list.
1332 ((eq current-prefix-arg
'-
) "- ")
1333 ((and (consp current-prefix-arg
)
1334 (eq (car current-prefix-arg
) 4)) "C-u ")
1335 ((and (consp current-prefix-arg
)
1336 (integerp (car current-prefix-arg
)))
1337 (format "%d " (car current-prefix-arg
)))
1338 ((integerp current-prefix-arg
)
1339 (format "%d " current-prefix-arg
)))
1340 ;; This isn't strictly correct if `execute-extended-command'
1341 ;; is bound to anything else (e.g. [menu]).
1342 ;; It could use (key-description (this-single-command-keys)),
1343 ;; but actually a prompt other than "M-x" would be confusing,
1344 ;; because "M-x" is a well-known prompt to read a command
1345 ;; and it serves as a shorthand for "Extended command: ".
1347 obarray
'commandp t nil
'extended-command-history
)))
1350 (defvar minibuffer-history nil
1351 "Default minibuffer history list.
1352 This is used for all minibuffer input
1353 except when an alternate history list is specified.
1355 Maximum length of the history list is determined by the value
1356 of `history-length', which see.")
1357 (defvar minibuffer-history-sexp-flag nil
1358 "Control whether history list elements are expressions or strings.
1359 If the value of this variable equals current minibuffer depth,
1360 they are expressions; otherwise they are strings.
1361 \(That convention is designed to do the right thing for
1362 recursive uses of the minibuffer.)")
1363 (setq minibuffer-history-variable
'minibuffer-history
)
1364 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1365 (defvar minibuffer-history-search-history nil
)
1367 (defvar minibuffer-text-before-history nil
1368 "Text that was in this minibuffer before any history commands.
1369 This is nil if there have not yet been any history commands
1370 in this use of the minibuffer.")
1372 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1374 (defun minibuffer-history-initialize ()
1375 (setq minibuffer-text-before-history nil
))
1377 (defun minibuffer-avoid-prompt (_new _old
)
1378 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1379 (constrain-to-field nil
(point-max)))
1381 (defcustom minibuffer-history-case-insensitive-variables nil
1382 "Minibuffer history variables for which matching should ignore case.
1383 If a history variable is a member of this list, then the
1384 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1385 commands ignore case when searching it, regardless of `case-fold-search'."
1386 :type
'(repeat variable
)
1389 (defun previous-matching-history-element (regexp n
)
1390 "Find the previous history element that matches REGEXP.
1391 \(Previous history elements refer to earlier actions.)
1392 With prefix argument N, search for Nth previous match.
1393 If N is negative, find the next or Nth next match.
1394 Normally, history elements are matched case-insensitively if
1395 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1396 makes the search case-sensitive.
1397 See also `minibuffer-history-case-insensitive-variables'."
1399 (let* ((enable-recursive-minibuffers t
)
1400 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1402 minibuffer-local-map
1404 'minibuffer-history-search-history
1405 (car minibuffer-history-search-history
))))
1406 ;; Use the last regexp specified, by default, if input is empty.
1407 (list (if (string= regexp
"")
1408 (if minibuffer-history-search-history
1409 (car minibuffer-history-search-history
)
1410 (error "No previous history search regexp"))
1412 (prefix-numeric-value current-prefix-arg
))))
1414 (if (and (zerop minibuffer-history-position
)
1415 (null minibuffer-text-before-history
))
1416 (setq minibuffer-text-before-history
1417 (minibuffer-contents-no-properties)))
1418 (let ((history (symbol-value minibuffer-history-variable
))
1420 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1421 ;; On some systems, ignore case for file names.
1422 (if (memq minibuffer-history-variable
1423 minibuffer-history-case-insensitive-variables
)
1425 ;; Respect the user's setting for case-fold-search:
1431 (pos minibuffer-history-position
))
1434 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1435 (when (= pos prevpos
)
1436 (error (if (= pos
1)
1437 "No later matching history item"
1438 "No earlier matching history item")))
1440 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1441 (let ((print-level nil
))
1442 (prin1-to-string (nth (1- pos
) history
)))
1443 (nth (1- pos
) history
)))
1446 (and (string-match regexp match-string
)
1448 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1449 (match-beginning 1))))
1451 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1452 (setq minibuffer-history-position pos
)
1453 (goto-char (point-max))
1454 (delete-minibuffer-contents)
1455 (insert match-string
)
1456 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1457 (if (memq (car (car command-history
)) '(previous-matching-history-element
1458 next-matching-history-element
))
1459 (setq command-history
(cdr command-history
))))
1461 (defun next-matching-history-element (regexp n
)
1462 "Find the next history element that matches REGEXP.
1463 \(The next history element refers to a more recent action.)
1464 With prefix argument N, search for Nth next match.
1465 If N is negative, find the previous or Nth previous match.
1466 Normally, history elements are matched case-insensitively if
1467 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1468 makes the search case-sensitive."
1470 (let* ((enable-recursive-minibuffers t
)
1471 (regexp (read-from-minibuffer "Next element matching (regexp): "
1473 minibuffer-local-map
1475 'minibuffer-history-search-history
1476 (car minibuffer-history-search-history
))))
1477 ;; Use the last regexp specified, by default, if input is empty.
1478 (list (if (string= regexp
"")
1479 (if minibuffer-history-search-history
1480 (car minibuffer-history-search-history
)
1481 (error "No previous history search regexp"))
1483 (prefix-numeric-value current-prefix-arg
))))
1484 (previous-matching-history-element regexp
(- n
)))
1486 (defvar minibuffer-temporary-goal-position nil
)
1488 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
1489 "Function run by `goto-history-element' before consuming default values.
1490 This is useful to dynamically add more elements to the list of default values
1491 when `goto-history-element' reaches the end of this list.
1492 Before calling this function `goto-history-element' sets the variable
1493 `minibuffer-default-add-done' to t, so it will call this function only
1494 once. In special cases, when this function needs to be called more
1495 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1496 overriding the setting of this variable to t in `goto-history-element'.")
1498 (defvar minibuffer-default-add-done nil
1499 "When nil, add more elements to the end of the list of default values.
1500 The value nil causes `goto-history-element' to add more elements to
1501 the list of defaults when it reaches the end of this list. It does
1502 this by calling a function defined by `minibuffer-default-add-function'.")
1504 (make-variable-buffer-local 'minibuffer-default-add-done
)
1506 (defun minibuffer-default-add-completions ()
1507 "Return a list of all completions without the default value.
1508 This function is used to add all elements of the completion table to
1509 the end of the list of defaults just after the default value."
1510 (let ((def minibuffer-default
)
1511 (all (all-completions ""
1512 minibuffer-completion-table
1513 minibuffer-completion-predicate
)))
1516 (cons def
(delete def all
)))))
1518 (defun goto-history-element (nabs)
1519 "Puts element of the minibuffer history in the minibuffer.
1520 The argument NABS specifies the absolute history position."
1522 (when (and (not minibuffer-default-add-done
)
1523 (functionp minibuffer-default-add-function
)
1524 (< nabs
(- (if (listp minibuffer-default
)
1525 (length minibuffer-default
)
1527 (setq minibuffer-default-add-done t
1528 minibuffer-default
(funcall minibuffer-default-add-function
)))
1529 (let ((minimum (if minibuffer-default
1530 (- (if (listp minibuffer-default
)
1531 (length minibuffer-default
)
1534 elt minibuffer-returned-to-present
)
1535 (if (and (zerop minibuffer-history-position
)
1536 (null minibuffer-text-before-history
))
1537 (setq minibuffer-text-before-history
1538 (minibuffer-contents-no-properties)))
1539 (if (< nabs minimum
)
1540 (if minibuffer-default
1541 (error "End of defaults; no next item")
1542 (error "End of history; no default available")))
1543 (if (> nabs
(length (symbol-value minibuffer-history-variable
)))
1544 (error "Beginning of history; no preceding item"))
1545 (unless (memq last-command
'(next-history-element
1546 previous-history-element
))
1547 (let ((prompt-end (minibuffer-prompt-end)))
1548 (set (make-local-variable 'minibuffer-temporary-goal-position
)
1549 (cond ((<= (point) prompt-end
) prompt-end
)
1552 (goto-char (point-max))
1553 (delete-minibuffer-contents)
1554 (setq minibuffer-history-position nabs
)
1556 (setq elt
(if (listp minibuffer-default
)
1557 (nth (1- (abs nabs
)) minibuffer-default
)
1558 minibuffer-default
)))
1560 (setq elt
(or minibuffer-text-before-history
""))
1561 (setq minibuffer-returned-to-present t
)
1562 (setq minibuffer-text-before-history nil
))
1563 (t (setq elt
(nth (1- minibuffer-history-position
)
1564 (symbol-value minibuffer-history-variable
)))))
1566 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1567 (not minibuffer-returned-to-present
))
1568 (let ((print-level nil
))
1569 (prin1-to-string elt
))
1571 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
1573 (defun next-history-element (n)
1574 "Puts next element of the minibuffer history in the minibuffer.
1575 With argument N, it uses the Nth following element."
1578 (goto-history-element (- minibuffer-history-position n
))))
1580 (defun previous-history-element (n)
1581 "Puts previous element of the minibuffer history in the minibuffer.
1582 With argument N, it uses the Nth previous element."
1585 (goto-history-element (+ minibuffer-history-position n
))))
1587 (defun next-complete-history-element (n)
1588 "Get next history element which completes the minibuffer before the point.
1589 The contents of the minibuffer after the point are deleted, and replaced
1590 by the new completion."
1592 (let ((point-at-start (point)))
1593 (next-matching-history-element
1595 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1597 ;; next-matching-history-element always puts us at (point-min).
1598 ;; Move to the position we were at before changing the buffer contents.
1599 ;; This is still sensical, because the text before point has not changed.
1600 (goto-char point-at-start
)))
1602 (defun previous-complete-history-element (n)
1604 Get previous history element which completes the minibuffer before the point.
1605 The contents of the minibuffer after the point are deleted, and replaced
1606 by the new completion."
1608 (next-complete-history-element (- n
)))
1610 ;; For compatibility with the old subr of the same name.
1611 (defun minibuffer-prompt-width ()
1612 "Return the display width of the minibuffer prompt.
1613 Return 0 if current buffer is not a minibuffer."
1614 ;; Return the width of everything before the field at the end of
1615 ;; the buffer; this should be 0 for normal buffers.
1616 (1- (minibuffer-prompt-end)))
1618 ;; isearch minibuffer history
1619 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
1621 (defvar minibuffer-history-isearch-message-overlay
)
1622 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
1624 (defun minibuffer-history-isearch-setup ()
1625 "Set up a minibuffer for using isearch to search the minibuffer history.
1626 Intended to be added to `minibuffer-setup-hook'."
1627 (set (make-local-variable 'isearch-search-fun-function
)
1628 'minibuffer-history-isearch-search
)
1629 (set (make-local-variable 'isearch-message-function
)
1630 'minibuffer-history-isearch-message
)
1631 (set (make-local-variable 'isearch-wrap-function
)
1632 'minibuffer-history-isearch-wrap
)
1633 (set (make-local-variable 'isearch-push-state-function
)
1634 'minibuffer-history-isearch-push-state
)
1635 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
1637 (defun minibuffer-history-isearch-end ()
1638 "Clean up the minibuffer after terminating isearch in the minibuffer."
1639 (if minibuffer-history-isearch-message-overlay
1640 (delete-overlay minibuffer-history-isearch-message-overlay
)))
1642 (defun minibuffer-history-isearch-search ()
1643 "Return the proper search function, for isearch in minibuffer history."
1646 (if isearch-forward
'word-search-forward
'word-search-backward
))
1648 (lambda (string bound noerror
)
1650 ;; Use standard functions to search within minibuffer text
1653 (if isearch-forward
're-search-forward
're-search-backward
))
1655 (if isearch-forward
'search-forward
'search-backward
))))
1657 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1658 ;; searching forward. Lazy-highlight calls this lambda with the
1659 ;; bound arg, so skip the minibuffer prompt.
1660 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
1661 (goto-char (minibuffer-prompt-end)))
1663 ;; 1. First try searching in the initial minibuffer text
1664 (funcall search-fun string
1665 (if isearch-forward bound
(minibuffer-prompt-end))
1667 ;; 2. If the above search fails, start putting next/prev history
1668 ;; elements in the minibuffer successively, and search the string
1669 ;; in them. Do this only when bound is nil (i.e. not while
1670 ;; lazy-highlighting search strings in the current minibuffer text).
1675 (cond (isearch-forward
1676 (next-history-element 1)
1677 (goto-char (minibuffer-prompt-end)))
1679 (previous-history-element 1)
1680 (goto-char (point-max))))
1681 (setq isearch-barrier
(point) isearch-opoint
(point))
1682 ;; After putting the next/prev history element, search
1683 ;; the string in them again, until next-history-element
1684 ;; or previous-history-element raises an error at the
1685 ;; beginning/end of history.
1686 (setq found
(funcall search-fun string
1687 (unless isearch-forward
1688 ;; For backward search, don't search
1689 ;; in the minibuffer prompt
1690 (minibuffer-prompt-end))
1692 ;; Return point of the new search result
1694 ;; Return nil when next(prev)-history-element fails
1697 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
1698 "Display the minibuffer history search prompt.
1699 If there are no search errors, this function displays an overlay with
1700 the isearch prompt which replaces the original minibuffer prompt.
1701 Otherwise, it displays the standard isearch message returned from
1703 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
1704 ;; Use standard function `isearch-message' when not in the minibuffer,
1705 ;; or search fails, or has an error (like incomplete regexp).
1706 ;; This function overwrites minibuffer text with isearch message,
1707 ;; so it's possible to see what is wrong in the search string.
1708 (isearch-message c-q-hack ellipsis
)
1709 ;; Otherwise, put the overlay with the standard isearch prompt over
1710 ;; the initial minibuffer prompt.
1711 (if (overlayp minibuffer-history-isearch-message-overlay
)
1712 (move-overlay minibuffer-history-isearch-message-overlay
1713 (point-min) (minibuffer-prompt-end))
1714 (setq minibuffer-history-isearch-message-overlay
1715 (make-overlay (point-min) (minibuffer-prompt-end)))
1716 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
1717 (overlay-put minibuffer-history-isearch-message-overlay
1718 'display
(isearch-message-prefix c-q-hack ellipsis
))
1719 ;; And clear any previous isearch message.
1722 (defun minibuffer-history-isearch-wrap ()
1723 "Wrap the minibuffer history search when search fails.
1724 Move point to the first history element for a forward search,
1725 or to the last history element for a backward search."
1726 (unless isearch-word
1727 ;; When `minibuffer-history-isearch-search' fails on reaching the
1728 ;; beginning/end of the history, wrap the search to the first/last
1729 ;; minibuffer history element.
1731 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
1732 (goto-history-element 0))
1733 (setq isearch-success t
))
1734 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
1736 (defun minibuffer-history-isearch-push-state ()
1737 "Save a function restoring the state of minibuffer history search.
1738 Save `minibuffer-history-position' to the additional state parameter
1739 in the search status stack."
1741 (minibuffer-history-isearch-pop-state cmd
,minibuffer-history-position
)))
1743 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos
)
1744 "Restore the minibuffer history search state.
1745 Go to the history element by the absolute history position HIST-POS."
1746 (goto-history-element hist-pos
))
1749 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1750 (define-obsolete-function-alias 'advertised-undo
'undo
"23.2")
1752 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
1753 "Table mapping redo records to the corresponding undo one.
1754 A redo record for undo-in-region maps to t.
1755 A redo record for ordinary undo maps to the following (earlier) undo.")
1757 (defvar undo-in-region nil
1758 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1760 (defvar undo-no-redo nil
1761 "If t, `undo' doesn't go through redo entries.")
1763 (defvar pending-undo-list nil
1764 "Within a run of consecutive undo commands, list remaining to be undone.
1765 If t, we undid all the way to the end of it.")
1767 (defun undo (&optional arg
)
1768 "Undo some previous changes.
1769 Repeat this command to undo more changes.
1770 A numeric ARG serves as a repeat count.
1772 In Transient Mark mode when the mark is active, only undo changes within
1773 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1774 as an argument limits undo to changes within the current region."
1776 ;; Make last-command indicate for the next command that this was an undo.
1777 ;; That way, another undo will undo more.
1778 ;; If we get to the end of the undo history and get an error,
1779 ;; another undo command will find the undo history empty
1780 ;; and will get another error. To begin undoing the undos,
1781 ;; you must type some other command.
1782 (let ((modified (buffer-modified-p))
1783 (recent-save (recent-auto-save-p))
1785 ;; If we get an error in undo-start,
1786 ;; the next command should not be a "consecutive undo".
1787 ;; So set `this-command' to something other than `undo'.
1788 (setq this-command
'undo-start
)
1790 (unless (and (eq last-command
'undo
)
1791 (or (eq pending-undo-list t
)
1792 ;; If something (a timer or filter?) changed the buffer
1793 ;; since the previous command, don't continue the undo seq.
1794 (let ((list buffer-undo-list
))
1795 (while (eq (car list
) nil
)
1796 (setq list
(cdr list
)))
1797 ;; If the last undo record made was made by undo
1798 ;; it shows nothing else happened in between.
1799 (gethash list undo-equiv-table
))))
1800 (setq undo-in-region
1801 (or (region-active-p) (and arg
(not (numberp arg
)))))
1803 (undo-start (region-beginning) (region-end))
1805 ;; get rid of initial undo boundary
1807 ;; If we got this far, the next command should be a consecutive undo.
1808 (setq this-command
'undo
)
1809 ;; Check to see whether we're hitting a redo record, and if
1810 ;; so, ask the user whether she wants to skip the redo/undo pair.
1811 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
1812 (or (eq (selected-window) (minibuffer-window))
1813 (setq message
(if undo-in-region
1814 (if equiv
"Redo in region!" "Undo in region!")
1815 (if equiv
"Redo!" "Undo!"))))
1816 (when (and (consp equiv
) undo-no-redo
)
1817 ;; The equiv entry might point to another redo record if we have done
1818 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1819 (while (let ((next (gethash equiv undo-equiv-table
)))
1820 (if next
(setq equiv next
))))
1821 (setq pending-undo-list equiv
)))
1824 (prefix-numeric-value arg
)
1826 ;; Record the fact that the just-generated undo records come from an
1827 ;; undo operation--that is, they are redo records.
1828 ;; In the ordinary case (not within a region), map the redo
1829 ;; record to the following undos.
1830 ;; I don't know how to do that in the undo-in-region case.
1831 (let ((list buffer-undo-list
))
1832 ;; Strip any leading undo boundaries there might be, like we do
1833 ;; above when checking.
1834 (while (eq (car list
) nil
)
1835 (setq list
(cdr list
)))
1836 (puthash list
(if undo-in-region t pending-undo-list
)
1838 ;; Don't specify a position in the undo record for the undo command.
1839 ;; Instead, undoing this should move point to where the change is.
1840 (let ((tail buffer-undo-list
)
1843 (when (integerp (car tail
))
1844 (let ((pos (car tail
)))
1846 (setcdr prev
(cdr tail
))
1847 (setq buffer-undo-list
(cdr tail
)))
1848 (setq tail
(cdr tail
))
1850 (if (eq pos
(car tail
))
1852 (setcdr prev
(cdr tail
))
1853 (setq buffer-undo-list
(cdr tail
)))
1855 (setq tail
(cdr tail
)))
1857 (setq prev tail tail
(cdr tail
))))
1858 ;; Record what the current undo list says,
1859 ;; so the next command can tell if the buffer was modified in between.
1860 (and modified
(not (buffer-modified-p))
1861 (delete-auto-save-file-if-necessary recent-save
))
1862 ;; Display a message announcing success.
1864 (message "%s" message
))))
1866 (defun buffer-disable-undo (&optional buffer
)
1867 "Make BUFFER stop keeping undo information.
1868 No argument or nil as argument means do this for the current buffer."
1870 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
1871 (setq buffer-undo-list t
)))
1873 (defun undo-only (&optional arg
)
1874 "Undo some previous changes.
1875 Repeat this command to undo more changes.
1876 A numeric ARG serves as a repeat count.
1877 Contrary to `undo', this will not redo a previous undo."
1879 (let ((undo-no-redo t
)) (undo arg
)))
1881 (defvar undo-in-progress nil
1882 "Non-nil while performing an undo.
1883 Some change-hooks test this variable to do something different.")
1885 (defun undo-more (n)
1886 "Undo back N undo-boundaries beyond what was already undone recently.
1887 Call `undo-start' to get ready to undo recent changes,
1888 then call `undo-more' one or more times to undo them."
1889 (or (listp pending-undo-list
)
1890 (error (concat "No further undo information"
1891 (and undo-in-region
" for region"))))
1892 (let ((undo-in-progress t
))
1893 ;; Note: The following, while pulling elements off
1894 ;; `pending-undo-list' will call primitive change functions which
1895 ;; will push more elements onto `buffer-undo-list'.
1896 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
1897 (if (null pending-undo-list
)
1898 (setq pending-undo-list t
))))
1900 ;; Deep copy of a list
1901 (defun undo-copy-list (list)
1902 "Make a copy of undo list LIST."
1903 (mapcar 'undo-copy-list-1 list
))
1905 (defun undo-copy-list-1 (elt)
1907 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
1910 (defun undo-start (&optional beg end
)
1911 "Set `pending-undo-list' to the front of the undo list.
1912 The next call to `undo-more' will undo the most recently made change.
1913 If BEG and END are specified, then only undo elements
1914 that apply to text between BEG and END are used; other undo elements
1915 are ignored. If BEG and END are nil, all undo elements are used."
1916 (if (eq buffer-undo-list t
)
1917 (error "No undo information in this buffer"))
1918 (setq pending-undo-list
1919 (if (and beg end
(not (= beg end
)))
1920 (undo-make-selective-list (min beg end
) (max beg end
))
1923 (defvar undo-adjusted-markers
)
1925 (defun undo-make-selective-list (start end
)
1926 "Return a list of undo elements for the region START to END.
1927 The elements come from `buffer-undo-list', but we keep only
1928 the elements inside this region, and discard those outside this region.
1929 If we find an element that crosses an edge of this region,
1930 we stop and ignore all further elements."
1931 (let ((undo-list-copy (undo-copy-list buffer-undo-list
))
1932 (undo-list (list nil
))
1933 undo-adjusted-markers
1935 undo-elt temp-undo-list delta
)
1936 (while undo-list-copy
1937 (setq undo-elt
(car undo-list-copy
))
1939 (cond ((and (consp undo-elt
) (eq (car undo-elt
) t
))
1940 ;; This is a "was unmodified" element.
1941 ;; Keep it if we have kept everything thus far.
1942 (not some-rejected
))
1944 (undo-elt-in-region undo-elt start end
)))))
1947 (setq end
(+ end
(cdr (undo-delta undo-elt
))))
1948 ;; Don't put two nils together in the list
1949 (if (not (and (eq (car undo-list
) nil
)
1951 (setq undo-list
(cons undo-elt undo-list
))))
1952 (if (undo-elt-crosses-region undo-elt start end
)
1953 (setq undo-list-copy nil
)
1954 (setq some-rejected t
)
1955 (setq temp-undo-list
(cdr undo-list-copy
))
1956 (setq delta
(undo-delta undo-elt
))
1958 (when (/= (cdr delta
) 0)
1959 (let ((position (car delta
))
1960 (offset (cdr delta
)))
1962 ;; Loop down the earlier events adjusting their buffer
1963 ;; positions to reflect the fact that a change to the buffer
1964 ;; isn't being undone. We only need to process those element
1965 ;; types which undo-elt-in-region will return as being in
1966 ;; the region since only those types can ever get into the
1969 (while temp-undo-list
1970 (setq undo-elt
(car temp-undo-list
))
1971 (cond ((integerp undo-elt
)
1972 (if (>= undo-elt position
)
1973 (setcar temp-undo-list
(- undo-elt offset
))))
1974 ((atom undo-elt
) nil
)
1975 ((stringp (car undo-elt
))
1976 ;; (TEXT . POSITION)
1977 (let ((text-pos (abs (cdr undo-elt
)))
1978 (point-at-end (< (cdr undo-elt
) 0 )))
1979 (if (>= text-pos position
)
1980 (setcdr undo-elt
(* (if point-at-end -
1 1)
1981 (- text-pos offset
))))))
1982 ((integerp (car undo-elt
))
1984 (when (>= (car undo-elt
) position
)
1985 (setcar undo-elt
(- (car undo-elt
) offset
))
1986 (setcdr undo-elt
(- (cdr undo-elt
) offset
))))
1987 ((null (car undo-elt
))
1988 ;; (nil PROPERTY VALUE BEG . END)
1989 (let ((tail (nthcdr 3 undo-elt
)))
1990 (when (>= (car tail
) position
)
1991 (setcar tail
(- (car tail
) offset
))
1992 (setcdr tail
(- (cdr tail
) offset
))))))
1993 (setq temp-undo-list
(cdr temp-undo-list
))))))))
1994 (setq undo-list-copy
(cdr undo-list-copy
)))
1995 (nreverse undo-list
)))
1997 (defun undo-elt-in-region (undo-elt start end
)
1998 "Determine whether UNDO-ELT falls inside the region START ... END.
1999 If it crosses the edge, we return nil."
2000 (cond ((integerp undo-elt
)
2001 (and (>= undo-elt start
)
2007 ((stringp (car undo-elt
))
2008 ;; (TEXT . POSITION)
2009 (and (>= (abs (cdr undo-elt
)) start
)
2010 (< (abs (cdr undo-elt
)) end
)))
2011 ((and (consp undo-elt
) (markerp (car undo-elt
)))
2012 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
2013 ;; See if MARKER is inside the region.
2014 (let ((alist-elt (assq (car undo-elt
) undo-adjusted-markers
)))
2016 (setq alist-elt
(cons (car undo-elt
)
2017 (marker-position (car undo-elt
))))
2018 (setq undo-adjusted-markers
2019 (cons alist-elt undo-adjusted-markers
)))
2020 (and (cdr alist-elt
)
2021 (>= (cdr alist-elt
) start
)
2022 (<= (cdr alist-elt
) end
))))
2023 ((null (car undo-elt
))
2024 ;; (nil PROPERTY VALUE BEG . END)
2025 (let ((tail (nthcdr 3 undo-elt
)))
2026 (and (>= (car tail
) start
)
2027 (<= (cdr tail
) end
))))
2028 ((integerp (car undo-elt
))
2030 (and (>= (car undo-elt
) start
)
2031 (<= (cdr undo-elt
) end
)))))
2033 (defun undo-elt-crosses-region (undo-elt start end
)
2034 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2035 This assumes we have already decided that UNDO-ELT
2036 is not *inside* the region START...END."
2037 (cond ((atom undo-elt
) nil
)
2038 ((null (car undo-elt
))
2039 ;; (nil PROPERTY VALUE BEG . END)
2040 (let ((tail (nthcdr 3 undo-elt
)))
2041 (and (< (car tail
) end
)
2042 (> (cdr tail
) start
))))
2043 ((integerp (car undo-elt
))
2045 (and (< (car undo-elt
) end
)
2046 (> (cdr undo-elt
) start
)))))
2048 ;; Return the first affected buffer position and the delta for an undo element
2049 ;; delta is defined as the change in subsequent buffer positions if we *did*
2051 (defun undo-delta (undo-elt)
2052 (if (consp undo-elt
)
2053 (cond ((stringp (car undo-elt
))
2054 ;; (TEXT . POSITION)
2055 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
2056 ((integerp (car undo-elt
))
2058 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
2063 (defcustom undo-ask-before-discard nil
2064 "If non-nil ask about discarding undo info for the current command.
2065 Normally, Emacs discards the undo info for the current command if
2066 it exceeds `undo-outer-limit'. But if you set this option
2067 non-nil, it asks in the echo area whether to discard the info.
2068 If you answer no, there is a slight risk that Emacs might crash, so
2069 only do it if you really want to undo the command.
2071 This option is mainly intended for debugging. You have to be
2072 careful if you use it for other purposes. Garbage collection is
2073 inhibited while the question is asked, meaning that Emacs might
2074 leak memory. So you should make sure that you do not wait
2075 excessively long before answering the question."
2080 (defvar undo-extra-outer-limit nil
2081 "If non-nil, an extra level of size that's ok in an undo item.
2082 We don't ask the user about truncating the undo list until the
2083 current item gets bigger than this amount.
2085 This variable only matters if `undo-ask-before-discard' is non-nil.")
2086 (make-variable-buffer-local 'undo-extra-outer-limit
)
2088 ;; When the first undo batch in an undo list is longer than
2089 ;; undo-outer-limit, this function gets called to warn the user that
2090 ;; the undo info for the current command was discarded. Garbage
2091 ;; collection is inhibited around the call, so it had better not do a
2093 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
2094 (defun undo-outer-limit-truncate (size)
2095 (if undo-ask-before-discard
2096 (when (or (null undo-extra-outer-limit
)
2097 (> size undo-extra-outer-limit
))
2098 ;; Don't ask the question again unless it gets even bigger.
2099 ;; This applies, in particular, if the user quits from the question.
2100 ;; Such a quit quits out of GC, but something else will call GC
2101 ;; again momentarily. It will call this function again,
2102 ;; but we don't want to ask the question again.
2103 (setq undo-extra-outer-limit
(+ size
50000))
2104 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
2105 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2106 (buffer-name) size
)))
2107 (progn (setq buffer-undo-list nil
)
2108 (setq undo-extra-outer-limit nil
)
2111 (display-warning '(undo discard-info
)
2113 (format "Buffer `%s' undo info was %d bytes long.\n"
2115 "The undo info was discarded because it exceeded \
2118 This is normal if you executed a command that made a huge change
2119 to the buffer. In that case, to prevent similar problems in the
2120 future, set `undo-outer-limit' to a value that is large enough to
2121 cover the maximum size of normal changes you expect a single
2122 command to make, but not so large that it might exceed the
2123 maximum memory allotted to Emacs.
2125 If you did not execute any such command, the situation is
2126 probably due to a bug and you should report it.
2128 You can disable the popping up of this buffer by adding the entry
2129 \(undo discard-info) to the user option `warning-suppress-types',
2130 which is defined in the `warnings' library.\n")
2132 (setq buffer-undo-list nil
)
2135 (defvar shell-command-history nil
2136 "History list for some commands that read shell commands.
2138 Maximum length of the history list is determined by the value
2139 of `history-length', which see.")
2141 (defvar shell-command-switch
(purecopy "-c")
2142 "Switch used to have the shell execute its command line argument.")
2144 (defvar shell-command-default-error-buffer nil
2145 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
2146 This buffer is used when `shell-command' or `shell-command-on-region'
2147 is run interactively. A value of nil means that output to stderr and
2148 stdout will be intermixed in the output stream.")
2150 (declare-function mailcap-file-default-commands
"mailcap" (files))
2151 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
2153 (defun minibuffer-default-add-shell-commands ()
2154 "Return a list of all commands associated with the current file.
2155 This function is used to add all related commands retrieved by `mailcap'
2156 to the end of the list of defaults just after the default value."
2158 (let* ((filename (if (listp minibuffer-default
)
2159 (car minibuffer-default
)
2160 minibuffer-default
))
2161 (commands (and filename
(require 'mailcap nil t
)
2162 (mailcap-file-default-commands (list filename
)))))
2163 (setq commands
(mapcar (lambda (command)
2164 (concat command
" " filename
))
2166 (if (listp minibuffer-default
)
2167 (append minibuffer-default commands
)
2168 (cons minibuffer-default commands
))))
2170 (defvar shell-delimiter-argument-list
)
2171 (defvar shell-file-name-chars
)
2172 (defvar shell-file-name-quote-list
)
2173 (defvar shell-dynamic-complete-functions
)
2174 ;; shell requires comint.
2175 (defvar comint-dynamic-complete-functions
)
2177 (defvar minibuffer-local-shell-command-map
2178 (let ((map (make-sparse-keymap)))
2179 (set-keymap-parent map minibuffer-local-map
)
2180 (define-key map
"\t" 'completion-at-point
)
2182 "Keymap used for completing shell commands in minibuffer.")
2184 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
2185 "Read a shell command from the minibuffer.
2186 The arguments are the same as the ones of `read-from-minibuffer',
2187 except READ and KEYMAP are missing and HIST defaults
2188 to `shell-command-history'."
2190 (minibuffer-with-setup-hook
2192 (set (make-local-variable 'comint-delimiter-argument-list
)
2193 shell-delimiter-argument-list
)
2194 (set (make-local-variable 'comint-file-name-chars
) shell-file-name-chars
)
2195 (set (make-local-variable 'comint-file-name-quote-list
)
2196 shell-file-name-quote-list
)
2197 (set (make-local-variable 'comint-dynamic-complete-functions
)
2198 shell-dynamic-complete-functions
)
2199 (add-hook 'completion-at-point-functions
2200 'comint-completion-at-point nil
'local
)
2201 (set (make-local-variable 'minibuffer-default-add-function
)
2202 'minibuffer-default-add-shell-commands
))
2203 (apply 'read-from-minibuffer prompt initial-contents
2204 minibuffer-local-shell-command-map
2206 (or hist
'shell-command-history
)
2209 (defun async-shell-command (command &optional output-buffer error-buffer
)
2210 "Execute string COMMAND asynchronously in background.
2212 Like `shell-command' but if COMMAND doesn't end in ampersand, adds `&'
2213 surrounded by whitespace and executes the command asynchronously.
2214 The output appears in the buffer `*Async Shell Command*'.
2216 In Elisp, you will often be better served by calling `start-process'
2217 directly, since it offers more control and does not impose the use of a
2218 shell (with its need to quote arguments)."
2221 (read-shell-command "Async shell command: " nil nil
2222 (and buffer-file-name
2223 (file-relative-name buffer-file-name
)))
2225 shell-command-default-error-buffer
))
2226 (unless (string-match "&[ \t]*\\'" command
)
2227 (setq command
(concat command
" &")))
2228 (shell-command command output-buffer error-buffer
))
2230 (defun shell-command (command &optional output-buffer error-buffer
)
2231 "Execute string COMMAND in inferior shell; display output, if any.
2232 With prefix argument, insert the COMMAND's output at point.
2234 If COMMAND ends in ampersand, execute it asynchronously.
2235 The output appears in the buffer `*Async Shell Command*'.
2236 That buffer is in shell mode.
2238 Otherwise, COMMAND is executed synchronously. The output appears in
2239 the buffer `*Shell Command Output*'. If the output is short enough to
2240 display in the echo area (which is determined by the variables
2241 `resize-mini-windows' and `max-mini-window-height'), it is shown
2242 there, but it is nonetheless available in buffer `*Shell Command
2243 Output*' even though that buffer is not automatically displayed.
2245 To specify a coding system for converting non-ASCII characters
2246 in the shell command output, use \\[universal-coding-system-argument] \
2247 before this command.
2249 Noninteractive callers can specify coding systems by binding
2250 `coding-system-for-read' and `coding-system-for-write'.
2252 The optional second argument OUTPUT-BUFFER, if non-nil,
2253 says to put the output in some other buffer.
2254 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2255 If OUTPUT-BUFFER is not a buffer and not nil,
2256 insert output in current buffer. (This cannot be done asynchronously.)
2257 In either case, the buffer is first erased, and the output is
2258 inserted after point (leaving mark after it).
2260 If the command terminates without error, but generates output,
2261 and you did not specify \"insert it in the current buffer\",
2262 the output can be displayed in the echo area or in its buffer.
2263 If the output is short enough to display in the echo area
2264 \(determined by the variable `max-mini-window-height' if
2265 `resize-mini-windows' is non-nil), it is shown there.
2266 Otherwise,the buffer containing the output is displayed.
2268 If there is output and an error, and you did not specify \"insert it
2269 in the current buffer\", a message about the error goes at the end
2272 If there is no output, or if output is inserted in the current buffer,
2273 then `*Shell Command Output*' is deleted.
2275 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2276 or buffer name to which to direct the command's standard error output.
2277 If it is nil, error output is mingled with regular output.
2278 In an interactive call, the variable `shell-command-default-error-buffer'
2279 specifies the value of ERROR-BUFFER.
2281 In Elisp, you will often be better served by calling `call-process' or
2282 `start-process' directly, since it offers more control and does not impose
2283 the use of a shell (with its need to quote arguments)."
2287 (read-shell-command "Shell command: " nil nil
2291 ((eq major-mode
'dired-mode
)
2292 (dired-get-filename nil t
)))))
2293 (and filename
(file-relative-name filename
))))
2295 shell-command-default-error-buffer
))
2296 ;; Look for a handler in case default-directory is a remote file name.
2298 (find-file-name-handler (directory-file-name default-directory
)
2301 (funcall handler
'shell-command command output-buffer error-buffer
)
2302 (if (and output-buffer
2303 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
2304 ;; Output goes in current buffer.
2308 (expand-file-name "scor"
2309 (or small-temporary-file-directory
2310 temporary-file-directory
)))
2312 (barf-if-buffer-read-only)
2314 ;; We do not use -f for csh; we will not support broken use of
2315 ;; .cshrcs. Even the BSD csh manual says to use
2316 ;; "if ($?prompt) exit" before things which are not useful
2317 ;; non-interactively. Besides, if someone wants their other
2318 ;; aliases for shell commands then they can still have them.
2319 (call-process shell-file-name nil
2323 nil shell-command-switch command
)
2324 (when (and error-file
(file-exists-p error-file
))
2325 (if (< 0 (nth 7 (file-attributes error-file
)))
2326 (with-current-buffer (get-buffer-create error-buffer
)
2327 (let ((pos-from-end (- (point-max) (point))))
2330 ;; Do no formatting while reading error file,
2331 ;; because that can run a shell command, and we
2332 ;; don't want that to cause an infinite recursion.
2333 (format-insert-file error-file nil
)
2334 ;; Put point after the inserted errors.
2335 (goto-char (- (point-max) pos-from-end
)))
2336 (display-buffer (current-buffer))))
2337 (delete-file error-file
))
2338 ;; This is like exchange-point-and-mark, but doesn't
2339 ;; activate the mark. It is cleaner to avoid activation,
2340 ;; even though the command loop would deactivate the mark
2341 ;; because we inserted text.
2342 (goto-char (prog1 (mark t
)
2343 (set-marker (mark-marker) (point)
2344 (current-buffer)))))
2345 ;; Output goes in a separate buffer.
2346 ;; Preserve the match data in case called from a program.
2348 (if (string-match "[ \t]*&[ \t]*\\'" command
)
2349 ;; Command ending with ampersand means asynchronous.
2350 (let ((buffer (get-buffer-create
2351 (or output-buffer
"*Async Shell Command*")))
2352 (directory default-directory
)
2354 ;; Remove the ampersand.
2355 (setq command
(substring command
0 (match-beginning 0)))
2356 ;; If will kill a process, query first.
2357 (setq proc
(get-buffer-process buffer
))
2359 (if (yes-or-no-p "A command is running. Kill it? ")
2361 (error "Shell command in progress")))
2362 (with-current-buffer buffer
2363 (setq buffer-read-only nil
)
2364 ;; Setting buffer-read-only to nil doesn't suffice
2365 ;; if some text has a non-nil read-only property,
2366 ;; which comint sometimes adds for prompts.
2367 (let ((inhibit-read-only t
))
2369 (display-buffer buffer
)
2370 (setq default-directory directory
)
2371 (setq proc
(start-process "Shell" buffer shell-file-name
2372 shell-command-switch command
))
2373 (setq mode-line-process
'(":%s"))
2374 (require 'shell
) (shell-mode)
2375 (set-process-sentinel proc
'shell-command-sentinel
)
2376 ;; Use the comint filter for proper handling of carriage motion
2377 ;; (see `comint-inhibit-carriage-motion'),.
2378 (set-process-filter proc
'comint-output-filter
)
2380 ;; Otherwise, command is executed synchronously.
2381 (shell-command-on-region (point) (point) command
2382 output-buffer nil error-buffer
)))))))
2384 (defun display-message-or-buffer (message
2385 &optional buffer-name not-this-window frame
)
2386 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2387 MESSAGE may be either a string or a buffer.
2389 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2390 the maximum height of the echo area, as defined by `max-mini-window-height'
2391 if `resize-mini-windows' is non-nil.
2393 Returns either the string shown in the echo area, or when a pop-up
2394 buffer is used, the window used to display it.
2396 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2397 name of the buffer used to display it in the case where a pop-up buffer
2398 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2399 string and it is displayed in the echo area, it is not specified whether
2400 the contents are inserted into the buffer anyway.
2402 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2403 and only used if a buffer is displayed."
2404 (cond ((and (stringp message
) (not (string-match "\n" message
)))
2405 ;; Trivial case where we can use the echo area
2406 (message "%s" message
))
2407 ((and (stringp message
)
2408 (= (string-match "\n" message
) (1- (length message
))))
2409 ;; Trivial case where we can just remove single trailing newline
2410 (message "%s" (substring message
0 (1- (length message
)))))
2413 (with-current-buffer
2414 (if (bufferp message
)
2416 (get-buffer-create (or buffer-name
"*Message*")))
2418 (unless (bufferp message
)
2423 (if (= (buffer-size) 0)
2425 (count-screen-lines nil nil nil
(minibuffer-window)))))
2427 ((and (or (<= lines
1)
2429 (if resize-mini-windows
2430 (cond ((floatp max-mini-window-height
)
2432 max-mini-window-height
))
2433 ((integerp max-mini-window-height
)
2434 max-mini-window-height
)
2438 ;; Don't use the echo area if the output buffer is
2439 ;; already dispayed in the selected frame.
2440 (not (get-buffer-window (current-buffer))))
2442 (goto-char (point-max))
2445 (message "%s" (buffer-substring (point-min) (point))))
2448 (goto-char (point-min))
2449 (display-buffer (current-buffer)
2450 not-this-window frame
))))))))
2453 ;; We have a sentinel to prevent insertion of a termination message
2454 ;; in the buffer itself.
2455 (defun shell-command-sentinel (process signal
)
2456 (if (memq (process-status process
) '(exit signal
))
2458 (car (cdr (cdr (process-command process
))))
2459 (substring signal
0 -
1))))
2461 (defun shell-command-on-region (start end command
2462 &optional output-buffer replace
2463 error-buffer display-error-buffer
)
2464 "Execute string COMMAND in inferior shell with region as input.
2465 Normally display output (if any) in temp buffer `*Shell Command Output*';
2466 Prefix arg means replace the region with it. Return the exit code of
2469 To specify a coding system for converting non-ASCII characters
2470 in the input and output to the shell command, use \\[universal-coding-system-argument]
2471 before this command. By default, the input (from the current buffer)
2472 is encoded in the same coding system that will be used to save the file,
2473 `buffer-file-coding-system'. If the output is going to replace the region,
2474 then it is decoded from that same coding system.
2476 The noninteractive arguments are START, END, COMMAND,
2477 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2478 Noninteractive callers can specify coding systems by binding
2479 `coding-system-for-read' and `coding-system-for-write'.
2481 If the command generates output, the output may be displayed
2482 in the echo area or in a buffer.
2483 If the output is short enough to display in the echo area
2484 \(determined by the variable `max-mini-window-height' if
2485 `resize-mini-windows' is non-nil), it is shown there. Otherwise
2486 it is displayed in the buffer `*Shell Command Output*'. The output
2487 is available in that buffer in both cases.
2489 If there is output and an error, a message about the error
2490 appears at the end of the output.
2492 If there is no output, or if output is inserted in the current buffer,
2493 then `*Shell Command Output*' is deleted.
2495 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2496 that says to put the output in some other buffer.
2497 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2498 If OUTPUT-BUFFER is not a buffer and not nil,
2499 insert output in the current buffer.
2500 In either case, the output is inserted after point (leaving mark after it).
2502 If REPLACE, the optional fifth argument, is non-nil, that means insert
2503 the output in place of text from START to END, putting point and mark
2506 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2507 or buffer name to which to direct the command's standard error output.
2508 If it is nil, error output is mingled with regular output.
2509 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2510 were any errors. (This is always t, interactively.)
2511 In an interactive call, the variable `shell-command-default-error-buffer'
2512 specifies the value of ERROR-BUFFER."
2513 (interactive (let (string)
2515 (error "The mark is not set now, so there is no region"))
2516 ;; Do this before calling region-beginning
2517 ;; and region-end, in case subprocess output
2518 ;; relocates them while we are in the minibuffer.
2519 (setq string
(read-shell-command "Shell command on region: "))
2520 ;; call-interactively recognizes region-beginning and
2521 ;; region-end specially, leaving them in the history.
2522 (list (region-beginning) (region-end)
2526 shell-command-default-error-buffer
2531 (expand-file-name "scor"
2532 (or small-temporary-file-directory
2533 temporary-file-directory
)))
2538 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
2539 ;; Replace specified region with output from command.
2540 (let ((swap (and replace
(< start end
))))
2541 ;; Don't muck with mark unless REPLACE says we should.
2543 (and replace
(push-mark (point) 'nomsg
))
2545 (call-process-region start end shell-file-name t
2549 nil shell-command-switch command
))
2550 ;; It is rude to delete a buffer which the command is not using.
2551 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2552 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2553 ;; (kill-buffer shell-buffer)))
2554 ;; Don't muck with mark unless REPLACE says we should.
2555 (and replace swap
(exchange-point-and-mark)))
2556 ;; No prefix argument: put the output in a temp buffer,
2557 ;; replacing its entire contents.
2558 (let ((buffer (get-buffer-create
2559 (or output-buffer
"*Shell Command Output*"))))
2561 (if (eq buffer
(current-buffer))
2562 ;; If the input is the same buffer as the output,
2563 ;; delete everything but the specified region,
2564 ;; then replace that region with the output.
2565 (progn (setq buffer-read-only nil
)
2566 (delete-region (max start end
) (point-max))
2567 (delete-region (point-min) (min start end
))
2569 (call-process-region (point-min) (point-max)
2574 nil shell-command-switch
2576 ;; Clear the output buffer, then run the command with
2578 (let ((directory default-directory
))
2579 (with-current-buffer buffer
2580 (setq buffer-read-only nil
)
2581 (if (not output-buffer
)
2582 (setq default-directory directory
))
2585 (call-process-region start end shell-file-name nil
2587 (list buffer error-file
)
2589 nil shell-command-switch command
)))
2590 ;; Report the output.
2591 (with-current-buffer buffer
2592 (setq mode-line-process
2593 (cond ((null exit-status
)
2595 ((stringp exit-status
)
2596 (format " - Signal [%s]" exit-status
))
2597 ((not (equal 0 exit-status
))
2598 (format " - Exit [%d]" exit-status
)))))
2599 (if (with-current-buffer buffer
(> (point-max) (point-min)))
2600 ;; There's some output, display it
2601 (display-message-or-buffer buffer
)
2602 ;; No output; error?
2605 (< 0 (nth 7 (file-attributes error-file
))))
2608 (cond ((null exit-status
)
2609 (message "(Shell command failed with error)"))
2610 ((equal 0 exit-status
)
2611 (message "(Shell command succeeded with %s)"
2613 ((stringp exit-status
)
2614 (message "(Shell command killed by signal %s)"
2617 (message "(Shell command failed with code %d and %s)"
2618 exit-status output
))))
2619 ;; Don't kill: there might be useful info in the undo-log.
2620 ;; (kill-buffer buffer)
2623 (when (and error-file
(file-exists-p error-file
))
2624 (if (< 0 (nth 7 (file-attributes error-file
)))
2625 (with-current-buffer (get-buffer-create error-buffer
)
2626 (let ((pos-from-end (- (point-max) (point))))
2629 ;; Do no formatting while reading error file,
2630 ;; because that can run a shell command, and we
2631 ;; don't want that to cause an infinite recursion.
2632 (format-insert-file error-file nil
)
2633 ;; Put point after the inserted errors.
2634 (goto-char (- (point-max) pos-from-end
)))
2635 (and display-error-buffer
2636 (display-buffer (current-buffer)))))
2637 (delete-file error-file
))
2640 (defun shell-command-to-string (command)
2641 "Execute shell command COMMAND and return its output as a string."
2642 (with-output-to-string
2643 (with-current-buffer
2645 (process-file shell-file-name nil t nil shell-command-switch command
))))
2647 (defun process-file (program &optional infile buffer display
&rest args
)
2648 "Process files synchronously in a separate process.
2649 Similar to `call-process', but may invoke a file handler based on
2650 `default-directory'. The current working directory of the
2651 subprocess is `default-directory'.
2653 File names in INFILE and BUFFER are handled normally, but file
2654 names in ARGS should be relative to `default-directory', as they
2655 are passed to the process verbatim. \(This is a difference to
2656 `call-process' which does not support file handlers for INFILE
2659 Some file handlers might not support all variants, for example
2660 they might behave as if DISPLAY was nil, regardless of the actual
2662 (let ((fh (find-file-name-handler default-directory
'process-file
))
2665 (if fh
(apply fh
'process-file program infile buffer display args
)
2666 (when infile
(setq lc
(file-local-copy infile
)))
2667 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
2668 (make-temp-file "emacs")))
2670 (apply 'call-process program
2672 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
2674 (when stderr-file
(copy-file stderr-file
(cadr buffer
)))))
2675 (when stderr-file
(delete-file stderr-file
))
2676 (when lc
(delete-file lc
)))))
2678 (defvar process-file-side-effects t
2679 "Whether a call of `process-file' changes remote files.
2681 Per default, this variable is always set to `t', meaning that a
2682 call of `process-file' could potentially change any file on a
2683 remote host. When set to `nil', a file handler could optimize
2684 its behaviour with respect to remote file attributes caching.
2686 This variable should never be changed by `setq'. Instead of, it
2687 shall be set only by let-binding.")
2689 (defun start-file-process (name buffer program
&rest program-args
)
2690 "Start a program in a subprocess. Return the process object for it.
2692 Similar to `start-process', but may invoke a file handler based on
2693 `default-directory'. See Info node `(elisp)Magic File Names'.
2695 This handler ought to run PROGRAM, perhaps on the local host,
2696 perhaps on a remote host that corresponds to `default-directory'.
2697 In the latter case, the local part of `default-directory' becomes
2698 the working directory of the process.
2700 PROGRAM and PROGRAM-ARGS might be file names. They are not
2701 objects of file handler invocation. File handlers might not
2702 support pty association, if PROGRAM is nil."
2703 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
2704 (if fh
(apply fh
'start-file-process name buffer program program-args
)
2705 (apply 'start-process name buffer program program-args
))))
2709 (defvar tabulated-list-format
)
2710 (defvar tabulated-list-entries
)
2711 (defvar tabulated-list-sort-key
)
2712 (declare-function tabulated-list-init-header
"tabulated-list" ())
2713 (declare-function tabulated-list-print
"tabulated-list"
2714 (&optional remember-pos
))
2716 (defvar process-menu-query-only nil
)
2718 (define-derived-mode process-menu-mode tabulated-list-mode
"Process Menu"
2719 "Major mode for listing the processes called by Emacs."
2720 (setq tabulated-list-format
[("Process" 15 t
)
2725 (make-local-variable 'process-menu-query-only
)
2726 (setq tabulated-list-sort-key
(cons "Process" nil
))
2727 (add-hook 'tabulated-list-revert-hook
'list-processes--refresh nil t
)
2728 (tabulated-list-init-header))
2730 (defun list-processes--refresh ()
2731 "Recompute the list of processes for the Process List buffer."
2732 (setq tabulated-list-entries nil
)
2733 (dolist (p (process-list))
2734 (when (or (not process-menu-query-only
)
2735 (process-query-on-exit-flag p
))
2736 (let* ((buf (process-buffer p
))
2737 (type (process-type p
))
2738 (name (process-name p
))
2739 (status (symbol-name (process-status p
)))
2740 (buf-label (if (buffer-live-p buf
)
2741 `(,(buffer-name buf
)
2743 help-echo
,(concat "Visit buffer `"
2744 (buffer-name buf
) "'")
2747 action process-menu-visit-buffer
)
2749 (tty (or (process-tty-name p
) "--"))
2751 (if (memq type
'(network serial
))
2752 (let ((contact (process-contact p t
)))
2753 (if (eq type
'network
)
2755 (if (plist-get contact
:type
)
2758 (if (plist-get contact
:server
)
2759 (format "server on %s"
2760 (plist-get contact
:server
))
2761 (format "connection to %s"
2762 (plist-get contact
:host
))))
2763 (format "(serial port %s%s)"
2764 (or (plist-get contact
:port
) "?")
2765 (let ((speed (plist-get contact
:speed
)))
2767 (format " at %s b/s" speed
)
2769 (mapconcat 'identity
(process-command p
) " "))))
2770 (push (list p
(vector name status buf-label tty cmd
))
2771 tabulated-list-entries
)))))
2773 (defun process-menu-visit-buffer (button)
2774 (display-buffer (button-get button
'process-buffer
)))
2776 (defun list-processes (&optional query-only buffer
)
2777 "Display a list of all processes.
2778 If optional argument QUERY-ONLY is non-nil, only processes with
2779 the query-on-exit flag set are listed.
2780 Any process listed as exited or signaled is actually eliminated
2781 after the listing is made.
2782 Optional argument BUFFER specifies a buffer to use, instead of
2784 The return value is always nil."
2786 (or (fboundp 'process-list
)
2787 (error "Asynchronous subprocesses are not supported on this system"))
2788 (unless (bufferp buffer
)
2789 (setq buffer
(get-buffer-create "*Process List*")))
2790 (with-current-buffer buffer
2792 (setq process-menu-query-only query-only
)
2793 (list-processes--refresh)
2794 (tabulated-list-print))
2795 (display-buffer buffer
)
2798 (defvar universal-argument-map
2799 (let ((map (make-sparse-keymap)))
2800 (define-key map
[t] 'universal-argument-other-key)
2801 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2802 (define-key map [switch-frame] nil)
2803 (define-key map [?\C-u] 'universal-argument-more)
2804 (define-key map [?-] 'universal-argument-minus)
2805 (define-key map [?0] 'digit-argument)
2806 (define-key map [?1] 'digit-argument)
2807 (define-key map [?2] 'digit-argument)
2808 (define-key map [?3] 'digit-argument)
2809 (define-key map [?4] 'digit-argument)
2810 (define-key map [?5] 'digit-argument)
2811 (define-key map [?6] 'digit-argument)
2812 (define-key map [?7] 'digit-argument)
2813 (define-key map [?8] 'digit-argument)
2814 (define-key map [?9] 'digit-argument)
2815 (define-key map [kp-0] 'digit-argument)
2816 (define-key map [kp-1] 'digit-argument)
2817 (define-key map [kp-2] 'digit-argument)
2818 (define-key map [kp-3] 'digit-argument)
2819 (define-key map [kp-4] 'digit-argument)
2820 (define-key map [kp-5] 'digit-argument)
2821 (define-key map [kp-6] 'digit-argument)
2822 (define-key map [kp-7] 'digit-argument)
2823 (define-key map [kp-8] 'digit-argument)
2824 (define-key map [kp-9] 'digit-argument)
2825 (define-key map [kp-subtract] 'universal-argument-minus)
2827 "Keymap used while processing \\[universal-argument].")
2829 (defvar universal-argument-num-events nil
2830 "Number of argument-specifying events read by `universal-argument'.
2831 `universal-argument-other-key' uses this to discard those events
2832 from (this-command-keys), and reread only the final command.")
2834 (defvar overriding-map-is-bound nil
2835 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2837 (defvar saved-overriding-map nil
2838 "The saved value of `overriding-terminal-local-map'.
2839 That variable gets restored to this value on exiting \"universal
2842 (defun ensure-overriding-map-is-bound ()
2843 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2844 (unless overriding-map-is-bound
2845 (setq saved-overriding-map overriding-terminal-local-map)
2846 (setq overriding-terminal-local-map universal-argument-map)
2847 (setq overriding-map-is-bound t)))
2849 (defun restore-overriding-map ()
2850 "Restore `overriding-terminal-local-map' to its saved value."
2851 (setq overriding-terminal-local-map saved-overriding-map)
2852 (setq overriding-map-is-bound nil))
2854 (defun universal-argument ()
2855 "Begin a numeric argument for the following command.
2856 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2857 \\[universal-argument] following the digits or minus sign ends the argument.
2858 \\[universal-argument] without digits or minus sign provides 4 as argument.
2859 Repeating \\[universal-argument] without digits or minus sign
2860 multiplies the argument by 4 each time.
2861 For some commands, just \\[universal-argument] by itself serves as a flag
2862 which is different in effect from any particular numeric argument.
2863 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2865 (setq prefix-arg (list 4))
2866 (setq universal-argument-num-events (length (this-command-keys)))
2867 (ensure-overriding-map-is-bound))
2869 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2870 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2871 (defun universal-argument-more (arg)
2874 (setq prefix-arg (list (* 4 (car arg))))
2876 (setq prefix-arg (list -4))
2877 (setq prefix-arg arg)
2878 (restore-overriding-map)))
2879 (setq universal-argument-num-events (length (this-command-keys))))
2881 (defun negative-argument (arg)
2882 "Begin a negative numeric argument for the next command.
2883 \\[universal-argument] following digits or minus sign ends the argument."
2885 (cond ((integerp arg)
2886 (setq prefix-arg (- arg)))
2888 (setq prefix-arg nil))
2890 (setq prefix-arg '-)))
2891 (setq universal-argument-num-events (length (this-command-keys)))
2892 (ensure-overriding-map-is-bound))
2894 (defun digit-argument (arg)
2895 "Part of the numeric argument for the next command.
2896 \\[universal-argument] following digits or minus sign ends the argument."
2898 (let* ((char (if (integerp last-command-event)
2900 (get last-command-event 'ascii-character)))
2901 (digit (- (logand char ?\177) ?0)))
2902 (cond ((integerp arg)
2903 (setq prefix-arg (+ (* arg 10)
2904 (if (< arg 0) (- digit) digit))))
2906 ;; Treat -0 as just -, so that -01 will work.
2907 (setq prefix-arg (if (zerop digit) '- (- digit))))
2909 (setq prefix-arg digit))))
2910 (setq universal-argument-num-events (length (this-command-keys)))
2911 (ensure-overriding-map-is-bound))
2913 ;; For backward compatibility, minus with no modifiers is an ordinary
2914 ;; command if digits have already been entered.
2915 (defun universal-argument-minus (arg)
2918 (universal-argument-other-key arg)
2919 (negative-argument arg)))
2921 ;; Anything else terminates the argument and is left in the queue to be
2922 ;; executed as a command.
2923 (defun universal-argument-other-key (arg)
2925 (setq prefix-arg arg)
2926 (let* ((key (this-command-keys))
2927 (keylist (listify-key-sequence key)))
2928 (setq unread-command-events
2929 (append (nthcdr universal-argument-num-events keylist)
2930 unread-command-events)))
2931 (reset-this-command-lengths)
2932 (restore-overriding-map))
2935 (defvar filter-buffer-substring-functions nil
2936 "Wrapper hook around `filter-buffer-substring'.
2937 The functions on this special hook are called with 4 arguments:
2938 NEXT-FUN BEG END DELETE
2939 NEXT-FUN is a function of 3 arguments (BEG END DELETE)
2940 that performs the default operation. The other 3 arguments are like
2941 the ones passed to `filter-buffer-substring'.")
2943 (defvar buffer-substring-filters nil
2944 "List of filter functions for `filter-buffer-substring'.
2945 Each function must accept a single argument, a string, and return
2946 a string. The buffer substring is passed to the first function
2947 in the list, and the return value of each function is passed to
2948 the next. The return value of the last function is used as the
2949 return value of `filter-buffer-substring'.
2951 If this variable is nil, no filtering is performed.")
2952 (make-obsolete-variable 'buffer-substring-filters
2953 'filter-buffer-substring-functions "24.1")
2955 (defun filter-buffer-substring (beg end &optional delete)
2956 "Return the buffer substring between BEG and END, after filtering.
2957 The filtering is performed by `filter-buffer-substring-functions'.
2959 If DELETE is non-nil, the text between BEG and END is deleted
2962 This function should be used instead of `buffer-substring',
2963 `buffer-substring-no-properties', or `delete-and-extract-region'
2964 when you want to allow filtering to take place. For example,
2965 major or minor modes can use `filter-buffer-substring-functions' to
2966 extract characters that are special to a buffer, and should not
2967 be copied into other buffers."
2968 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
2970 ((or delete buffer-substring-filters)
2973 (let ((string (if delete (delete-and-extract-region beg end)
2974 (buffer-substring beg end))))
2975 (dolist (filter buffer-substring-filters)
2976 (setq string (funcall filter string)))
2979 (buffer-substring beg end)))))
2982 ;;;; Window system cut and paste hooks.
2984 (defvar interprogram-cut-function nil
2985 "Function to call to make a killed region available to other programs.
2987 Most window systems provide some sort of facility for cutting and
2988 pasting text between the windows of different programs.
2989 This variable holds a function that Emacs calls whenever text
2990 is put in the kill ring, to make the new kill available to other
2993 The function takes one argument, TEXT, which is a string containing
2994 the text which should be made available.")
2996 (defvar interprogram-paste-function nil
2997 "Function to call to get text cut from other programs.
2999 Most window systems provide some sort of facility for cutting and
3000 pasting text between the windows of different programs.
3001 This variable holds a function that Emacs calls to obtain
3002 text that other programs have provided for pasting.
3004 The function should be called with no arguments. If the function
3005 returns nil, then no other program has provided such text, and the top
3006 of the Emacs kill ring should be used. If the function returns a
3007 string, then the caller of the function \(usually `current-kill')
3008 should put this string in the kill ring as the latest kill.
3010 This function may also return a list of strings if the window
3011 system supports multiple selections. The first string will be
3012 used as the pasted text, but the other will be placed in the
3013 kill ring for easy access via `yank-pop'.
3015 Note that the function should return a string only if a program other
3016 than Emacs has provided a string for pasting; if Emacs provided the
3017 most recent string, the function should return nil. If it is
3018 difficult to tell whether Emacs or some other program provided the
3019 current string, it is probably good enough to return nil if the string
3020 is equal (according to `string=') to the last text Emacs provided.")
3024 ;;;; The kill ring data structure.
3026 (defvar kill-ring nil
3027 "List of killed text sequences.
3028 Since the kill ring is supposed to interact nicely with cut-and-paste
3029 facilities offered by window systems, use of this variable should
3030 interact nicely with `interprogram-cut-function' and
3031 `interprogram-paste-function'. The functions `kill-new',
3032 `kill-append', and `current-kill' are supposed to implement this
3033 interaction; you may want to use them instead of manipulating the kill
3036 (defcustom kill-ring-max 60
3037 "Maximum length of kill ring before oldest elements are thrown away."
3041 (defvar kill-ring-yank-pointer nil
3042 "The tail of the kill ring whose car is the last thing yanked.")
3044 (defcustom save-interprogram-paste-before-kill nil
3045 "Save clipboard strings into kill ring before replacing them.
3046 When one selects something in another program to paste it into Emacs,
3047 but kills something in Emacs before actually pasting it,
3048 this selection is gone unless this variable is non-nil,
3049 in which case the other program's selection is saved in the `kill-ring'
3050 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3055 (defcustom kill-do-not-save-duplicates nil
3056 "Do not add a new string to `kill-ring' when it is the same as the last one."
3061 (defun kill-new (string &optional replace yank-handler)
3062 "Make STRING the latest kill in the kill ring.
3063 Set `kill-ring-yank-pointer' to point to it.
3064 If `interprogram-cut-function' is non-nil, apply it to STRING.
3065 Optional second argument REPLACE non-nil means that STRING will replace
3066 the front of the kill ring, rather than being added to the list.
3068 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3069 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3072 When the yank handler has a non-nil PARAM element, the original STRING
3073 argument is not used by `insert-for-yank'. However, since Lisp code
3074 may access and use elements from the kill ring directly, the STRING
3075 argument should still be a \"useful\" string for such uses."
3076 (if (> (length string) 0)
3078 (put-text-property 0 (length string)
3079 'yank-handler yank-handler string))
3081 (signal 'args-out-of-range
3082 (list string "yank-handler specified for empty string"))))
3083 (unless (and kill-do-not-save-duplicates
3084 (equal string (car kill-ring)))
3085 (if (fboundp 'menu-bar-update-yank-menu)
3086 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
3087 (when save-interprogram-paste-before-kill
3088 (let ((interprogram-paste (and interprogram-paste-function
3089 (funcall interprogram-paste-function))))
3090 (when interprogram-paste
3091 (dolist (s (if (listp interprogram-paste)
3092 (nreverse interprogram-paste)
3093 (list interprogram-paste)))
3094 (unless (and kill-do-not-save-duplicates
3095 (equal s (car kill-ring)))
3096 (push s kill-ring))))))
3097 (unless (and kill-do-not-save-duplicates
3098 (equal string (car kill-ring)))
3099 (if (and replace kill-ring)
3100 (setcar kill-ring string)
3101 (push string kill-ring)
3102 (if (> (length kill-ring) kill-ring-max)
3103 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
3104 (setq kill-ring-yank-pointer kill-ring)
3105 (if interprogram-cut-function
3106 (funcall interprogram-cut-function string)))
3107 (set-advertised-calling-convention
3108 'kill-new '(string &optional replace) "23.3")
3110 (defun kill-append (string before-p &optional yank-handler)
3111 "Append STRING to the end of the latest kill in the kill ring.
3112 If BEFORE-P is non-nil, prepend STRING to the kill.
3113 If `interprogram-cut-function' is set, pass the resulting kill to it."
3114 (let* ((cur (car kill-ring)))
3115 (kill-new (if before-p (concat string cur) (concat cur string))
3116 (or (= (length cur) 0)
3117 (equal yank-handler (get-text-property 0 'yank-handler cur)))
3119 (set-advertised-calling-convention 'kill-append '(string before-p) "23.3")
3121 (defcustom yank-pop-change-selection nil
3122 "If non-nil, rotating the kill ring changes the window system selection."
3127 (defun current-kill (n &optional do-not-move)
3128 "Rotate the yanking point by N places, and then return that kill.
3129 If N is zero, `interprogram-paste-function' is set, and calling
3130 it returns a string or list of strings, then that string (or
3131 list) is added to the front of the kill ring and the string (or
3132 first string in the list) is returned as the latest kill.
3134 If N is not zero, and if `yank-pop-change-selection' is
3135 non-nil, use `interprogram-cut-function' to transfer the
3136 kill at the new yank point into the window system selection.
3138 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3139 move the yanking point; just return the Nth kill forward."
3141 (let ((interprogram-paste (and (= n 0)
3142 interprogram-paste-function
3143 (funcall interprogram-paste-function))))
3144 (if interprogram-paste
3146 ;; Disable the interprogram cut function when we add the new
3147 ;; text to the kill ring, so Emacs doesn't try to own the
3148 ;; selection, with identical text.
3149 (let ((interprogram-cut-function nil))
3150 (if (listp interprogram-paste)
3151 (mapc 'kill-new (nreverse interprogram-paste))
3152 (kill-new interprogram-paste)))
3154 (or kill-ring (error "Kill ring is empty"))
3155 (let ((ARGth-kill-element
3156 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3160 (setq kill-ring-yank-pointer ARGth-kill-element)
3161 (when (and yank-pop-change-selection
3163 interprogram-cut-function)
3164 (funcall interprogram-cut-function (car ARGth-kill-element))))
3165 (car ARGth-kill-element)))))
3169 ;;;; Commands for manipulating the kill ring.
3171 (defcustom kill-read-only-ok nil
3172 "Non-nil means don't signal an error for killing read-only text."
3176 (put 'text-read-only 'error-conditions
3177 '(text-read-only buffer-read-only error))
3178 (put 'text-read-only 'error-message (purecopy "Text is read-only"))
3180 (defun kill-region (beg end &optional yank-handler)
3181 "Kill (\"cut\") text between point and mark.
3182 This deletes the text from the buffer and saves it in the kill ring.
3183 The command \\[yank] can retrieve it from there.
3184 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3186 If you want to append the killed region to the last killed text,
3187 use \\[append-next-kill] before \\[kill-region].
3189 If the buffer is read-only, Emacs will beep and refrain from deleting
3190 the text, but put the text in the kill ring anyway. This means that
3191 you can use the killing commands to copy text from a read-only buffer.
3193 Lisp programs should use this function for killing text.
3194 (To delete text, use `delete-region'.)
3195 Supply two arguments, character positions indicating the stretch of text
3197 Any command that calls this function is a \"kill command\".
3198 If the previous command was also a kill command,
3199 the text killed this time appends to the text killed last time
3200 to make one entry in the kill ring."
3201 ;; Pass point first, then mark, because the order matters
3202 ;; when calling kill-append.
3203 (interactive (list (point) (mark)))
3204 (unless (and beg end)
3205 (error "The mark is not set now, so there is no region"))
3207 (let ((string (filter-buffer-substring beg end t)))
3208 (when string ;STRING is nil if BEG = END
3209 ;; Add that string to the kill ring, one way or another.
3210 (if (eq last-command 'kill-region)
3211 (kill-append string (< end beg) yank-handler)
3212 (kill-new string nil yank-handler)))
3213 (when (or string (eq last-command 'kill-region))
3214 (setq this-command 'kill-region))
3216 ((buffer-read-only text-read-only)
3217 ;; The code above failed because the buffer, or some of the characters
3218 ;; in the region, are read-only.
3219 ;; We should beep, in case the user just isn't aware of this.
3220 ;; However, there's no harm in putting
3221 ;; the region's text in the kill ring, anyway.
3222 (copy-region-as-kill beg end)
3223 ;; Set this-command now, so it will be set even if we get an error.
3224 (setq this-command 'kill-region)
3225 ;; This should barf, if appropriate, and give us the correct error.
3226 (if kill-read-only-ok
3227 (progn (message "Read only text copied to kill ring") nil)
3228 ;; Signal an error if the buffer is read-only.
3229 (barf-if-buffer-read-only)
3230 ;; If the buffer isn't read-only, the text is.
3231 (signal 'text-read-only (list (current-buffer)))))))
3232 (set-advertised-calling-convention 'kill-region '(beg end) "23.3")
3234 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3235 ;; to get two copies of the text when the user accidentally types M-w and
3236 ;; then corrects it with the intended C-w.
3237 (defun copy-region-as-kill (beg end)
3238 "Save the region as if killed, but don't kill it.
3239 In Transient Mark mode, deactivate the mark.
3240 If `interprogram-cut-function' is non-nil, also save the text for a window
3241 system cut and paste.
3243 This command's old key binding has been given to `kill-ring-save'."
3245 (if (eq last-command 'kill-region)
3246 (kill-append (filter-buffer-substring beg end) (< end beg))
3247 (kill-new (filter-buffer-substring beg end)))
3248 (setq deactivate-mark t)
3251 (defun kill-ring-save (beg end)
3252 "Save the region as if killed, but don't kill it.
3253 In Transient Mark mode, deactivate the mark.
3254 If `interprogram-cut-function' is non-nil, also save the text for a window
3255 system cut and paste.
3257 If you want to append the killed line to the last killed text,
3258 use \\[append-next-kill] before \\[kill-ring-save].
3260 This command is similar to `copy-region-as-kill', except that it gives
3261 visual feedback indicating the extent of the region being copied."
3263 (copy-region-as-kill beg end)
3264 ;; This use of called-interactively-p is correct
3265 ;; because the code it controls just gives the user visual feedback.
3266 (if (called-interactively-p 'interactive)
3267 (let ((other-end (if (= (point) beg) end beg))
3269 ;; Inhibit quitting so we can make a quit here
3270 ;; look like a C-g typed as a command.
3272 (if (pos-visible-in-window-p other-end (selected-window))
3273 ;; Swap point-and-mark quickly so as to show the region that
3274 ;; was selected. Don't do it if the region is highlighted.
3275 (unless (and (region-active-p)
3276 (face-background 'region))
3277 ;; Swap point and mark.
3278 (set-marker (mark-marker) (point) (current-buffer))
3279 (goto-char other-end)
3280 (sit-for blink-matching-delay)
3282 (set-marker (mark-marker) other-end (current-buffer))
3284 ;; If user quit, deactivate the mark
3285 ;; as C-g would as a command.
3286 (and quit-flag mark-active
3288 (let* ((killed-text (current-kill 0))
3289 (message-len (min (length killed-text) 40)))
3291 ;; Don't say "killed"; that is misleading.
3292 (message "Saved text until \"%s\""
3293 (substring killed-text (- message-len)))
3294 (message "Saved text from \"%s\""
3295 (substring killed-text 0 message-len))))))))
3297 (defun append-next-kill (&optional interactive)
3298 "Cause following command, if it kills, to append to previous kill.
3299 The argument is used for internal purposes; do not supply one."
3301 ;; We don't use (interactive-p), since that breaks kbd macros.
3304 (setq this-command 'kill-region)
3305 (message "If the next command is a kill, it will append"))
3306 (setq last-command 'kill-region)))
3310 ;; This is actually used in subr.el but defcustom does not work there.
3311 (defcustom yank-excluded-properties
3312 '(read-only invisible intangible field mouse-face help-echo local-map keymap
3313 yank-handler follow-link fontified)
3314 "Text properties to discard when yanking.
3315 The value should be a list of text properties to discard or t,
3316 which means to discard all text properties."
3317 :type '(choice (const :tag "All" t) (repeat symbol))
3321 (defvar yank-window-start nil)
3322 (defvar yank-undo-function nil
3323 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3324 Function is called with two parameters, START and END corresponding to
3325 the value of the mark and point; it is guaranteed that START <= END.
3326 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3328 (defun yank-pop (&optional arg)
3329 "Replace just-yanked stretch of killed text with a different stretch.
3330 This command is allowed only immediately after a `yank' or a `yank-pop'.
3331 At such a time, the region contains a stretch of reinserted
3332 previously-killed text. `yank-pop' deletes that text and inserts in its
3333 place a different stretch of killed text.
3335 With no argument, the previous kill is inserted.
3336 With argument N, insert the Nth previous kill.
3337 If N is negative, this is a more recent kill.
3339 The sequence of kills wraps around, so that after the oldest one
3340 comes the newest one.
3342 When this command inserts killed text into the buffer, it honors
3343 `yank-excluded-properties' and `yank-handler' as described in the
3344 doc string for `insert-for-yank-1', which see."
3346 (if (not (eq last-command 'yank))
3347 (error "Previous command was not a yank"))
3348 (setq this-command 'yank)
3349 (unless arg (setq arg 1))
3350 (let ((inhibit-read-only t)
3351 (before (< (point) (mark t))))
3353 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3354 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
3355 (setq yank-undo-function nil)
3356 (set-marker (mark-marker) (point) (current-buffer))
3357 (insert-for-yank (current-kill arg))
3358 ;; Set the window start back where it was in the yank command,
3360 (set-window-start (selected-window) yank-window-start t)
3362 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3363 ;; It is cleaner to avoid activation, even though the command
3364 ;; loop would deactivate the mark because we inserted text.
3365 (goto-char (prog1 (mark t)
3366 (set-marker (mark-marker) (point) (current-buffer))))))
3369 (defun yank (&optional arg)
3370 "Reinsert (\"paste\") the last stretch of killed text.
3371 More precisely, reinsert the stretch of killed text most recently
3372 killed OR yanked. Put point at end, and set mark at beginning.
3373 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
3374 With argument N, reinsert the Nth most recently killed stretch of killed
3377 When this command inserts killed text into the buffer, it honors
3378 `yank-excluded-properties' and `yank-handler' as described in the
3379 doc string for `insert-for-yank-1', which see.
3381 See also the command `yank-pop' (\\[yank-pop])."
3383 (setq yank-window-start (window-start))
3384 ;; If we don't get all the way thru, make last-command indicate that
3385 ;; for the following command.
3386 (setq this-command t)
3388 (insert-for-yank (current-kill (cond
3393 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3394 ;; It is cleaner to avoid activation, even though the command
3395 ;; loop would deactivate the mark because we inserted text.
3396 (goto-char (prog1 (mark t)
3397 (set-marker (mark-marker) (point) (current-buffer)))))
3398 ;; If we do get all the way thru, make this-command indicate that.
3399 (if (eq this-command t)
3400 (setq this-command 'yank))
3403 (defun rotate-yank-pointer (arg)
3404 "Rotate the yanking point in the kill ring.
3405 With ARG, rotate that many kills forward (or backward, if negative)."
3409 ;; Some kill commands.
3411 ;; Internal subroutine of delete-char
3412 (defun kill-forward-chars (arg)
3413 (if (listp arg) (setq arg (car arg)))
3414 (if (eq arg '-) (setq arg -1))
3415 (kill-region (point) (+ (point) arg)))
3417 ;; Internal subroutine of backward-delete-char
3418 (defun kill-backward-chars (arg)
3419 (if (listp arg) (setq arg (car arg)))
3420 (if (eq arg '-) (setq arg -1))
3421 (kill-region (point) (- (point) arg)))
3423 (defcustom backward-delete-char-untabify-method 'untabify
3424 "The method for untabifying when deleting backward.
3425 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3426 `hungry' -- delete all whitespace, both tabs and spaces;
3427 `all' -- delete all whitespace, including tabs, spaces and newlines;
3428 nil -- just delete one character."
3429 :type '(choice (const untabify) (const hungry) (const all) (const nil))
3433 (defun backward-delete-char-untabify (arg &optional killp)
3434 "Delete characters backward, changing tabs into spaces.
3435 The exact behavior depends on `backward-delete-char-untabify-method'.
3436 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3437 Interactively, ARG is the prefix arg (default 1)
3438 and KILLP is t if a prefix arg was specified."
3439 (interactive "*p\nP")
3440 (when (eq backward-delete-char-untabify-method 'untabify)
3443 (while (and (> count 0) (not (bobp)))
3444 (if (= (preceding-char) ?\t)
3445 (let ((col (current-column)))
3447 (setq col (- col (current-column)))
3448 (insert-char ?\s col)
3451 (setq count (1- count))))))
3452 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3453 ((eq backward-delete-char-untabify-method 'all)
3456 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
3458 (+ arg (if (zerop wh) 0 (1- wh))))
3460 ;; Avoid warning about delete-backward-char
3461 (with-no-warnings (delete-backward-char n killp))))
3463 (defun zap-to-char (arg char)
3464 "Kill up to and including ARGth occurrence of CHAR.
3465 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3466 Goes backward if ARG is negative; error if CHAR not found."
3467 (interactive "p\ncZap to char: ")
3468 ;; Avoid "obsolete" warnings for translation-table-for-input.
3470 (if (char-table-p translation-table-for-input)
3471 (setq char (or (aref translation-table-for-input char) char))))
3472 (kill-region (point) (progn
3473 (search-forward (char-to-string char) nil nil arg)
3474 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3477 ;; kill-line and its subroutines.
3479 (defcustom kill-whole-line nil
3480 "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
3484 (defun kill-line (&optional arg)
3485 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3486 With prefix argument ARG, kill that many lines from point.
3487 Negative arguments kill lines backward.
3488 With zero argument, kills the text before point on the current line.
3490 When calling from a program, nil means \"no arg\",
3491 a number counts as a prefix arg.
3493 To kill a whole line, when point is not at the beginning, type \
3494 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3496 If `kill-whole-line' is non-nil, then this command kills the whole line
3497 including its terminating newline, when used at the beginning of a line
3498 with no argument. As a consequence, you can always kill a whole line
3499 by typing \\[move-beginning-of-line] \\[kill-line].
3501 If you want to append the killed line to the last killed text,
3502 use \\[append-next-kill] before \\[kill-line].
3504 If the buffer is read-only, Emacs will beep and refrain from deleting
3505 the line, but put the line in the kill ring anyway. This means that
3506 you can use this command to copy text from a read-only buffer.
3507 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3510 (kill-region (point)
3511 ;; It is better to move point to the other end of the kill
3512 ;; before killing. That way, in a read-only buffer, point
3513 ;; moves across the text that is copied to the kill ring.
3514 ;; The choice has no effect on undo now that undo records
3515 ;; the value of point from before the command was run.
3518 (forward-visible-line (prefix-numeric-value arg))
3520 (signal 'end-of-buffer nil))
3523 (end-of-visible-line) (point))))
3524 (if (or (save-excursion
3525 ;; If trailing whitespace is visible,
3526 ;; don't treat it as nothing.
3527 (unless show-trailing-whitespace
3528 (skip-chars-forward " \t" end))
3530 (and kill-whole-line (bolp)))
3531 (forward-visible-line 1)
3535 (defun kill-whole-line (&optional arg)
3537 With prefix ARG, kill that many lines starting from the current line.
3538 If ARG is negative, kill backward. Also kill the preceding newline.
3539 \(This is meant to make \\[repeat] work well with negative arguments.\)
3540 If ARG is zero, kill current line but exclude the trailing newline."
3542 (or arg (setq arg 1))
3543 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3544 (signal 'end-of-buffer nil))
3545 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3546 (signal 'beginning-of-buffer nil))
3547 (unless (eq last-command 'kill-region)
3549 (setq last-command 'kill-region))
3551 ;; We need to kill in two steps, because the previous command
3552 ;; could have been a kill command, in which case the text
3553 ;; before point needs to be prepended to the current kill
3554 ;; ring entry and the text after point appended. Also, we
3555 ;; need to use save-excursion to avoid copying the same text
3556 ;; twice to the kill ring in read-only buffers.
3558 (kill-region (point) (progn (forward-visible-line 0) (point))))
3559 (kill-region (point) (progn (end-of-visible-line) (point))))
3562 (kill-region (point) (progn (end-of-visible-line) (point))))
3563 (kill-region (point)
3564 (progn (forward-visible-line (1+ arg))
3565 (unless (bobp) (backward-char))
3569 (kill-region (point) (progn (forward-visible-line 0) (point))))
3570 (kill-region (point)
3571 (progn (forward-visible-line arg) (point))))))
3573 (defun forward-visible-line (arg)
3574 "Move forward by ARG lines, ignoring currently invisible newlines only.
3575 If ARG is negative, move backward -ARG lines.
3576 If ARG is zero, move to the beginning of the current line."
3581 (or (zerop (forward-line 1))
3582 (signal 'end-of-buffer nil))
3583 ;; If the newline we just skipped is invisible,
3586 (get-char-property (1- (point)) 'invisible)))
3587 (if (if (eq buffer-invisibility-spec t)
3589 (or (memq prop buffer-invisibility-spec)
3590 (assq prop buffer-invisibility-spec)))
3591 (setq arg (1+ arg))))
3592 (setq arg (1- arg)))
3593 ;; If invisible text follows, and it is a number of complete lines,
3595 (let ((opoint (point)))
3596 (while (and (not (eobp))
3598 (get-char-property (point) 'invisible)))
3599 (if (eq buffer-invisibility-spec t)
3601 (or (memq prop buffer-invisibility-spec)
3602 (assq prop buffer-invisibility-spec)))))
3604 (if (get-text-property (point) 'invisible)
3605 (or (next-single-property-change (point) 'invisible)
3607 (next-overlay-change (point)))))
3609 (goto-char opoint))))
3611 (while (or first (<= arg 0))
3614 (or (zerop (forward-line -1))
3615 (signal 'beginning-of-buffer nil)))
3616 ;; If the newline we just moved to is invisible,
3620 (get-char-property (1- (point)) 'invisible)))
3621 (unless (if (eq buffer-invisibility-spec t)
3623 (or (memq prop buffer-invisibility-spec)
3624 (assq prop buffer-invisibility-spec)))
3625 (setq arg (1+ arg)))))
3627 ;; If invisible text follows, and it is a number of complete lines,
3629 (let ((opoint (point)))
3630 (while (and (not (bobp))
3632 (get-char-property (1- (point)) 'invisible)))
3633 (if (eq buffer-invisibility-spec t)
3635 (or (memq prop buffer-invisibility-spec)
3636 (assq prop buffer-invisibility-spec)))))
3638 (if (get-text-property (1- (point)) 'invisible)
3639 (or (previous-single-property-change (point) 'invisible)
3641 (previous-overlay-change (point)))))
3643 (goto-char opoint)))))
3644 ((beginning-of-buffer end-of-buffer)
3647 (defun end-of-visible-line ()
3648 "Move to end of current visible line."
3650 ;; If the following character is currently invisible,
3651 ;; skip all characters with that same `invisible' property value,
3652 ;; then find the next newline.
3653 (while (and (not (eobp))
3655 (skip-chars-forward "^\n")
3657 (get-char-property (point) 'invisible)))
3658 (if (eq buffer-invisibility-spec t)
3660 (or (memq prop buffer-invisibility-spec)
3661 (assq prop buffer-invisibility-spec))))))
3662 (skip-chars-forward "^\n")
3663 (if (get-text-property (point) 'invisible)
3664 (goto-char (next-single-property-change (point) 'invisible))
3665 (goto-char (next-overlay-change (point))))
3668 (defun insert-buffer (buffer)
3669 "Insert after point the contents of BUFFER.
3670 Puts mark after the inserted text.
3671 BUFFER may be a buffer or a buffer name.
3673 This function is meant for the user to run interactively.
3674 Don't call it from programs: use `insert-buffer-substring' instead!"
3678 (barf-if-buffer-read-only)
3679 (read-buffer "Insert buffer: "
3680 (if (eq (selected-window) (next-window (selected-window)))
3681 (other-buffer (current-buffer))
3682 (window-buffer (next-window (selected-window))))
3686 (insert-buffer-substring (get-buffer buffer))
3690 (defun append-to-buffer (buffer start end)
3691 "Append to specified buffer the text of the region.
3692 It is inserted into that buffer before its point.
3694 When calling from a program, give three arguments:
3695 BUFFER (or buffer name), START and END.
3696 START and END specify the portion of the current buffer to be copied."
3698 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3699 (region-beginning) (region-end)))
3700 (let* ((oldbuf (current-buffer))
3701 (append-to (get-buffer-create buffer))
3702 (windows (get-buffer-window-list append-to t t))
3705 (with-current-buffer append-to
3706 (setq point (point))
3707 (barf-if-buffer-read-only)
3708 (insert-buffer-substring oldbuf start end)
3709 (dolist (window windows)
3710 (when (= (window-point window) point)
3711 (set-window-point window (point))))))))
3713 (defun prepend-to-buffer (buffer start end)
3714 "Prepend to specified buffer the text of the region.
3715 It is inserted into that buffer after its point.
3717 When calling from a program, give three arguments:
3718 BUFFER (or buffer name), START and END.
3719 START and END specify the portion of the current buffer to be copied."
3720 (interactive "BPrepend to buffer: \nr")
3721 (let ((oldbuf (current-buffer)))
3722 (with-current-buffer (get-buffer-create buffer)
3723 (barf-if-buffer-read-only)
3725 (insert-buffer-substring oldbuf start end)))))
3727 (defun copy-to-buffer (buffer start end)
3728 "Copy to specified buffer the text of the region.
3729 It is inserted into that buffer, replacing existing text there.
3731 When calling from a program, give three arguments:
3732 BUFFER (or buffer name), START and END.
3733 START and END specify the portion of the current buffer to be copied."
3734 (interactive "BCopy to buffer: \nr")
3735 (let ((oldbuf (current-buffer)))
3736 (with-current-buffer (get-buffer-create buffer)
3737 (barf-if-buffer-read-only)
3740 (insert-buffer-substring oldbuf start end)))))
3742 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3743 (put 'mark-inactive 'error-message (purecopy "The mark is not active now"))
3745 (defvar activate-mark-hook nil
3746 "Hook run when the mark becomes active.
3747 It is also run at the end of a command, if the mark is active and
3748 it is possible that the region may have changed.")
3750 (defvar deactivate-mark-hook nil
3751 "Hook run when the mark becomes inactive.")
3753 (defun mark (&optional force)
3754 "Return this buffer's mark value as integer, or nil if never set.
3756 In Transient Mark mode, this function signals an error if
3757 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3758 or the argument FORCE is non-nil, it disregards whether the mark
3759 is active, and returns an integer or nil in the usual way.
3761 If you are using this in an editing command, you are most likely making
3762 a mistake; see the documentation of `set-mark'."
3763 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3764 (marker-position (mark-marker))
3765 (signal 'mark-inactive nil)))
3767 (defsubst deactivate-mark (&optional force)
3768 "Deactivate the mark by setting `mark-active' to nil.
3769 Unless FORCE is non-nil, this function does nothing if Transient
3770 Mark mode is disabled.
3771 This function also runs `deactivate-mark-hook'."
3772 (when (or transient-mark-mode force)
3773 (when (and (if (eq select-active-regions 'only)
3774 (eq (car-safe transient-mark-mode) 'only)
3775 select-active-regions)
3777 (display-selections-p))
3778 ;; The var `saved-region-selection', if non-nil, is the text in
3779 ;; the region prior to the last command modifying the buffer.
3780 ;; Set the selection to that, or to the current region.
3781 (cond (saved-region-selection
3782 (x-set-selection 'PRIMARY saved-region-selection)
3783 (setq saved-region-selection nil))
3784 ((/= (region-beginning) (region-end))
3785 (x-set-selection 'PRIMARY
3786 (buffer-substring-no-properties
3789 (if (and (null force)
3790 (or (eq transient-mark-mode 'lambda)
3791 (and (eq (car-safe transient-mark-mode) 'only)
3792 (null (cdr transient-mark-mode)))))
3793 ;; When deactivating a temporary region, don't change
3794 ;; `mark-active' or run `deactivate-mark-hook'.
3795 (setq transient-mark-mode nil)
3796 (if (eq (car-safe transient-mark-mode) 'only)
3797 (setq transient-mark-mode (cdr transient-mark-mode)))
3798 (setq mark-active nil)
3799 (run-hooks 'deactivate-mark-hook))))
3801 (defun activate-mark ()
3802 "Activate the mark."
3804 (setq mark-active t)
3805 (unless transient-mark-mode
3806 (setq transient-mark-mode 'lambda))))
3808 (defun set-mark (pos)
3809 "Set this buffer's mark to POS. Don't use this function!
3810 That is to say, don't use this function unless you want
3811 the user to see that the mark has moved, and you want the previous
3812 mark position to be lost.
3814 Normally, when a new mark is set, the old one should go on the stack.
3815 This is why most applications should use `push-mark', not `set-mark'.
3817 Novice Emacs Lisp programmers often try to use the mark for the wrong
3818 purposes. The mark saves a location for the user's convenience.
3819 Most editing commands should not alter the mark.
3820 To remember a location for internal use in the Lisp program,
3821 store it in a Lisp variable. Example:
3823 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3827 (setq mark-active t)
3828 (run-hooks 'activate-mark-hook)
3829 (set-marker (mark-marker) pos (current-buffer)))
3830 ;; Normally we never clear mark-active except in Transient Mark mode.
3831 ;; But when we actually clear out the mark value too, we must
3832 ;; clear mark-active in any mode.
3834 (set-marker (mark-marker) nil)))
3836 (defcustom use-empty-active-region nil
3837 "Whether \"region-aware\" commands should act on empty regions.
3838 If nil, region-aware commands treat empty regions as inactive.
3839 If non-nil, region-aware commands treat the region as active as
3840 long as the mark is active, even if the region is empty.
3842 Region-aware commands are those that act on the region if it is
3843 active and Transient Mark mode is enabled, and on the text near
3847 :group 'editing-basics)
3849 (defun use-region-p ()
3850 "Return t if the region is active and it is appropriate to act on it.
3851 This is used by commands that act specially on the region under
3852 Transient Mark mode.
3854 The return value is t if Transient Mark mode is enabled and the
3855 mark is active; furthermore, if `use-empty-active-region' is nil,
3856 the region must not be empty. Otherwise, the return value is nil.
3858 For some commands, it may be appropriate to ignore the value of
3859 `use-empty-active-region'; in that case, use `region-active-p'."
3860 (and (region-active-p)
3861 (or use-empty-active-region (> (region-end) (region-beginning)))))
3863 (defun region-active-p ()
3864 "Return t if Transient Mark mode is enabled and the mark is active.
3866 Some commands act specially on the region when Transient Mark
3867 mode is enabled. Usually, such commands should use
3868 `use-region-p' instead of this function, because `use-region-p'
3869 also checks the value of `use-empty-active-region'."
3870 (and transient-mark-mode mark-active))
3872 (defvar mark-ring nil
3873 "The list of former marks of the current buffer, most recent first.")
3874 (make-variable-buffer-local 'mark-ring)
3875 (put 'mark-ring 'permanent-local t)
3877 (defcustom mark-ring-max 16
3878 "Maximum size of mark ring. Start discarding off end if gets this big."
3880 :group 'editing-basics)
3882 (defvar global-mark-ring nil
3883 "The list of saved global marks, most recent first.")
3885 (defcustom global-mark-ring-max 16
3886 "Maximum size of global mark ring. \
3887 Start discarding off end if gets this big."
3889 :group 'editing-basics)
3891 (defun pop-to-mark-command ()
3892 "Jump to mark, and pop a new position for mark off the ring.
3893 \(Does not affect global mark ring\)."
3896 (error "No mark set in this buffer")
3897 (if (= (point) (mark t))
3898 (message "Mark popped"))
3899 (goto-char (mark t))
3902 (defun push-mark-command (arg &optional nomsg)
3903 "Set mark at where point is.
3904 If no prefix ARG and mark is already set there, just activate it.
3905 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3907 (let ((mark (marker-position (mark-marker))))
3908 (if (or arg (null mark) (/= mark (point)))
3909 (push-mark nil nomsg t)
3910 (setq mark-active t)
3911 (run-hooks 'activate-mark-hook)
3913 (message "Mark activated")))))
3915 (defcustom set-mark-command-repeat-pop nil
3916 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3917 That means that C-u \\[set-mark-command] \\[set-mark-command]
3918 will pop the mark twice, and
3919 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3920 will pop the mark three times.
3922 A value of nil means \\[set-mark-command]'s behavior does not change
3923 after C-u \\[set-mark-command]."
3925 :group 'editing-basics)
3927 (defcustom set-mark-default-inactive nil
3928 "If non-nil, setting the mark does not activate it.
3929 This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
3930 behave the same whether or not `transient-mark-mode' is enabled."
3932 :group 'editing-basics
3935 (defun set-mark-command (arg)
3936 "Set the mark where point is, or jump to the mark.
3937 Setting the mark also alters the region, which is the text
3938 between point and mark; this is the closest equivalent in
3939 Emacs to what some editors call the \"selection\".
3941 With no prefix argument, set the mark at point, and push the
3942 old mark position on local mark ring. Also push the old mark on
3943 global mark ring, if the previous mark was set in another buffer.
3945 When Transient Mark Mode is off, immediately repeating this
3946 command activates `transient-mark-mode' temporarily.
3948 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3949 jump to the mark, and set the mark from
3950 position popped off the local mark ring \(this does not affect the global
3951 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3952 mark ring \(see `pop-global-mark'\).
3954 If `set-mark-command-repeat-pop' is non-nil, repeating
3955 the \\[set-mark-command] command with no prefix argument pops the next position
3956 off the local (or global) mark ring and jumps there.
3958 With \\[universal-argument] \\[universal-argument] as prefix
3959 argument, unconditionally set mark where point is, even if
3960 `set-mark-command-repeat-pop' is non-nil.
3962 Novice Emacs Lisp programmers often try to use the mark for the wrong
3963 purposes. See the documentation of `set-mark' for more information."
3965 (cond ((eq transient-mark-mode 'lambda)
3966 (setq transient-mark-mode nil))
3967 ((eq (car-safe transient-mark-mode) 'only)
3970 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3971 (push-mark-command nil))
3972 ((not (eq this-command 'set-mark-command))
3974 (pop-to-mark-command)
3975 (push-mark-command t)))
3976 ((and set-mark-command-repeat-pop
3977 (eq last-command 'pop-to-mark-command))
3978 (setq this-command 'pop-to-mark-command)
3979 (pop-to-mark-command))
3980 ((and set-mark-command-repeat-pop
3981 (eq last-command 'pop-global-mark)
3983 (setq this-command 'pop-global-mark)
3986 (setq this-command 'pop-to-mark-command)
3987 (pop-to-mark-command))
3988 ((eq last-command 'set-mark-command)
3989 (if (region-active-p)
3992 (message "Mark deactivated"))
3994 (message "Mark activated")))
3996 (push-mark-command nil)
3997 (if set-mark-default-inactive (deactivate-mark)))))
3999 (defun push-mark (&optional location nomsg activate)
4000 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
4001 If the last global mark pushed was not in the current buffer,
4002 also push LOCATION on the global mark ring.
4003 Display `Mark set' unless the optional second arg NOMSG is non-nil.
4005 Novice Emacs Lisp programmers often try to use the mark for the wrong
4006 purposes. See the documentation of `set-mark' for more information.
4008 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
4009 (unless (null (mark t))
4010 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
4011 (when (> (length mark-ring) mark-ring-max)
4012 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
4013 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
4014 (set-marker (mark-marker) (or location (point)) (current-buffer))
4015 ;; Now push the mark on the global mark ring.
4016 (if (and global-mark-ring
4017 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
4018 ;; The last global mark pushed was in this same buffer.
4019 ;; Don't push another one.
4021 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
4022 (when (> (length global-mark-ring) global-mark-ring-max)
4023 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
4024 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
4025 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
4026 (message "Mark set"))
4027 (if (or activate (not transient-mark-mode))
4028 (set-mark (mark t)))
4032 "Pop off mark ring into the buffer's actual mark.
4033 Does not set point. Does nothing if mark ring is empty."
4035 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
4036 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
4037 (move-marker (car mark-ring) nil)
4038 (if (null (mark t)) (ding))
4039 (setq mark-ring (cdr mark-ring)))
4042 (define-obsolete-function-alias
4043 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
4044 (defun exchange-point-and-mark (&optional arg)
4045 "Put the mark where point is now, and point where the mark is now.
4046 This command works even when the mark is not active,
4047 and it reactivates the mark.
4049 If Transient Mark mode is on, a prefix ARG deactivates the mark
4050 if it is active, and otherwise avoids reactivating it. If
4051 Transient Mark mode is off, a prefix ARG enables Transient Mark
4054 (let ((omark (mark t))
4055 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
4057 (error "No mark set in this buffer"))
4061 (if set-mark-default-inactive (deactivate-mark))
4062 (cond (temp-highlight
4063 (setq transient-mark-mode (cons 'only transient-mark-mode)))
4064 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
4065 (not (or arg (region-active-p))))
4067 (t (activate-mark)))
4070 (defcustom shift-select-mode t
4071 "When non-nil, shifted motion keys activate the mark momentarily.
4073 While the mark is activated in this way, any shift-translated point
4074 motion key extends the region, and if Transient Mark mode was off, it
4075 is temporarily turned on. Furthermore, the mark will be deactivated
4076 by any subsequent point motion key that was not shift-translated, or
4077 by any action that normally deactivates the mark in Transient Mark mode.
4079 See `this-command-keys-shift-translated' for the meaning of
4082 :group 'editing-basics)
4084 (defun handle-shift-selection ()
4085 "Activate/deactivate mark depending on invocation thru shift translation.
4086 This function is called by `call-interactively' when a command
4087 with a `^' character in its `interactive' spec is invoked, before
4088 running the command itself.
4090 If `shift-select-mode' is enabled and the command was invoked
4091 through shift translation, set the mark and activate the region
4092 temporarily, unless it was already set in this way. See
4093 `this-command-keys-shift-translated' for the meaning of shift
4096 Otherwise, if the region has been activated temporarily,
4097 deactivate it, and restore the variable `transient-mark-mode' to
4099 (cond ((and shift-select-mode this-command-keys-shift-translated)
4100 (unless (and mark-active
4101 (eq (car-safe transient-mark-mode) 'only))
4102 (setq transient-mark-mode
4104 (unless (eq transient-mark-mode 'lambda)
4105 transient-mark-mode)))
4106 (push-mark nil nil t)))
4107 ((eq (car-safe transient-mark-mode) 'only)
4108 (setq transient-mark-mode (cdr transient-mark-mode))
4109 (deactivate-mark))))
4111 (define-minor-mode transient-mark-mode
4112 "Toggle Transient Mark mode.
4113 With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
4115 In Transient Mark mode, when the mark is active, the region is highlighted.
4116 Changing the buffer \"deactivates\" the mark.
4117 So do certain other operations that set the mark
4118 but whose main purpose is something else--for example,
4119 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4121 You can also deactivate the mark by typing \\[keyboard-quit] or
4122 \\[keyboard-escape-quit].
4124 Many commands change their behavior when Transient Mark mode is in effect
4125 and the mark is active, by acting on the region instead of their usual
4126 default part of the buffer's text. Examples of such commands include
4127 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
4128 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4129 Invoke \\[apropos-documentation] and type \"transient\" or
4130 \"mark.*active\" at the prompt, to see the documentation of
4131 commands which are sensitive to the Transient Mark mode."
4133 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4134 :variable transient-mark-mode)
4136 (defvar widen-automatically t
4137 "Non-nil means it is ok for commands to call `widen' when they want to.
4138 Some commands will do this in order to go to positions outside
4139 the current accessible part of the buffer.
4141 If `widen-automatically' is nil, these commands will do something else
4142 as a fallback, and won't change the buffer bounds.")
4144 (defvar non-essential nil
4145 "Whether the currently executing code is performing an essential task.
4146 This variable should be non-nil only when running code which should not
4147 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4148 user for a password when we are simply scanning a set of files in the
4149 background or displaying possible completions before the user even asked
4152 (defun pop-global-mark ()
4153 "Pop off global mark ring and jump to the top location."
4155 ;; Pop entries which refer to non-existent buffers.
4156 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4157 (setq global-mark-ring (cdr global-mark-ring)))
4158 (or global-mark-ring
4159 (error "No global mark set"))
4160 (let* ((marker (car global-mark-ring))
4161 (buffer (marker-buffer marker))
4162 (position (marker-position marker)))
4163 (setq global-mark-ring (nconc (cdr global-mark-ring)
4164 (list (car global-mark-ring))))
4166 (or (and (>= position (point-min))
4167 (<= position (point-max)))
4168 (if widen-automatically
4170 (error "Global mark position is outside accessible part of buffer")))
4171 (goto-char position)
4172 (switch-to-buffer buffer)))
4174 (defcustom next-line-add-newlines nil
4175 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4178 :group 'editing-basics)
4180 (defun next-line (&optional arg try-vscroll)
4181 "Move cursor vertically down ARG lines.
4182 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4183 If there is no character in the target line exactly under the current column,
4184 the cursor is positioned after the character in that line which spans this
4185 column, or at the end of the line if it is not long enough.
4186 If there is no line in the buffer after this one, behavior depends on the
4187 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4188 to create a line, and moves the cursor to that line. Otherwise it moves the
4189 cursor to the end of the buffer.
4191 If the variable `line-move-visual' is non-nil, this command moves
4192 by display lines. Otherwise, it moves by buffer lines, without
4193 taking variable-width characters or continued lines into account.
4195 The command \\[set-goal-column] can be used to create
4196 a semipermanent goal column for this command.
4197 Then instead of trying to move exactly vertically (or as close as possible),
4198 this command moves to the specified goal column (or as close as possible).
4199 The goal column is stored in the variable `goal-column', which is nil
4200 when there is no goal column.
4202 If you are thinking of using this in a Lisp program, consider
4203 using `forward-line' instead. It is usually easier to use
4204 and more reliable (no dependence on goal column, etc.)."
4205 (interactive "^p\np")
4206 (or arg (setq arg 1))
4207 (if (and next-line-add-newlines (= arg 1))
4208 (if (save-excursion (end-of-line) (eobp))
4209 ;; When adding a newline, don't expand an abbrev.
4210 (let ((abbrev-mode nil))
4212 (insert (if use-hard-newlines hard-newline "\n")))
4213 (line-move arg nil nil try-vscroll))
4214 (if (called-interactively-p 'interactive)
4216 (line-move arg nil nil try-vscroll)
4217 ((beginning-of-buffer end-of-buffer)
4218 (signal (car err) (cdr err))))
4219 (line-move arg nil nil try-vscroll)))
4222 (defun previous-line (&optional arg try-vscroll)
4223 "Move cursor vertically up ARG lines.
4224 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4225 If there is no character in the target line exactly over the current column,
4226 the cursor is positioned after the character in that line which spans this
4227 column, or at the end of the line if it is not long enough.
4229 If the variable `line-move-visual' is non-nil, this command moves
4230 by display lines. Otherwise, it moves by buffer lines, without
4231 taking variable-width characters or continued lines into account.
4233 The command \\[set-goal-column] can be used to create
4234 a semipermanent goal column for this command.
4235 Then instead of trying to move exactly vertically (or as close as possible),
4236 this command moves to the specified goal column (or as close as possible).
4237 The goal column is stored in the variable `goal-column', which is nil
4238 when there is no goal column.
4240 If you are thinking of using this in a Lisp program, consider using
4241 `forward-line' with a negative argument instead. It is usually easier
4242 to use and more reliable (no dependence on goal column, etc.)."
4243 (interactive "^p\np")
4244 (or arg (setq arg 1))
4245 (if (called-interactively-p 'interactive)
4247 (line-move (- arg) nil nil try-vscroll)
4248 ((beginning-of-buffer end-of-buffer)
4249 (signal (car err) (cdr err))))
4250 (line-move (- arg) nil nil try-vscroll))
4253 (defcustom track-eol nil
4254 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4255 This means moving to the end of each line moved onto.
4256 The beginning of a blank line does not count as the end of a line.
4257 This has no effect when `line-move-visual' is non-nil."
4259 :group 'editing-basics)
4261 (defcustom goal-column nil
4262 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
4263 :type '(choice integer
4264 (const :tag "None" nil))
4265 :group 'editing-basics)
4266 (make-variable-buffer-local 'goal-column)
4268 (defvar temporary-goal-column 0
4269 "Current goal column for vertical motion.
4270 It is the column where point was at the start of the current run
4271 of vertical motion commands.
4273 When moving by visual lines via `line-move-visual', it is a cons
4274 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4275 divided by the default column width, and HSCROLL is the number of
4276 columns by which window is scrolled from left margin.
4278 When the `track-eol' feature is doing its job, the value is
4279 `most-positive-fixnum'.")
4281 (defcustom line-move-ignore-invisible t
4282 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
4283 Outline mode sets this."
4285 :group 'editing-basics)
4287 (defcustom line-move-visual t
4288 "When non-nil, `line-move' moves point by visual lines.
4289 This movement is based on where the cursor is displayed on the
4290 screen, instead of relying on buffer contents alone. It takes
4291 into account variable-width characters and line continuation.
4292 If nil, `line-move' moves point by logical lines."
4294 :group 'editing-basics
4297 ;; Returns non-nil if partial move was done.
4298 (defun line-move-partial (arg noerror to-end)
4300 ;; Move backward (up).
4301 ;; If already vscrolled, reduce vscroll
4302 (let ((vs (window-vscroll nil t)))
4303 (when (> vs (frame-char-height))
4304 (set-window-vscroll nil (- vs (frame-char-height)) t)))
4306 ;; Move forward (down).
4307 (let* ((lh (window-line-height -1))
4313 (>= rbot (frame-char-height))
4314 (<= ypos (- (frame-char-height))))
4316 (let ((wend (pos-visible-in-window-p t nil t)))
4317 (setq rbot (nth 3 wend)
4318 vpos (nth 5 wend))))
4320 ;; If last line of window is fully visible, move forward.
4321 ((or (null rbot) (= rbot 0))
4323 ;; If cursor is not in the bottom scroll margin, move forward.
4326 (or (nth 1 (window-line-height))
4327 (let ((ppos (posn-at-point)))
4328 (cdr (or (posn-actual-col-row ppos)
4329 (posn-col-row ppos))))))
4330 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
4332 ;; When already vscrolled, we vscroll some more if we can,
4333 ;; or clear vscroll and move forward at end of tall image.
4334 ((> (setq vs (window-vscroll nil t)) 0)
4336 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
4337 ;; If cursor just entered the bottom scroll margin, move forward,
4338 ;; but also vscroll one line so redisplay wont recenter.
4340 (= py (min (- (window-text-height) scroll-margin 1)
4342 (set-window-vscroll nil (frame-char-height) t)
4343 (line-move-1 arg noerror to-end)
4345 ;; If there are lines above the last line, scroll-up one line.
4349 ;; Finally, start vscroll.
4351 (set-window-vscroll nil (frame-char-height) t)))))))
4354 ;; This is like line-move-1 except that it also performs
4355 ;; vertical scrolling of tall images if appropriate.
4356 ;; That is not really a clean thing to do, since it mixes
4357 ;; scrolling with cursor motion. But so far we don't have
4358 ;; a cleaner solution to the problem of making C-n do something
4359 ;; useful given a tall image.
4360 (defun line-move (arg &optional noerror to-end try-vscroll)
4361 (unless (and auto-window-vscroll try-vscroll
4362 ;; Only vscroll for single line moves
4364 ;; But don't vscroll in a keyboard macro.
4365 (not defining-kbd-macro)
4366 (not executing-kbd-macro)
4367 (line-move-partial arg noerror to-end))
4368 (set-window-vscroll nil 0 t)
4369 (if line-move-visual
4370 (line-move-visual arg noerror)
4371 (line-move-1 arg noerror to-end))))
4373 ;; Display-based alternative to line-move-1.
4374 ;; Arg says how many lines to move. The value is t if we can move the
4375 ;; specified number of lines.
4376 (defun line-move-visual (arg &optional noerror)
4377 (let ((opoint (point))
4378 (hscroll (window-hscroll))
4380 ;; Check if the previous command was a line-motion command, or if
4381 ;; we were called from some other command.
4382 (if (and (consp temporary-goal-column)
4383 (memq last-command `(next-line previous-line ,this-command)))
4384 ;; If so, there's no need to reset `temporary-goal-column',
4385 ;; but we may need to hscroll.
4386 (if (or (/= (cdr temporary-goal-column) hscroll)
4387 (> (cdr temporary-goal-column) 0))
4388 (setq target-hscroll (cdr temporary-goal-column)))
4389 ;; Otherwise, we should reset `temporary-goal-column'.
4390 (let ((posn (posn-at-point)))
4392 ;; Handle the `overflow-newline-into-fringe' case:
4393 ((eq (nth 1 posn) 'right-fringe)
4394 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
4395 ((car (posn-x-y posn))
4396 (setq temporary-goal-column
4397 (cons (/ (float (car (posn-x-y posn)))
4398 (frame-char-width)) hscroll))))))
4400 (set-window-hscroll (selected-window) target-hscroll))
4401 (or (and (= (vertical-motion
4402 (cons (or goal-column
4403 (if (consp temporary-goal-column)
4404 (car temporary-goal-column)
4405 temporary-goal-column))
4410 ;; If the goal column lies on a display string,
4411 ;; `vertical-motion' advances the cursor to the end
4412 ;; of the string. For arg < 0, this can cause the
4413 ;; cursor to get stuck. (Bug#3020).
4414 (= (vertical-motion arg) arg)))
4416 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
4419 ;; This is the guts of next-line and previous-line.
4420 ;; Arg says how many lines to move.
4421 ;; The value is t if we can move the specified number of lines.
4422 (defun line-move-1 (arg &optional noerror _to-end)
4423 ;; Don't run any point-motion hooks, and disregard intangibility,
4424 ;; for intermediate positions.
4425 (let ((inhibit-point-motion-hooks t)
4428 (if (consp temporary-goal-column)
4429 (setq temporary-goal-column (+ (car temporary-goal-column)
4430 (cdr temporary-goal-column))))
4433 (if (not (memq last-command '(next-line previous-line)))
4434 (setq temporary-goal-column
4435 (if (and track-eol (eolp)
4436 ;; Don't count beg of empty line as end of line
4437 ;; unless we just did explicit end-of-line.
4438 (or (not (bolp)) (eq last-command 'move-end-of-line)))
4439 most-positive-fixnum
4442 (if (not (or (integerp selective-display)
4443 line-move-ignore-invisible))
4444 ;; Use just newline characters.
4445 ;; Set ARG to 0 if we move as many lines as requested.
4447 (progn (if (> arg 1) (forward-line (1- arg)))
4448 ;; This way of moving forward ARG lines
4449 ;; verifies that we have a newline after the last one.
4450 ;; It doesn't get confused by intangible text.
4452 (if (zerop (forward-line 1))
4454 (and (zerop (forward-line arg))
4458 (signal (if (< arg 0)
4459 'beginning-of-buffer
4462 ;; Move by arg lines, but ignore invisible ones.
4464 (while (and (> arg 0) (not done))
4465 ;; If the following character is currently invisible,
4466 ;; skip all characters with that same `invisible' property value.
4467 (while (and (not (eobp)) (invisible-p (point)))
4468 (goto-char (next-char-property-change (point))))
4470 ;; We don't use `end-of-line', since we want to escape
4471 ;; from field boundaries occurring exactly at point.
4472 (goto-char (constrain-to-field
4473 (let ((inhibit-field-text-motion t))
4474 (line-end-position))
4476 'inhibit-line-move-field-capture))
4477 ;; If there's no invisibility here, move over the newline.
4481 (signal 'end-of-buffer nil)
4483 ((and (> arg 1) ;; Use vertical-motion for last move
4484 (not (integerp selective-display))
4485 (not (invisible-p (point))))
4486 ;; We avoid vertical-motion when possible
4487 ;; because that has to fontify.
4489 ;; Otherwise move a more sophisticated way.
4490 ((zerop (vertical-motion 1))
4492 (signal 'end-of-buffer nil)
4495 (setq arg (1- arg))))
4496 ;; The logic of this is the same as the loop above,
4497 ;; it just goes in the other direction.
4498 (while (and (< arg 0) (not done))
4499 ;; For completely consistency with the forward-motion
4500 ;; case, we should call beginning-of-line here.
4501 ;; However, if point is inside a field and on a
4502 ;; continued line, the call to (vertical-motion -1)
4503 ;; below won't move us back far enough; then we return
4504 ;; to the same column in line-move-finish, and point
4505 ;; gets stuck -- cyd
4510 (signal 'beginning-of-buffer nil)
4512 ((and (< arg -1) ;; Use vertical-motion for last move
4513 (not (integerp selective-display))
4514 (not (invisible-p (1- (point)))))
4516 ((zerop (vertical-motion -1))
4518 (signal 'beginning-of-buffer nil)
4522 (while (and ;; Don't move over previous invis lines
4523 ;; if our target is the middle of this line.
4524 (or (zerop (or goal-column temporary-goal-column))
4526 (not (bobp)) (invisible-p (1- (point))))
4527 (goto-char (previous-char-property-change (point))))))))
4528 ;; This is the value the function returns.
4532 ;; If we did not move down as far as desired, at least go
4533 ;; to end of line. Be sure to call point-entered and
4534 ;; point-left-hooks.
4535 (let* ((npoint (prog1 (line-end-position)
4536 (goto-char opoint)))
4537 (inhibit-point-motion-hooks nil))
4538 (goto-char npoint)))
4540 ;; If we did not move up as far as desired,
4541 ;; at least go to beginning of line.
4542 (let* ((npoint (prog1 (line-beginning-position)
4543 (goto-char opoint)))
4544 (inhibit-point-motion-hooks nil))
4545 (goto-char npoint)))
4547 (line-move-finish (or goal-column temporary-goal-column)
4548 opoint (> orig-arg 0)))))))
4550 (defun line-move-finish (column opoint forward)
4553 ;; Set REPEAT to t to repeat the whole thing.
4558 (line-beg (line-beginning-position))
4560 ;; Compute the end of the line
4561 ;; ignoring effectively invisible newlines.
4563 ;; Like end-of-line but ignores fields.
4564 (skip-chars-forward "^\n")
4565 (while (and (not (eobp)) (invisible-p (point)))
4566 (goto-char (next-char-property-change (point)))
4567 (skip-chars-forward "^\n"))
4570 ;; Move to the desired column.
4571 (line-move-to-column (truncate column))
4573 ;; Corner case: suppose we start out in a field boundary in
4574 ;; the middle of a continued line. When we get to
4575 ;; line-move-finish, point is at the start of a new *screen*
4576 ;; line but the same text line; then line-move-to-column would
4577 ;; move us backwards. Test using C-n with point on the "x" in
4578 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4585 ;; Process intangibility within a line.
4586 ;; With inhibit-point-motion-hooks bound to nil, a call to
4587 ;; goto-char moves point past intangible text.
4589 ;; However, inhibit-point-motion-hooks controls both the
4590 ;; intangibility and the point-entered/point-left hooks. The
4591 ;; following hack avoids calling the point-* hooks
4592 ;; unnecessarily. Note that we move *forward* past intangible
4593 ;; text when the initial and final points are the same.
4595 (let ((inhibit-point-motion-hooks nil))
4598 ;; If intangibility moves us to a different (later) place
4599 ;; in the same line, use that as the destination.
4600 (if (<= (point) line-end)
4602 ;; If that position is "too late",
4603 ;; try the previous allowable position.
4607 ;; If going forward, don't accept the previous
4608 ;; allowable position if it is before the target line.
4609 (< line-beg (point))
4610 ;; If going backward, don't accept the previous
4611 ;; allowable position if it is still after the target line.
4612 (<= (point) line-end))
4614 ;; As a last resort, use the end of the line.
4615 (setq new line-end))))
4617 ;; Now move to the updated destination, processing fields
4618 ;; as well as intangibility.
4620 (let ((inhibit-point-motion-hooks nil))
4622 ;; Ignore field boundaries if the initial and final
4623 ;; positions have the same `field' property, even if the
4624 ;; fields are non-contiguous. This seems to be "nicer"
4625 ;; behavior in many situations.
4626 (if (eq (get-char-property new 'field)
4627 (get-char-property opoint 'field))
4629 (constrain-to-field new opoint t t
4630 'inhibit-line-move-field-capture))))
4632 ;; If all this moved us to a different line,
4633 ;; retry everything within that new line.
4634 (when (or (< (point) line-beg) (> (point) line-end))
4635 ;; Repeat the intangibility and field processing.
4636 (setq repeat t))))))
4638 (defun line-move-to-column (col)
4639 "Try to find column COL, considering invisibility.
4640 This function works only in certain cases,
4641 because what we really need is for `move-to-column'
4642 and `current-column' to be able to ignore invisible text."
4645 (move-to-column col))
4647 (when (and line-move-ignore-invisible
4648 (not (bolp)) (invisible-p (1- (point))))
4649 (let ((normal-location (point))
4650 (normal-column (current-column)))
4651 ;; If the following character is currently invisible,
4652 ;; skip all characters with that same `invisible' property value.
4653 (while (and (not (eobp))
4654 (invisible-p (point)))
4655 (goto-char (next-char-property-change (point))))
4656 ;; Have we advanced to a larger column position?
4657 (if (> (current-column) normal-column)
4658 ;; We have made some progress towards the desired column.
4659 ;; See if we can make any further progress.
4660 (line-move-to-column (+ (current-column) (- col normal-column)))
4661 ;; Otherwise, go to the place we originally found
4662 ;; and move back over invisible text.
4663 ;; that will get us to the same place on the screen
4664 ;; but with a more reasonable buffer position.
4665 (goto-char normal-location)
4666 (let ((line-beg (line-beginning-position)))
4667 (while (and (not (bolp)) (invisible-p (1- (point))))
4668 (goto-char (previous-char-property-change (point) line-beg))))))))
4670 (defun move-end-of-line (arg)
4671 "Move point to end of current line as displayed.
4672 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4673 If point reaches the beginning or end of buffer, it stops there.
4675 To ignore the effects of the `intangible' text or overlay
4676 property, bind `inhibit-point-motion-hooks' to t.
4677 If there is an image in the current line, this function
4678 disregards newlines that are part of the text on which the image
4681 (or arg (setq arg 1))
4686 (let ((goal-column 0)
4687 (line-move-visual nil))
4688 (and (line-move arg t)
4689 ;; With bidi reordering, we may not be at bol,
4690 ;; so make sure we are.
4691 (skip-chars-backward "^\n")
4694 (while (and (not (bobp)) (invisible-p (1- (point))))
4695 (goto-char (previous-single-char-property-change
4696 (point) 'invisible)))
4700 (if (and (> (point) newpos)
4701 (eq (preceding-char) ?\n))
4703 (if (and (> (point) newpos) (not (eobp))
4704 (not (eq (following-char) ?\n)))
4705 ;; If we skipped something intangible and now we're not
4706 ;; really at eol, keep going.
4710 (defun move-beginning-of-line (arg)
4711 "Move point to beginning of current line as displayed.
4712 \(If there's an image in the line, this disregards newlines
4713 which are part of the text that the image rests on.)
4715 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4716 If point reaches the beginning or end of buffer, it stops there.
4717 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4719 (or arg (setq arg 1))
4721 (let ((orig (point))
4722 first-vis first-vis-field-value)
4724 ;; Move by lines, if ARG is not 1 (the default).
4726 (let ((line-move-visual nil))
4727 (line-move (1- arg) t)))
4729 ;; Move to beginning-of-line, ignoring fields and invisibles.
4730 (skip-chars-backward "^\n")
4731 (while (and (not (bobp)) (invisible-p (1- (point))))
4732 (goto-char (previous-char-property-change (point)))
4733 (skip-chars-backward "^\n"))
4735 ;; Now find first visible char in the line
4736 (while (and (not (eobp)) (invisible-p (point)))
4737 (goto-char (next-char-property-change (point))))
4738 (setq first-vis (point))
4740 ;; See if fields would stop us from reaching FIRST-VIS.
4741 (setq first-vis-field-value
4742 (constrain-to-field first-vis orig (/= arg 1) t nil))
4744 (goto-char (if (/= first-vis-field-value first-vis)
4745 ;; If yes, obey them.
4746 first-vis-field-value
4747 ;; Otherwise, move to START with attention to fields.
4748 ;; (It is possible that fields never matter in this case.)
4749 (constrain-to-field (point) orig
4750 (/= arg 1) t nil)))))
4753 ;; Many people have said they rarely use this feature, and often type
4754 ;; it by accident. Maybe it shouldn't even be on a key.
4755 (put 'set-goal-column 'disabled t)
4757 (defun set-goal-column (arg)
4758 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4759 Those commands will move to this position in the line moved to
4760 rather than trying to keep the same horizontal position.
4761 With a non-nil argument ARG, clears out the goal column
4762 so that \\[next-line] and \\[previous-line] resume vertical motion.
4763 The goal column is stored in the variable `goal-column'."
4767 (setq goal-column nil)
4768 (message "No goal column"))
4769 (setq goal-column (current-column))
4770 ;; The older method below can be erroneous if `set-goal-column' is bound
4771 ;; to a sequence containing %
4772 ;;(message (substitute-command-keys
4773 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4777 (format "Goal column %d " goal-column)
4778 (substitute-command-keys
4779 "(use \\[set-goal-column] with an arg to unset it)")))
4784 ;;; Editing based on visual lines, as opposed to logical lines.
4786 (defun end-of-visual-line (&optional n)
4787 "Move point to end of current visual line.
4788 With argument N not nil or 1, move forward N - 1 visual lines first.
4789 If point reaches the beginning or end of buffer, it stops there.
4790 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4794 (let ((line-move-visual t))
4795 (line-move (1- n) t)))
4796 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
4797 ;; constrain to field boundaries, so we don't either.
4798 (vertical-motion (cons (window-width) 0)))
4800 (defun beginning-of-visual-line (&optional n)
4801 "Move point to beginning of current visual line.
4802 With argument N not nil or 1, move forward N - 1 visual lines first.
4803 If point reaches the beginning or end of buffer, it stops there.
4804 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4807 (let ((opoint (point)))
4809 (let ((line-move-visual t))
4810 (line-move (1- n) t)))
4812 ;; Constrain to field boundaries, like `move-beginning-of-line'.
4813 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
4815 (defun kill-visual-line (&optional arg)
4816 "Kill the rest of the visual line.
4817 With prefix argument ARG, kill that many visual lines from point.
4818 If ARG is negative, kill visual lines backward.
4819 If ARG is zero, kill the text before point on the current visual
4822 If you want to append the killed line to the last killed text,
4823 use \\[append-next-kill] before \\[kill-line].
4825 If the buffer is read-only, Emacs will beep and refrain from deleting
4826 the line, but put the line in the kill ring anyway. This means that
4827 you can use this command to copy text from a read-only buffer.
4828 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4831 ;; Like in `kill-line', it's better to move point to the other end
4832 ;; of the kill before killing.
4833 (let ((opoint (point))
4834 (kill-whole-line (and kill-whole-line (bolp))))
4836 (vertical-motion (prefix-numeric-value arg))
4837 (end-of-visual-line 1)
4838 (if (= (point) opoint)
4840 ;; Skip any trailing whitespace at the end of the visual line.
4841 ;; We used to do this only if `show-trailing-whitespace' is
4842 ;; nil, but that's wrong; the correct thing would be to check
4843 ;; whether the trailing whitespace is highlighted. But, it's
4844 ;; OK to just do this unconditionally.
4845 (skip-chars-forward " \t")))
4846 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
4850 (defun next-logical-line (&optional arg try-vscroll)
4851 "Move cursor vertically down ARG lines.
4852 This is identical to `next-line', except that it always moves
4853 by logical lines instead of visual lines, ignoring the value of
4854 the variable `line-move-visual'."
4855 (interactive "^p\np")
4856 (let ((line-move-visual nil))
4858 (next-line arg try-vscroll))))
4860 (defun previous-logical-line (&optional arg try-vscroll)
4861 "Move cursor vertically up ARG lines.
4862 This is identical to `previous-line', except that it always moves
4863 by logical lines instead of visual lines, ignoring the value of
4864 the variable `line-move-visual'."
4865 (interactive "^p\np")
4866 (let ((line-move-visual nil))
4868 (previous-line arg try-vscroll))))
4870 (defgroup visual-line nil
4871 "Editing based on visual lines."
4875 (defvar visual-line-mode-map
4876 (let ((map (make-sparse-keymap)))
4877 (define-key map [remap kill-line] 'kill-visual-line)
4878 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4879 (define-key map [remap move-end-of-line] 'end-of-visual-line)
4880 ;; These keybindings interfere with xterm function keys. Are
4881 ;; there any other suitable bindings?
4882 ;; (define-key map "\M-[" 'previous-logical-line)
4883 ;; (define-key map "\M-]" 'next-logical-line)
4886 (defcustom visual-line-fringe-indicators '(nil nil)
4887 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4888 The value should be a list of the form (LEFT RIGHT), where LEFT
4889 and RIGHT are symbols representing the bitmaps to display, to
4890 indicate wrapped lines, in the left and right fringes respectively.
4891 See also `fringe-indicator-alist'.
4892 The default is not to display fringe indicators for wrapped lines.
4893 This variable does not affect fringe indicators displayed for
4895 :type '(list (choice (const :tag "Hide left indicator" nil)
4896 (const :tag "Left curly arrow" left-curly-arrow)
4897 (symbol :tag "Other bitmap"))
4898 (choice (const :tag "Hide right indicator" nil)
4899 (const :tag "Right curly arrow" right-curly-arrow)
4900 (symbol :tag "Other bitmap")))
4901 :set (lambda (symbol value)
4902 (dolist (buf (buffer-list))
4903 (with-current-buffer buf
4904 (when (and (boundp 'visual-line-mode)
4905 (symbol-value 'visual-line-mode))
4906 (setq fringe-indicator-alist
4907 (cons (cons 'continuation value)
4910 (copy-tree fringe-indicator-alist)))))))
4911 (set-default symbol value)))
4913 (defvar visual-line--saved-state nil)
4915 (define-minor-mode visual-line-mode
4916 "Redefine simple editing commands to act on visual lines, not logical lines.
4917 This also turns on `word-wrap' in the buffer."
4918 :keymap visual-line-mode-map
4921 (if visual-line-mode
4923 (set (make-local-variable 'visual-line--saved-state) nil)
4924 ;; Save the local values of some variables, to be restored if
4925 ;; visual-line-mode is turned off.
4926 (dolist (var '(line-move-visual truncate-lines
4927 truncate-partial-width-windows
4928 word-wrap fringe-indicator-alist))
4929 (if (local-variable-p var)
4930 (push (cons var (symbol-value var))
4931 visual-line--saved-state)))
4932 (set (make-local-variable 'line-move-visual) t)
4933 (set (make-local-variable 'truncate-partial-width-windows) nil)
4934 (setq truncate-lines nil
4936 fringe-indicator-alist
4937 (cons (cons 'continuation visual-line-fringe-indicators)
4938 fringe-indicator-alist)))
4939 (kill-local-variable 'line-move-visual)
4940 (kill-local-variable 'word-wrap)
4941 (kill-local-variable 'truncate-lines)
4942 (kill-local-variable 'truncate-partial-width-windows)
4943 (kill-local-variable 'fringe-indicator-alist)
4944 (dolist (saved visual-line--saved-state)
4945 (set (make-local-variable (car saved)) (cdr saved)))
4946 (kill-local-variable 'visual-line--saved-state)))
4948 (defun turn-on-visual-line-mode ()
4949 (visual-line-mode 1))
4951 (define-globalized-minor-mode global-visual-line-mode
4952 visual-line-mode turn-on-visual-line-mode
4956 (defun transpose-chars (arg)
4957 "Interchange characters around point, moving forward one character.
4958 With prefix arg ARG, effect is to take character before point
4959 and drag it forward past ARG other characters (backward if ARG negative).
4960 If no argument and at end of line, the previous two chars are exchanged."
4962 (and (null arg) (eolp) (forward-char -1))
4963 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4965 (defun transpose-words (arg)
4966 "Interchange words around point, leaving point at end of them.
4967 With prefix arg ARG, effect is to take word before or around point
4968 and drag it forward past ARG other words (backward if ARG negative).
4969 If ARG is zero, the words around or after point and around or after mark
4971 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
4973 (transpose-subr 'forward-word arg))
4975 (defun transpose-sexps (arg)
4976 "Like \\[transpose-words] but applies to sexps.
4977 Does not work on a sexp that point is in the middle of
4978 if it is a list or string."
4982 ;; Here we should try to simulate the behavior of
4983 ;; (cons (progn (forward-sexp x) (point))
4984 ;; (progn (forward-sexp (- x)) (point)))
4985 ;; Except that we don't want to rely on the second forward-sexp
4986 ;; putting us back to where we want to be, since forward-sexp-function
4987 ;; might do funny things like infix-precedence.
4989 (looking-at "\\sw\\|\\s_")
4991 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4992 ;; Jumping over a symbol. We might be inside it, mind you.
4993 (progn (funcall (if (> arg 0)
4994 'skip-syntax-backward 'skip-syntax-forward)
4996 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4997 ;; Otherwise, we're between sexps. Take a step back before jumping
4998 ;; to make sure we'll obey the same precedence no matter which direction
5000 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
5001 (cons (save-excursion (forward-sexp arg) (point))
5002 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
5003 (not (zerop (funcall (if (> arg 0)
5004 'skip-syntax-forward
5005 'skip-syntax-backward)
5010 (defun transpose-lines (arg)
5011 "Exchange current line and previous line, leaving point after both.
5012 With argument ARG, takes previous line and moves it past ARG lines.
5013 With argument 0, interchanges line point is in with line mark is in."
5015 (transpose-subr (function
5019 ;; Move forward over ARG lines,
5020 ;; but create newlines if necessary.
5021 (setq arg (forward-line arg))
5022 (if (/= (preceding-char) ?\n)
5023 (setq arg (1+ arg)))
5026 (forward-line arg))))
5029 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
5030 ;; which seems inconsistent with the ARG /= 0 case.
5031 ;; FIXME document SPECIAL.
5032 (defun transpose-subr (mover arg &optional special)
5033 "Subroutine to do the work of transposing objects.
5034 Works for lines, sentences, paragraphs, etc. MOVER is a function that
5035 moves forward by units of the given object (e.g. forward-sentence,
5036 forward-paragraph). If ARG is zero, exchanges the current object
5037 with the one containing mark. If ARG is an integer, moves the
5038 current object past ARG following (if ARG is positive) or
5039 preceding (if ARG is negative) objects, leaving point after the
5041 (let ((aux (if special mover
5043 (cons (progn (funcall mover x) (point))
5044 (progn (funcall mover (- x)) (point))))))
5049 (setq pos1 (funcall aux 1))
5050 (goto-char (or (mark) (error "No mark set in this buffer")))
5051 (setq pos2 (funcall aux 1))
5052 (transpose-subr-1 pos1 pos2))
5053 (exchange-point-and-mark))
5055 (setq pos1 (funcall aux -1))
5056 (setq pos2 (funcall aux arg))
5057 (transpose-subr-1 pos1 pos2)
5058 (goto-char (car pos2)))
5060 (setq pos1 (funcall aux -1))
5061 (goto-char (car pos1))
5062 (setq pos2 (funcall aux arg))
5063 (transpose-subr-1 pos1 pos2)))))
5065 (defun transpose-subr-1 (pos1 pos2)
5066 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
5067 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
5068 (when (> (car pos1) (car pos2))
5070 (setq pos1 pos2 pos2 swap)))
5071 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
5072 (atomic-change-group
5074 ;; FIXME: We first delete the two pieces of text, so markers that
5075 ;; used to point to after the text end up pointing to before it :-(
5076 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
5077 (goto-char (car pos2))
5078 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
5079 (goto-char (car pos1))
5082 (defun backward-word (&optional arg)
5083 "Move backward until encountering the beginning of a word.
5084 With argument ARG, do this that many times."
5086 (forward-word (- (or arg 1))))
5088 (defun mark-word (&optional arg allow-extend)
5089 "Set mark ARG words away from point.
5090 The place mark goes is the same place \\[forward-word] would
5091 move to with the same argument.
5092 Interactively, if this command is repeated
5093 or (in Transient Mark mode) if the mark is active,
5094 it marks the next ARG words after the ones already marked."
5095 (interactive "P\np")
5096 (cond ((and allow-extend
5097 (or (and (eq last-command this-command) (mark t))
5099 (setq arg (if arg (prefix-numeric-value arg)
5100 (if (< (mark) (point)) -1 1)))
5109 (forward-word (prefix-numeric-value arg))
5113 (defun kill-word (arg)
5114 "Kill characters forward until encountering the end of a word.
5115 With argument ARG, do this that many times."
5117 (kill-region (point) (progn (forward-word arg) (point))))
5119 (defun backward-kill-word (arg)
5120 "Kill characters backward until encountering the beginning of a word.
5121 With argument ARG, do this that many times."
5123 (kill-word (- arg)))
5125 (defun current-word (&optional strict really-word)
5126 "Return the symbol or word that point is on (or a nearby one) as a string.
5127 The return value includes no text properties.
5128 If optional arg STRICT is non-nil, return nil unless point is within
5129 or adjacent to a symbol or word. In all cases the value can be nil
5130 if there is no word nearby.
5131 The function, belying its name, normally finds a symbol.
5132 If optional arg REALLY-WORD is non-nil, it finds just a word."
5134 (let* ((oldpoint (point)) (start (point)) (end (point))
5135 (syntaxes (if really-word "w" "w_"))
5136 (not-syntaxes (concat "^" syntaxes)))
5137 (skip-syntax-backward syntaxes) (setq start (point))
5138 (goto-char oldpoint)
5139 (skip-syntax-forward syntaxes) (setq end (point))
5140 (when (and (eq start oldpoint) (eq end oldpoint)
5141 ;; Point is neither within nor adjacent to a word.
5143 ;; Look for preceding word in same line.
5144 (skip-syntax-backward not-syntaxes (line-beginning-position))
5146 ;; No preceding word in same line.
5147 ;; Look for following word in same line.
5149 (skip-syntax-forward not-syntaxes (line-end-position))
5150 (setq start (point))
5151 (skip-syntax-forward syntaxes)
5154 (skip-syntax-backward syntaxes)
5155 (setq start (point))))
5156 ;; If we found something nonempty, return it as a string.
5157 (unless (= start end)
5158 (buffer-substring-no-properties start end)))))
5160 (defcustom fill-prefix nil
5161 "String for filling to insert at front of new line, or nil for none."
5162 :type '(choice (const :tag "None" nil)
5165 (make-variable-buffer-local 'fill-prefix)
5166 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
5168 (defcustom auto-fill-inhibit-regexp nil
5169 "Regexp to match lines which should not be auto-filled."
5170 :type '(choice (const :tag "None" nil)
5174 (defun do-auto-fill ()
5175 "The default value for `normal-auto-fill-function'.
5176 This is the default auto-fill function, some major modes use a different one.
5177 Returns t if it really did any work."
5178 (let (fc justify give-up
5179 (fill-prefix fill-prefix))
5180 (if (or (not (setq justify (current-justification)))
5181 (null (setq fc (current-fill-column)))
5182 (and (eq justify 'left)
5183 (<= (current-column) fc))
5184 (and auto-fill-inhibit-regexp
5185 (save-excursion (beginning-of-line)
5186 (looking-at auto-fill-inhibit-regexp))))
5187 nil ;; Auto-filling not required
5188 (if (memq justify '(full center right))
5189 (save-excursion (unjustify-current-line)))
5191 ;; Choose a fill-prefix automatically.
5192 (when (and adaptive-fill-mode
5193 (or (null fill-prefix) (string= fill-prefix "")))
5195 (fill-context-prefix
5196 (save-excursion (backward-paragraph 1) (point))
5197 (save-excursion (forward-paragraph 1) (point)))))
5198 (and prefix (not (equal prefix ""))
5199 ;; Use auto-indentation rather than a guessed empty prefix.
5200 (not (and fill-indent-according-to-mode
5201 (string-match "\\`[ \t]*\\'" prefix)))
5202 (setq fill-prefix prefix))))
5204 (while (and (not give-up) (> (current-column) fc))
5205 ;; Determine where to split the line.
5210 (setq after-prefix (point))
5212 (looking-at (regexp-quote fill-prefix))
5213 (setq after-prefix (match-end 0)))
5214 (move-to-column (1+ fc))
5215 (fill-move-to-break-point after-prefix)
5218 ;; See whether the place we found is any good.
5220 (goto-char fill-point)
5222 ;; There is no use breaking at end of line.
5223 (save-excursion (skip-chars-forward " ") (eolp))
5224 ;; It is futile to split at the end of the prefix
5225 ;; since we would just insert the prefix again.
5226 (and after-prefix (<= (point) after-prefix))
5227 ;; Don't split right after a comment starter
5228 ;; since we would just make another comment starter.
5229 (and comment-start-skip
5230 (let ((limit (point)))
5232 (and (re-search-forward comment-start-skip
5234 (eq (point) limit))))))
5235 ;; No good place to break => stop trying.
5237 ;; Ok, we have a useful place to break the line. Do it.
5238 (let ((prev-column (current-column)))
5239 ;; If point is at the fill-point, do not `save-excursion'.
5240 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5241 ;; point will end up before it rather than after it.
5243 (skip-chars-backward " \t")
5244 (= (point) fill-point))
5245 (default-indent-new-line t)
5247 (goto-char fill-point)
5248 (default-indent-new-line t)))
5249 ;; Now do justification, if required
5250 (if (not (eq justify 'left))
5253 (justify-current-line justify nil t)))
5254 ;; If making the new line didn't reduce the hpos of
5255 ;; the end of the line, then give up now;
5256 ;; trying again will not help.
5257 (if (>= (current-column) prev-column)
5258 (setq give-up t))))))
5259 ;; Justify last line.
5260 (justify-current-line justify t t)
5263 (defvar comment-line-break-function 'comment-indent-new-line
5264 "*Mode-specific function which line breaks and continues a comment.
5265 This function is called during auto-filling when a comment syntax
5267 The function should take a single optional argument, which is a flag
5268 indicating whether it should use soft newlines.")
5270 (defun default-indent-new-line (&optional soft)
5271 "Break line at point and indent.
5272 If a comment syntax is defined, call `comment-indent-new-line'.
5274 The inserted newline is marked hard if variable `use-hard-newlines' is true,
5275 unless optional argument SOFT is non-nil."
5278 (funcall comment-line-break-function soft)
5279 ;; Insert the newline before removing empty space so that markers
5280 ;; get preserved better.
5281 (if soft (insert-and-inherit ?\n) (newline 1))
5282 (save-excursion (forward-char -1) (delete-horizontal-space))
5283 (delete-horizontal-space)
5285 (if (and fill-prefix (not adaptive-fill-mode))
5286 ;; Blindly trust a non-adaptive fill-prefix.
5288 (indent-to-left-margin)
5289 (insert-before-markers-and-inherit fill-prefix))
5292 ;; If there's an adaptive prefix, use it unless we're inside
5293 ;; a comment and the prefix is not a comment starter.
5295 (indent-to-left-margin)
5296 (insert-and-inherit fill-prefix))
5297 ;; If we're not inside a comment, just try to indent.
5298 (t (indent-according-to-mode))))))
5300 (defvar normal-auto-fill-function 'do-auto-fill
5301 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
5302 Some major modes set this.")
5304 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
5305 ;; `functions' and `hooks' are usually unsafe to set, but setting
5306 ;; auto-fill-function to nil in a file-local setting is safe and
5307 ;; can be useful to prevent auto-filling.
5308 (put 'auto-fill-function 'safe-local-variable 'null)
5309 ;; FIXME: turn into a proper minor mode.
5310 ;; Add a global minor mode version of it.
5311 (define-minor-mode auto-fill-mode
5312 "Toggle Auto Fill mode.
5313 With ARG, turn Auto Fill mode on if and only if ARG is positive.
5314 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
5315 automatically breaks the line at a previous space.
5317 The value of `normal-auto-fill-function' specifies the function to use
5318 for `auto-fill-function' when turning Auto Fill mode on."
5319 :variable (eq auto-fill-function normal-auto-fill-function))
5321 ;; This holds a document string used to document auto-fill-mode.
5322 (defun auto-fill-function ()
5323 "Automatically break line at a previous space, in insertion of text."
5326 (defun turn-on-auto-fill ()
5327 "Unconditionally turn on Auto Fill mode."
5330 (defun turn-off-auto-fill ()
5331 "Unconditionally turn off Auto Fill mode."
5332 (auto-fill-mode -1))
5334 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
5336 (defun set-fill-column (arg)
5337 "Set `fill-column' to specified argument.
5338 Use \\[universal-argument] followed by a number to specify a column.
5339 Just \\[universal-argument] as argument means to use the current column."
5341 (list (or current-prefix-arg
5342 ;; We used to use current-column silently, but C-x f is too easily
5343 ;; typed as a typo for C-x C-f, so we turned it into an error and
5344 ;; now an interactive prompt.
5345 (read-number "Set fill-column to: " (current-column)))))
5347 (setq arg (current-column)))
5348 (if (not (integerp arg))
5349 ;; Disallow missing argument; it's probably a typo for C-x C-f.
5350 (error "set-fill-column requires an explicit argument")
5351 (message "Fill column set to %d (was %d)" arg fill-column)
5352 (setq fill-column arg)))
5354 (defun set-selective-display (arg)
5355 "Set `selective-display' to ARG; clear it if no arg.
5356 When the value of `selective-display' is a number > 0,
5357 lines whose indentation is >= that value are not displayed.
5358 The variable `selective-display' has a separate value for each buffer."
5360 (if (eq selective-display t)
5361 (error "selective-display already in use for marked lines"))
5364 (narrow-to-region (point-min) (point))
5365 (goto-char (window-start))
5366 (vertical-motion (window-height)))))
5367 (setq selective-display
5368 (and arg (prefix-numeric-value arg)))
5369 (recenter current-vpos))
5370 (set-window-start (selected-window) (window-start (selected-window)))
5371 (princ "selective-display set to " t)
5372 (prin1 selective-display t)
5375 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
5377 (defun toggle-truncate-lines (&optional arg)
5378 "Toggle whether to fold or truncate long lines for the current buffer.
5379 With prefix argument ARG, truncate long lines if ARG is positive,
5380 otherwise don't truncate them. Note that in side-by-side windows,
5381 this command has no effect if `truncate-partial-width-windows'
5384 (setq truncate-lines
5386 (not truncate-lines)
5387 (> (prefix-numeric-value arg) 0)))
5388 (force-mode-line-update)
5389 (unless truncate-lines
5390 (let ((buffer (current-buffer)))
5391 (walk-windows (lambda (window)
5392 (if (eq buffer (window-buffer window))
5393 (set-window-hscroll window 0)))
5395 (message "Truncate long lines %s"
5396 (if truncate-lines "enabled" "disabled")))
5398 (defun toggle-word-wrap (&optional arg)
5399 "Toggle whether to use word-wrapping for continuation lines.
5400 With prefix argument ARG, wrap continuation lines at word boundaries
5401 if ARG is positive, otherwise wrap them at the right screen edge.
5402 This command toggles the value of `word-wrap'. It has no effect
5403 if long lines are truncated."
5408 (> (prefix-numeric-value arg) 0)))
5409 (force-mode-line-update)
5410 (message "Word wrapping %s"
5411 (if word-wrap "enabled" "disabled")))
5413 (defvar overwrite-mode-textual (purecopy " Ovwrt")
5414 "The string displayed in the mode line when in overwrite mode.")
5415 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
5416 "The string displayed in the mode line when in binary overwrite mode.")
5418 (define-minor-mode overwrite-mode
5419 "Toggle overwrite mode.
5420 With prefix argument ARG, turn overwrite mode on if ARG is positive,
5421 otherwise turn it off. In overwrite mode, printing characters typed
5422 in replace existing text on a one-for-one basis, rather than pushing
5423 it to the right. At the end of a line, such characters extend the line.
5424 Before a tab, such characters insert until the tab is filled in.
5425 \\[quoted-insert] still inserts characters in overwrite mode; this
5426 is supposed to make it easier to insert characters when necessary."
5427 :variable (eq overwrite-mode 'overwrite-mode-textual))
5429 (define-minor-mode binary-overwrite-mode
5430 "Toggle binary overwrite mode.
5431 With prefix argument ARG, turn binary overwrite mode on if ARG is
5432 positive, otherwise turn it off. In binary overwrite mode, printing
5433 characters typed in replace existing text. Newlines are not treated
5434 specially, so typing at the end of a line joins the line to the next,
5435 with the typed character between them. Typing before a tab character
5436 simply replaces the tab with the character typed. \\[quoted-insert]
5437 replaces the text at the cursor, just as ordinary typing characters do.
5439 Note that binary overwrite mode is not its own minor mode; it is a
5440 specialization of overwrite mode, entered by setting the
5441 `overwrite-mode' variable to `overwrite-mode-binary'."
5442 :variable (eq overwrite-mode 'overwrite-mode-binary))
5444 (define-minor-mode line-number-mode
5445 "Toggle Line Number mode.
5446 With ARG, turn Line Number mode on if ARG is positive, otherwise
5447 turn it off. When Line Number mode is enabled, the line number
5448 appears in the mode line.
5450 Line numbers do not appear for very large buffers and buffers
5451 with very long lines; see variables `line-number-display-limit'
5452 and `line-number-display-limit-width'."
5453 :init-value t :global t :group 'mode-line)
5455 (define-minor-mode column-number-mode
5456 "Toggle Column Number mode.
5457 With ARG, turn Column Number mode on if ARG is positive,
5458 otherwise turn it off. When Column Number mode is enabled, the
5459 column number appears in the mode line."
5460 :global t :group 'mode-line)
5462 (define-minor-mode size-indication-mode
5463 "Toggle Size Indication mode.
5464 With ARG, turn Size Indication mode on if ARG is positive,
5465 otherwise turn it off. When Size Indication mode is enabled, the
5466 size of the accessible part of the buffer appears in the mode line."
5467 :global t :group 'mode-line)
5469 (define-minor-mode auto-save-mode
5470 "Toggle auto-saving of contents of current buffer.
5471 With prefix argument ARG, turn auto-saving on if positive, else off."
5472 :variable ((and buffer-auto-save-file-name
5473 ;; If auto-save is off because buffer has shrunk,
5474 ;; then toggling should turn it on.
5475 (>= buffer-saved-size 0))
5477 (setq buffer-auto-save-file-name
5480 ((and buffer-file-name auto-save-visited-file-name
5481 (not buffer-read-only))
5483 (t (make-auto-save-file-name))))))
5484 ;; If -1 was stored here, to temporarily turn off saving,
5486 (and (< buffer-saved-size 0)
5487 (setq buffer-saved-size 0)))
5489 (defgroup paren-blinking nil
5490 "Blinking matching of parens and expressions."
5491 :prefix "blink-matching-"
5492 :group 'paren-matching)
5494 (defcustom blink-matching-paren t
5495 "Non-nil means show matching open-paren when close-paren is inserted."
5497 :group 'paren-blinking)
5499 (defcustom blink-matching-paren-on-screen t
5500 "Non-nil means show matching open-paren when it is on screen.
5501 If nil, don't show it (but the open-paren can still be shown
5502 when it is off screen).
5504 This variable has no effect if `blink-matching-paren' is nil.
5505 \(In that case, the open-paren is never shown.)
5506 It is also ignored if `show-paren-mode' is enabled."
5508 :group 'paren-blinking)
5510 (defcustom blink-matching-paren-distance (* 100 1024)
5511 "If non-nil, maximum distance to search backwards for matching open-paren.
5512 If nil, search stops at the beginning of the accessible portion of the buffer."
5513 :version "23.2" ; 25->100k
5514 :type '(choice (const nil) integer)
5515 :group 'paren-blinking)
5517 (defcustom blink-matching-delay 1
5518 "Time in seconds to delay after showing a matching paren."
5520 :group 'paren-blinking)
5522 (defcustom blink-matching-paren-dont-ignore-comments nil
5523 "If nil, `blink-matching-paren' ignores comments.
5524 More precisely, when looking for the matching parenthesis,
5525 it skips the contents of comments that end before point."
5527 :group 'paren-blinking)
5529 (defun blink-matching-check-mismatch (start end)
5530 "Return whether or not START...END are matching parens.
5531 END is the current point and START is the blink position.
5532 START might be nil if no matching starter was found.
5533 Returns non-nil if we find there is a mismatch."
5534 (let* ((end-syntax (syntax-after (1- end)))
5535 (matching-paren (and (consp end-syntax)
5536 (eq (syntax-class end-syntax) 5)
5538 ;; For self-matched chars like " and $, we can't know when they're
5539 ;; mismatched or unmatched, so we can only do it for parens.
5540 (when matching-paren
5543 (eq (char-after start) matching-paren)
5544 ;; The cdr might hold a new paren-class info rather than
5545 ;; a matching-char info, in which case the two CDRs
5547 (eq matching-paren (cdr-safe (syntax-after start)))))))))
5549 (defvar blink-matching-check-function #'blink-matching-check-mismatch
5550 "Function to check parentheses mismatches.
5551 The function takes two arguments (START and END) where START is the
5552 position just before the opening token and END is the position right after.
5553 START can be nil, if it was not found.
5554 The function should return non-nil if the two tokens do not match.")
5556 (defun blink-matching-open ()
5557 "Move cursor momentarily to the beginning of the sexp before point."
5559 (when (and (not (bobp))
5560 blink-matching-paren)
5561 (let* ((oldpos (point))
5562 (message-log-max nil) ; Don't log messages about paren matching.
5566 (if blink-matching-paren-distance
5568 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5569 (- (point) blink-matching-paren-distance))
5571 (let ((parse-sexp-ignore-comments
5572 (and parse-sexp-ignore-comments
5573 (not blink-matching-paren-dont-ignore-comments))))
5577 ;; backward-sexp skips backward over prefix chars,
5578 ;; so move back to the matching paren.
5579 (while (and (< (point) (1- oldpos))
5580 (let ((code (syntax-after (point))))
5581 (or (eq (syntax-class code) 6)
5582 (eq (logand 1048576 (car code))
5587 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
5592 (minibuffer-message " [Mismatched parentheses]")
5593 (message "Mismatched parentheses"))
5595 (minibuffer-message " [Unmatched parenthesis]")
5596 (message "Unmatched parenthesis"))))
5597 ((not blinkpos) nil)
5598 ((pos-visible-in-window-p blinkpos)
5599 ;; Matching open within window, temporarily move to blinkpos but only
5600 ;; if `blink-matching-paren-on-screen' is non-nil.
5601 (and blink-matching-paren-on-screen
5602 (not show-paren-mode)
5604 (goto-char blinkpos)
5605 (sit-for blink-matching-delay))))
5608 (goto-char blinkpos)
5609 (let ((open-paren-line-string
5610 ;; Show what precedes the open in its line, if anything.
5612 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5613 (buffer-substring (line-beginning-position)
5615 ;; Show what follows the open in its line, if anything.
5618 (skip-chars-forward " \t")
5620 (buffer-substring blinkpos
5621 (line-end-position)))
5622 ;; Otherwise show the previous nonblank line,
5624 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5626 (buffer-substring (progn
5627 (skip-chars-backward "\n \t")
5628 (line-beginning-position))
5629 (progn (end-of-line)
5630 (skip-chars-backward " \t")
5632 ;; Replace the newline and other whitespace with `...'.
5634 (buffer-substring blinkpos (1+ blinkpos))))
5635 ;; There is nothing to show except the char itself.
5636 (t (buffer-substring blinkpos (1+ blinkpos))))))
5637 (message "Matches %s"
5638 (substring-no-properties open-paren-line-string)))))))))
5640 (defvar blink-paren-function 'blink-matching-open
5641 "Function called, if non-nil, whenever a close parenthesis is inserted.
5642 More precisely, a char with closeparen syntax is self-inserted.")
5644 (defun blink-paren-post-self-insert-function ()
5645 (when (and (eq (char-before) last-command-event) ; Sanity check.
5646 (memq (char-syntax last-command-event) '(?\) ?\$))
5647 blink-paren-function
5648 (not executing-kbd-macro)
5649 (not noninteractive)
5650 ;; Verify an even number of quoting characters precede the close.
5651 (= 1 (logand 1 (- (point)
5654 (skip-syntax-backward "/\\")
5656 (funcall blink-paren-function)))
5658 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
5659 ;; Most likely, this hook is nil, so this arg doesn't matter,
5660 ;; but I use it as a reminder that this function usually
5661 ;; likes to be run after others since it does `sit-for'.
5664 ;; This executes C-g typed while Emacs is waiting for a command.
5665 ;; Quitting out of a program does not go through here;
5666 ;; that happens in the QUIT macro at the C code level.
5667 (defun keyboard-quit ()
5668 "Signal a `quit' condition.
5669 During execution of Lisp code, this character causes a quit directly.
5670 At top-level, as an editor command, this simply beeps."
5672 ;; Avoid adding the region to the window selection.
5673 (setq saved-region-selection nil)
5674 (let (select-active-regions)
5676 (if (fboundp 'kmacro-keyboard-quit)
5677 (kmacro-keyboard-quit))
5678 (setq defining-kbd-macro nil)
5681 (defvar buffer-quit-function nil
5682 "Function to call to \"quit\" the current buffer, or nil if none.
5683 \\[keyboard-escape-quit] calls this function when its more local actions
5684 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5686 (defun keyboard-escape-quit ()
5687 "Exit the current \"mode\" (in a generalized sense of the word).
5688 This command can exit an interactive command such as `query-replace',
5689 can clear out a prefix argument or a region,
5690 can get out of the minibuffer or other recursive edit,
5691 cancel the use of the current buffer (for special-purpose buffers),
5692 or go back to just one window (by deleting all but the selected window)."
5694 (cond ((eq last-command 'mode-exited) nil)
5697 ((> (minibuffer-depth) 0)
5698 (abort-recursive-edit))
5701 ((> (recursion-depth) 0)
5702 (exit-recursive-edit))
5703 (buffer-quit-function
5704 (funcall buffer-quit-function))
5705 ((not (one-window-p t))
5706 (delete-other-windows))
5707 ((string-match "^ \\*" (buffer-name (current-buffer)))
5710 (defun play-sound-file (file &optional volume device)
5711 "Play sound stored in FILE.
5712 VOLUME and DEVICE correspond to the keywords of the sound
5713 specification for `play-sound'."
5714 (interactive "fPlay sound file: ")
5715 (let ((sound (list :file file)))
5717 (plist-put sound :volume volume))
5719 (plist-put sound :device device))
5721 (play-sound sound)))
5724 (defcustom read-mail-command 'rmail
5725 "Your preference for a mail reading package.
5726 This is used by some keybindings which support reading mail.
5727 See also `mail-user-agent' concerning sending mail."
5728 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
5729 (function-item :tag "Gnus" :format "%t\n" gnus)
5730 (function-item :tag "Emacs interface to MH"
5731 :format "%t\n" mh-rmail)
5732 (function :tag "Other"))
5736 (defcustom mail-user-agent 'message-user-agent
5737 "Your preference for a mail composition package.
5738 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
5739 outgoing email message. This variable lets you specify which
5740 mail-sending package you prefer.
5742 Valid values include:
5744 `message-user-agent' -- use the Message package.
5745 See Info node `(message)'.
5746 `sendmail-user-agent' -- use the Mail package.
5747 See Info node `(emacs)Sending Mail'.
5748 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5749 See Info node `(mh-e)'.
5750 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5751 paraphernalia, particularly the Gcc: header for
5754 Additional valid symbols may be available; check with the author of
5755 your package for details. The function should return non-nil if it
5758 See also `read-mail-command' concerning reading mail."
5759 :type '(radio (function-item :tag "Message package"
5762 (function-item :tag "Mail package"
5764 sendmail-user-agent)
5765 (function-item :tag "Emacs interface to MH"
5768 (function-item :tag "Message with full Gnus features"
5771 (function :tag "Other"))
5772 :version "23.2" ; sendmail->message
5775 (defcustom compose-mail-user-agent-warnings t
5776 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
5777 If the value of `mail-user-agent' is the default, and the user
5778 appears to have customizations applying to the old default,
5779 `compose-mail' issues a warning."
5784 (defun rfc822-goto-eoh ()
5785 "If the buffer starts with a mail header, move point to the header's end.
5786 Otherwise, moves to `point-min'.
5787 The end of the header is the start of the next line, if there is one,
5788 else the end of the last line. This function obeys RFC822."
5789 (goto-char (point-min))
5790 (when (re-search-forward
5791 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5792 (goto-char (match-beginning 0))))
5794 (defun compose-mail (&optional to subject other-headers continue
5795 switch-function yank-action send-actions
5797 "Start composing a mail message to send.
5798 This uses the user's chosen mail composition package
5799 as selected with the variable `mail-user-agent'.
5800 The optional arguments TO and SUBJECT specify recipients
5801 and the initial Subject field, respectively.
5803 OTHER-HEADERS is an alist specifying additional
5804 header fields. Elements look like (HEADER . VALUE) where both
5805 HEADER and VALUE are strings.
5807 CONTINUE, if non-nil, says to continue editing a message already
5808 being composed. Interactively, CONTINUE is the prefix argument.
5810 SWITCH-FUNCTION, if non-nil, is a function to use to
5811 switch to and display the buffer used for mail composition.
5813 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
5814 to insert the raw text of the message being replied to.
5815 It has the form (FUNCTION . ARGS). The user agent will apply
5816 FUNCTION to ARGS, to insert the raw text of the original message.
5817 \(The user agent will also run `mail-citation-hook', *after* the
5818 original text has been inserted in this way.)
5820 SEND-ACTIONS is a list of actions to call when the message is sent.
5821 Each action has the form (FUNCTION . ARGS).
5823 RETURN-ACTION, if non-nil, is an action for returning to the
5824 caller. It has the form (FUNCTION . ARGS). The function is
5825 called after the mail has been sent or put aside, and the mail
5828 (list nil nil nil current-prefix-arg))
5830 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
5831 ;; from sendmail-user-agent to message-user-agent. Some users may
5832 ;; encounter incompatibilities. This hack tries to detect problems
5833 ;; and warn about them.
5834 (and compose-mail-user-agent-warnings
5835 (eq mail-user-agent 'message-user-agent)
5837 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
5838 mail-yank-hooks mail-archive-file-name
5839 mail-default-reply-to mail-mailing-lists
5843 (push var warn-vars)))
5845 (display-warning 'mail
5847 The default mail mode is now Message mode.
5848 You have the following Mail mode variable%s customized:
5849 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
5850 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
5851 (if (> (length warn-vars) 1) "s" "")
5852 (mapconcat 'symbol-name
5855 (let ((function (get mail-user-agent 'composefunc)))
5856 (funcall function to subject other-headers continue switch-function
5857 yank-action send-actions return-action)))
5859 (defun compose-mail-other-window (&optional to subject other-headers continue
5860 yank-action send-actions
5862 "Like \\[compose-mail], but edit the outgoing message in another window."
5863 (interactive (list nil nil nil current-prefix-arg))
5864 (compose-mail to subject other-headers continue
5865 'switch-to-buffer-other-window yank-action send-actions
5868 (defun compose-mail-other-frame (&optional to subject other-headers continue
5869 yank-action send-actions
5871 "Like \\[compose-mail], but edit the outgoing message in another frame."
5872 (interactive (list nil nil nil current-prefix-arg))
5873 (compose-mail to subject other-headers continue
5874 'switch-to-buffer-other-frame yank-action send-actions
5878 (defvar set-variable-value-history nil
5879 "History of values entered with `set-variable'.
5881 Maximum length of the history list is determined by the value
5882 of `history-length', which see.")
5884 (defun set-variable (variable value &optional make-local)
5885 "Set VARIABLE to VALUE. VALUE is a Lisp object.
5886 VARIABLE should be a user option variable name, a Lisp variable
5887 meant to be customized by users. You should enter VALUE in Lisp syntax,
5888 so if you want VALUE to be a string, you must surround it with doublequotes.
5889 VALUE is used literally, not evaluated.
5891 If VARIABLE has a `variable-interactive' property, that is used as if
5892 it were the arg to `interactive' (which see) to interactively read VALUE.
5894 If VARIABLE has been defined with `defcustom', then the type information
5895 in the definition is used to check that VALUE is valid.
5897 With a prefix argument, set VARIABLE to VALUE buffer-locally."
5899 (let* ((default-var (variable-at-point))
5900 (var (if (user-variable-p default-var)
5901 (read-variable (format "Set variable (default %s): " default-var)
5903 (read-variable "Set variable: ")))
5904 (minibuffer-help-form '(describe-variable var))
5905 (prop (get var 'variable-interactive))
5906 (obsolete (car (get var 'byte-obsolete-variable)))
5907 (prompt (format "Set %s %s to value: " var
5908 (cond ((local-variable-p var)
5910 ((or current-prefix-arg
5911 (local-variable-if-set-p var))
5916 (message (concat "`%S' is obsolete; "
5917 (if (symbolp obsolete) "use `%S' instead" "%s"))
5921 ;; Use VAR's `variable-interactive' property
5922 ;; as an interactive spec for prompting.
5923 (call-interactively `(lambda (arg)
5927 (read-string prompt nil
5928 'set-variable-value-history
5929 (format "%S" (symbol-value var))))))))
5930 (list var val current-prefix-arg)))
5932 (and (custom-variable-p variable)
5933 (not (get variable 'custom-type))
5934 (custom-load-symbol variable))
5935 (let ((type (get variable 'custom-type)))
5937 ;; Match with custom type.
5939 (setq type (widget-convert type))
5940 (unless (widget-apply type :match value)
5941 (error "Value `%S' does not match type %S of %S"
5942 value (car type) variable))))
5945 (make-local-variable variable))
5947 (set variable value)
5949 ;; Force a thorough redisplay for the case that the variable
5950 ;; has an effect on the display, like `tab-width' has.
5951 (force-mode-line-update))
5953 ;; Define the major mode for lists of completions.
5955 (defvar completion-list-mode-map
5956 (let ((map (make-sparse-keymap)))
5957 (define-key map [mouse-2] 'mouse-choose-completion)
5958 (define-key map [follow-link] 'mouse-face)
5959 (define-key map [down-mouse-2] nil)
5960 (define-key map "\C-m" 'choose-completion)
5961 (define-key map "\e\e\e" 'delete-completion-window)
5962 (define-key map [left] 'previous-completion)
5963 (define-key map [right] 'next-completion)
5964 (define-key map "q" 'quit-window)
5965 (define-key map "z" 'kill-this-buffer)
5967 "Local map for completion list buffers.")
5969 ;; Completion mode is suitable only for specially formatted data.
5970 (put 'completion-list-mode 'mode-class 'special)
5972 (defvar completion-reference-buffer nil
5973 "Record the buffer that was current when the completion list was requested.
5974 This is a local variable in the completion list buffer.
5975 Initial value is nil to avoid some compiler warnings.")
5977 (defvar completion-no-auto-exit nil
5978 "Non-nil means `choose-completion-string' should never exit the minibuffer.
5979 This also applies to other functions such as `choose-completion'.")
5981 (defvar completion-base-position nil
5982 "Position of the base of the text corresponding to the shown completions.
5983 This variable is used in the *Completions* buffers.
5984 Its value is a list of the form (START END) where START is the place
5985 where the completion should be inserted and END (if non-nil) is the end
5986 of the text to replace. If END is nil, point is used instead.")
5988 (defvar completion-base-size nil
5989 "Number of chars before point not involved in completion.
5990 This is a local variable in the completion list buffer.
5991 It refers to the chars in the minibuffer if completing in the
5992 minibuffer, or in `completion-reference-buffer' otherwise.
5993 Only characters in the field at point are included.
5995 If nil, Emacs determines which part of the tail end of the
5996 buffer's text is involved in completion by comparing the text
5998 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
6000 (defun delete-completion-window ()
6001 "Delete the completion list window.
6002 Go to the window from which completion was requested."
6004 (let ((buf completion-reference-buffer))
6005 (if (one-window-p t)
6006 (if (window-dedicated-p (selected-window))
6007 (delete-frame (selected-frame)))
6008 (delete-window (selected-window))
6009 (if (get-buffer-window buf)
6010 (select-window (get-buffer-window buf))))))
6012 (defun previous-completion (n)
6013 "Move to the previous item in the completion list."
6015 (next-completion (- n)))
6017 (defun next-completion (n)
6018 "Move to the next item in the completion list.
6019 With prefix argument N, move N items (negative N means move backward)."
6021 (let ((beg (point-min)) (end (point-max)))
6022 (while (and (> n 0) (not (eobp)))
6023 ;; If in a completion, move to the end of it.
6024 (when (get-text-property (point) 'mouse-face)
6025 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6026 ;; Move to start of next one.
6027 (unless (get-text-property (point) 'mouse-face)
6028 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6030 (while (and (< n 0) (not (bobp)))
6031 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
6032 ;; If in a completion, move to the start of it.
6033 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
6034 (goto-char (previous-single-property-change
6035 (point) 'mouse-face nil beg)))
6036 ;; Move to end of the previous completion.
6037 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
6038 (goto-char (previous-single-property-change
6039 (point) 'mouse-face nil beg)))
6040 ;; Move to the start of that one.
6041 (goto-char (previous-single-property-change
6042 (point) 'mouse-face nil beg))
6045 (defun choose-completion (&optional event)
6046 "Choose the completion at point."
6047 (interactive (list last-nonmenu-event))
6048 ;; In case this is run via the mouse, give temporary modes such as
6049 ;; isearch a chance to turn off.
6050 (run-hooks 'mouse-leave-buffer-hook)
6051 (let (buffer base-size base-position choice)
6052 (with-current-buffer (window-buffer (posn-window (event-start event)))
6053 (setq buffer completion-reference-buffer)
6054 (setq base-size completion-base-size)
6055 (setq base-position completion-base-position)
6057 (goto-char (posn-point (event-start event)))
6059 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
6060 (setq end (point) beg (1+ (point))))
6061 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
6062 (setq end (1- (point)) beg (point)))
6064 (error "No completion here"))
6065 (setq beg (previous-single-property-change beg 'mouse-face))
6066 (setq end (or (next-single-property-change end 'mouse-face)
6068 (setq choice (buffer-substring-no-properties beg end)))))
6070 (let ((owindow (selected-window)))
6071 (select-window (posn-window (event-start event)))
6072 (if (and (one-window-p t 'selected-frame)
6073 (window-dedicated-p (selected-window)))
6074 ;; This is a special buffer's frame
6075 (iconify-frame (selected-frame))
6076 (or (window-dedicated-p (selected-window))
6079 (or (and (buffer-live-p buffer)
6080 (get-buffer-window buffer 0))
6083 (choose-completion-string
6087 ;; Someone's using old completion code that doesn't know
6088 ;; about base-position yet.
6089 (list (+ base-size (with-current-buffer buffer (field-beginning)))))
6090 ;; If all else fails, just guess.
6091 (with-current-buffer buffer
6092 (list (choose-completion-guess-base-position choice)))))))
6094 ;; Delete the longest partial match for STRING
6095 ;; that can be found before POINT.
6096 (defun choose-completion-guess-base-position (string)
6098 (let ((opoint (point))
6100 ;; Try moving back by the length of the string.
6101 (goto-char (max (- (point) (length string))
6102 (minibuffer-prompt-end)))
6103 ;; See how far back we were actually able to move. That is the
6104 ;; upper bound on how much we can match and delete.
6105 (setq len (- opoint (point)))
6106 (if completion-ignore-case
6107 (setq string (downcase string)))
6108 (while (and (> len 0)
6109 (let ((tail (buffer-substring (point) opoint)))
6110 (if completion-ignore-case
6111 (setq tail (downcase tail)))
6112 (not (string= tail (substring string 0 len)))))
6117 (defun choose-completion-delete-max-match (string)
6118 (delete-region (choose-completion-guess-base-position string) (point)))
6119 (make-obsolete 'choose-completion-delete-max-match
6120 'choose-completion-guess-base-position "23.2")
6122 (defvar choose-completion-string-functions nil
6123 "Functions that may override the normal insertion of a completion choice.
6124 These functions are called in order with four arguments:
6125 CHOICE - the string to insert in the buffer,
6126 BUFFER - the buffer in which the choice should be inserted,
6127 MINI-P - non-nil if BUFFER is a minibuffer, and
6128 BASE-SIZE - the number of characters in BUFFER before
6129 the string being completed.
6131 If a function in the list returns non-nil, that function is supposed
6132 to have inserted the CHOICE in the BUFFER, and possibly exited
6133 the minibuffer; no further functions will be called.
6135 If all functions in the list return nil, that means to use
6136 the default method of inserting the completion in BUFFER.")
6138 (defun choose-completion-string (choice &optional buffer base-position)
6139 "Switch to BUFFER and insert the completion choice CHOICE.
6140 BASE-POSITION, says where to insert the completion."
6142 ;; If BUFFER is the minibuffer, exit the minibuffer
6143 ;; unless it is reading a file name and CHOICE is a directory,
6144 ;; or completion-no-auto-exit is non-nil.
6146 ;; Some older code may call us passing `base-size' instead of
6147 ;; `base-position'. It's difficult to make any use of `base-size',
6148 ;; so we just ignore it.
6149 (unless (consp base-position)
6150 (message "Obsolete `base-size' passed to choose-completion-string")
6151 (setq base-position nil))
6153 (let* ((buffer (or buffer completion-reference-buffer))
6154 (mini-p (minibufferp buffer)))
6155 ;; If BUFFER is a minibuffer, barf unless it's the currently
6156 ;; active minibuffer.
6158 (or (not (active-minibuffer-window))
6160 (window-buffer (active-minibuffer-window))))))
6161 (error "Minibuffer is not active for completion")
6162 ;; Set buffer so buffer-local choose-completion-string-functions works.
6164 (unless (run-hook-with-args-until-success
6165 'choose-completion-string-functions
6166 ;; The fourth arg used to be `mini-p' but was useless
6167 ;; (since minibufferp can be used on the `buffer' arg)
6168 ;; and indeed unused. The last used to be `base-size', so we
6169 ;; keep it to try and avoid breaking old code.
6170 choice buffer base-position nil)
6171 ;; Insert the completion into the buffer where it was requested.
6172 (delete-region (or (car base-position) (point))
6173 (or (cadr base-position) (point)))
6175 (remove-text-properties (- (point) (length choice)) (point)
6177 ;; Update point in the window that BUFFER is showing in.
6178 (let ((window (get-buffer-window buffer t)))
6179 (set-window-point window (point)))
6180 ;; If completing for the minibuffer, exit it with this choice.
6181 (and (not completion-no-auto-exit)
6182 (minibufferp buffer)
6183 minibuffer-completion-table
6184 ;; If this is reading a file name, and the file name chosen
6185 ;; is a directory, don't exit the minibuffer.
6186 (let* ((result (buffer-substring (field-beginning) (point)))
6188 (completion-boundaries result minibuffer-completion-table
6189 minibuffer-completion-predicate
6191 (if (eq (car bounds) (length result))
6192 ;; The completion chosen leads to a new set of completions
6193 ;; (e.g. it's a directory): don't exit the minibuffer yet.
6194 (let ((mini (active-minibuffer-window)))
6195 (select-window mini)
6196 (when minibuffer-auto-raise
6197 (raise-frame (window-frame mini))))
6198 (exit-minibuffer))))))))
6200 (define-derived-mode completion-list-mode nil "Completion List"
6201 "Major mode for buffers showing lists of possible completions.
6202 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
6203 to select the completion near point.
6204 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
6207 \\{completion-list-mode-map}"
6208 (set (make-local-variable 'completion-base-size) nil))
6210 (defun completion-list-mode-finish ()
6211 "Finish setup of the completions buffer.
6212 Called from `temp-buffer-show-hook'."
6213 (when (eq major-mode 'completion-list-mode)
6214 (toggle-read-only 1)))
6216 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
6219 ;; Variables and faces used in `completion-setup-function'.
6221 (defcustom completion-show-help t
6222 "Non-nil means show help message in *Completions* buffer."
6227 ;; This function goes in completion-setup-hook, so that it is called
6228 ;; after the text of the completion list buffer is written.
6229 (defun completion-setup-function ()
6230 (let* ((mainbuf (current-buffer))
6232 ;; When reading a file name in the minibuffer,
6233 ;; try and find the right default-directory to set in the
6234 ;; completion list buffer.
6235 ;; FIXME: Why do we do that, actually? --Stef
6236 (if minibuffer-completing-file-name
6237 (file-name-as-directory
6239 (substring (minibuffer-completion-contents)
6240 0 (or completion-base-size 0)))))))
6241 (with-current-buffer standard-output
6242 (let ((base-size completion-base-size) ;Read before killing localvars.
6243 (base-position completion-base-position))
6244 (completion-list-mode)
6245 (set (make-local-variable 'completion-base-size) base-size)
6246 (set (make-local-variable 'completion-base-position) base-position))
6247 (set (make-local-variable 'completion-reference-buffer) mainbuf)
6248 (if base-dir (setq default-directory base-dir))
6249 ;; Maybe insert help string.
6250 (when completion-show-help
6251 (goto-char (point-min))
6252 (if (display-mouse-p)
6253 (insert (substitute-command-keys
6254 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
6255 (insert (substitute-command-keys
6256 "In this buffer, type \\[choose-completion] to \
6257 select the completion near point.\n\n"))))))
6259 (add-hook 'completion-setup-hook 'completion-setup-function)
6261 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
6262 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
6264 (defun switch-to-completions ()
6265 "Select the completion list window."
6267 (let ((window (or (get-buffer-window "*Completions*" 0)
6268 ;; Make sure we have a completions window.
6269 (progn (minibuffer-completion-help)
6270 (get-buffer-window "*Completions*" 0)))))
6272 (select-window window)
6273 ;; In the new buffer, go to the first completion.
6274 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
6276 (next-completion 1)))))
6278 ;;; Support keyboard commands to turn on various modifiers.
6280 ;; These functions -- which are not commands -- each add one modifier
6281 ;; to the following event.
6283 (defun event-apply-alt-modifier (_ignore-prompt)
6284 "\\<function-key-map>Add the Alt modifier to the following event.
6285 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
6286 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
6287 (defun event-apply-super-modifier (_ignore-prompt)
6288 "\\<function-key-map>Add the Super modifier to the following event.
6289 For example, type \\[event-apply-super-modifier] & to enter Super-&."
6290 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
6291 (defun event-apply-hyper-modifier (_ignore-prompt)
6292 "\\<function-key-map>Add the Hyper modifier to the following event.
6293 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
6294 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
6295 (defun event-apply-shift-modifier (_ignore-prompt)
6296 "\\<function-key-map>Add the Shift modifier to the following event.
6297 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
6298 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
6299 (defun event-apply-control-modifier (_ignore-prompt)
6300 "\\<function-key-map>Add the Ctrl modifier to the following event.
6301 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
6302 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
6303 (defun event-apply-meta-modifier (_ignore-prompt)
6304 "\\<function-key-map>Add the Meta modifier to the following event.
6305 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
6306 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
6308 (defun event-apply-modifier (event symbol lshiftby prefix)
6309 "Apply a modifier flag to event EVENT.
6310 SYMBOL is the name of this modifier, as a symbol.
6311 LSHIFTBY is the numeric value of this modifier, in keyboard events.
6312 PREFIX is the string that represents this modifier in an event type symbol."
6314 (cond ((eq symbol 'control)
6315 (if (and (<= (downcase event) ?z)
6316 (>= (downcase event) ?a))
6317 (- (downcase event) ?a -1)
6318 (if (and (<= (downcase event) ?Z)
6319 (>= (downcase event) ?A))
6320 (- (downcase event) ?A -1)
6321 (logior (lsh 1 lshiftby) event))))
6323 (if (and (<= (downcase event) ?z)
6324 (>= (downcase event) ?a))
6326 (logior (lsh 1 lshiftby) event)))
6328 (logior (lsh 1 lshiftby) event)))
6329 (if (memq symbol (event-modifiers event))
6331 (let ((event-type (if (symbolp event) event (car event))))
6332 (setq event-type (intern (concat prefix (symbol-name event-type))))
6335 (cons event-type (cdr event)))))))
6337 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
6338 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
6339 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
6340 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
6341 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
6342 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
6344 ;;;; Keypad support.
6346 ;; Make the keypad keys act like ordinary typing keys. If people add
6347 ;; bindings for the function key symbols, then those bindings will
6348 ;; override these, so this shouldn't interfere with any existing
6351 ;; Also tell read-char how to handle these keys.
6353 (lambda (keypad-normal)
6354 (let ((keypad (nth 0 keypad-normal))
6355 (normal (nth 1 keypad-normal)))
6356 (put keypad 'ascii-character normal)
6357 (define-key function-key-map (vector keypad) (vector normal))))
6358 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
6359 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
6370 ;; Do the same for various keys that are represented as symbols under
6371 ;; GUIs but naturally correspond to characters.
6382 ;;;; forking a twin copy of a buffer.
6385 (defvar clone-buffer-hook nil
6386 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
6388 (defvar clone-indirect-buffer-hook nil
6389 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
6391 (defun clone-process (process &optional newname)
6392 "Create a twin copy of PROCESS.
6393 If NEWNAME is nil, it defaults to PROCESS' name;
6394 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
6395 If PROCESS is associated with a buffer, the new process will be associated
6396 with the current buffer instead.
6397 Returns nil if PROCESS has already terminated."
6398 (setq newname (or newname (process-name process)))
6399 (if (string-match "<[0-9]+>\\'" newname)
6400 (setq newname (substring newname 0 (match-beginning 0))))
6401 (when (memq (process-status process) '(run stop open))
6402 (let* ((process-connection-type (process-tty-name process))
6404 (if (memq (process-status process) '(open))
6405 (let ((args (process-contact process t)))
6406 (setq args (plist-put args :name newname))
6407 (setq args (plist-put args :buffer
6408 (if (process-buffer process)
6410 (apply 'make-network-process args))
6411 (apply 'start-process newname
6412 (if (process-buffer process) (current-buffer))
6413 (process-command process)))))
6414 (set-process-query-on-exit-flag
6415 new-process (process-query-on-exit-flag process))
6416 (set-process-inherit-coding-system-flag
6417 new-process (process-inherit-coding-system-flag process))
6418 (set-process-filter new-process (process-filter process))
6419 (set-process-sentinel new-process (process-sentinel process))
6420 (set-process-plist new-process (copy-sequence (process-plist process)))
6423 ;; things to maybe add (currently partly covered by `funcall mode'):
6426 (defun clone-buffer (&optional newname display-flag)
6427 "Create and return a twin copy of the current buffer.
6428 Unlike an indirect buffer, the new buffer can be edited
6429 independently of the old one (if it is not read-only).
6430 NEWNAME is the name of the new buffer. It may be modified by
6431 adding or incrementing <N> at the end as necessary to create a
6432 unique buffer name. If nil, it defaults to the name of the
6433 current buffer, with the proper suffix. If DISPLAY-FLAG is
6434 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
6435 clone a file-visiting buffer, or a buffer whose major mode symbol
6436 has a non-nil `no-clone' property, results in an error.
6438 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
6439 current buffer with appropriate suffix. However, if a prefix
6440 argument is given, then the command prompts for NEWNAME in the
6443 This runs the normal hook `clone-buffer-hook' in the new buffer
6444 after it has been set up properly in other respects."
6447 (if buffer-file-name
6448 (error "Cannot clone a file-visiting buffer"))
6449 (if (get major-mode 'no-clone)
6450 (error "Cannot clone a buffer in %s mode" mode-name))
6451 (list (if current-prefix-arg
6452 (read-buffer "Name of new cloned buffer: " (current-buffer)))
6454 (if buffer-file-name
6455 (error "Cannot clone a file-visiting buffer"))
6456 (if (get major-mode 'no-clone)
6457 (error "Cannot clone a buffer in %s mode" mode-name))
6458 (setq newname (or newname (buffer-name)))
6459 (if (string-match "<[0-9]+>\\'" newname)
6460 (setq newname (substring newname 0 (match-beginning 0))))
6461 (let ((buf (current-buffer))
6465 (mk (if mark-active (mark t)))
6466 (modified (buffer-modified-p))
6468 (lvars (buffer-local-variables))
6469 (process (get-buffer-process (current-buffer)))
6470 (new (generate-new-buffer (or newname (buffer-name)))))
6473 (with-current-buffer new
6474 (insert-buffer-substring buf)))
6475 (with-current-buffer new
6476 (narrow-to-region ptmin ptmax)
6478 (if mk (set-mark mk))
6479 (set-buffer-modified-p modified)
6481 ;; Clone the old buffer's process, if any.
6482 (when process (clone-process process))
6484 ;; Now set up the major mode.
6487 ;; Set up other local variables.
6489 (condition-case () ;in case var is read-only
6492 (set (make-local-variable (car v)) (cdr v)))
6496 ;; Run any hooks (typically set up by the major mode
6497 ;; for cloning to work properly).
6498 (run-hooks 'clone-buffer-hook))
6500 ;; Presumably the current buffer is shown in the selected frame, so
6501 ;; we want to display the clone elsewhere.
6502 (let ((same-window-regexps nil)
6503 (same-window-buffer-names))
6504 (pop-to-buffer new)))
6508 (defun clone-indirect-buffer (newname display-flag &optional norecord)
6509 "Create an indirect buffer that is a twin copy of the current buffer.
6511 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
6512 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6513 or if not called with a prefix arg, NEWNAME defaults to the current
6514 buffer's name. The name is modified by adding a `<N>' suffix to it
6515 or by incrementing the N in an existing suffix. Trying to clone a
6516 buffer whose major mode symbol has a non-nil `no-clone-indirect'
6517 property results in an error.
6519 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
6520 This is always done when called interactively.
6522 Optional third arg NORECORD non-nil means do not put this buffer at the
6523 front of the list of recently selected ones."
6526 (if (get major-mode 'no-clone-indirect)
6527 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6528 (list (if current-prefix-arg
6529 (read-buffer "Name of indirect buffer: " (current-buffer)))
6531 (if (get major-mode 'no-clone-indirect)
6532 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6533 (setq newname (or newname (buffer-name)))
6534 (if (string-match "<[0-9]+>\\'" newname)
6535 (setq newname (substring newname 0 (match-beginning 0))))
6536 (let* ((name (generate-new-buffer-name newname))
6537 (buffer (make-indirect-buffer (current-buffer) name t)))
6538 (with-current-buffer buffer
6539 (run-hooks 'clone-indirect-buffer-hook))
6541 (pop-to-buffer buffer norecord))
6545 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6546 "Like `clone-indirect-buffer' but display in another window."
6549 (if (get major-mode 'no-clone-indirect)
6550 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6551 (list (if current-prefix-arg
6552 (read-buffer "Name of indirect buffer: " (current-buffer)))
6554 (let ((pop-up-windows t))
6555 (clone-indirect-buffer newname display-flag norecord)))
6558 ;;; Handling of Backspace and Delete keys.
6560 (defcustom normal-erase-is-backspace 'maybe
6561 "Set the default behavior of the Delete and Backspace keys.
6563 If set to t, Delete key deletes forward and Backspace key deletes
6566 If set to nil, both Delete and Backspace keys delete backward.
6568 If set to 'maybe (which is the default), Emacs automatically
6569 selects a behavior. On window systems, the behavior depends on
6570 the keyboard used. If the keyboard has both a Backspace key and
6571 a Delete key, and both are mapped to their usual meanings, the
6572 option's default value is set to t, so that Backspace can be used
6573 to delete backward, and Delete can be used to delete forward.
6575 If not running under a window system, customizing this option
6576 accomplishes a similar effect by mapping C-h, which is usually
6577 generated by the Backspace key, to DEL, and by mapping DEL to C-d
6578 via `keyboard-translate'. The former functionality of C-h is
6579 available on the F1 key. You should probably not use this
6580 setting if you don't have both Backspace, Delete and F1 keys.
6582 Setting this variable with setq doesn't take effect. Programmatically,
6583 call `normal-erase-is-backspace-mode' (which see) instead."
6584 :type '(choice (const :tag "Off" nil)
6585 (const :tag "Maybe" maybe)
6586 (other :tag "On" t))
6587 :group 'editing-basics
6589 :set (lambda (symbol value)
6590 ;; The fboundp is because of a problem with :set when
6591 ;; dumping Emacs. It doesn't really matter.
6592 (if (fboundp 'normal-erase-is-backspace-mode)
6593 (normal-erase-is-backspace-mode (or value 0))
6594 (set-default symbol value))))
6596 (defun normal-erase-is-backspace-setup-frame (&optional frame)
6597 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6598 (unless frame (setq frame (selected-frame)))
6599 (with-selected-frame frame
6600 (unless (terminal-parameter nil 'normal-erase-is-backspace)
6601 (normal-erase-is-backspace-mode
6602 (if (if (eq normal-erase-is-backspace 'maybe)
6603 (and (not noninteractive)
6604 (or (memq system-type '(ms-dos windows-nt))
6605 (memq window-system '(ns))
6606 (and (memq window-system '(x))
6607 (fboundp 'x-backspace-delete-keys-p)
6608 (x-backspace-delete-keys-p))
6609 ;; If the terminal Emacs is running on has erase char
6610 ;; set to ^H, use the Backspace key for deleting
6611 ;; backward, and the Delete key for deleting forward.
6612 (and (null window-system)
6613 (eq tty-erase-char ?\^H))))
6614 normal-erase-is-backspace)
6617 (define-minor-mode normal-erase-is-backspace-mode
6618 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6620 With numeric ARG, turn the mode on if and only if ARG is positive.
6622 On window systems, when this mode is on, Delete is mapped to C-d
6623 and Backspace is mapped to DEL; when this mode is off, both
6624 Delete and Backspace are mapped to DEL. (The remapping goes via
6625 `local-function-key-map', so binding Delete or Backspace in the
6626 global or local keymap will override that.)
6628 In addition, on window systems, the bindings of C-Delete, M-Delete,
6629 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6630 the global keymap in accordance with the functionality of Delete and
6631 Backspace. For example, if Delete is remapped to C-d, which deletes
6632 forward, C-Delete is bound to `kill-word', but if Delete is remapped
6633 to DEL, which deletes backward, C-Delete is bound to
6634 `backward-kill-word'.
6636 If not running on a window system, a similar effect is accomplished by
6637 remapping C-h (normally produced by the Backspace key) and DEL via
6638 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6639 to C-d; if it's off, the keys are not remapped.
6641 When not running on a window system, and this mode is turned on, the
6642 former functionality of C-h is available on the F1 key. You should
6643 probably not turn on this mode on a text-only terminal if you don't
6644 have both Backspace, Delete and F1 keys.
6646 See also `normal-erase-is-backspace'."
6647 :variable (eq (terminal-parameter
6648 nil 'normal-erase-is-backspace) 1)
6649 (let ((enabled (eq 1 (terminal-parameter
6650 nil 'normal-erase-is-backspace))))
6652 (cond ((or (memq window-system '(x w32 ns pc))
6653 (memq system-type '(ms-dos windows-nt)))
6655 `(([M-delete] [M-backspace])
6656 ([C-M-delete] [C-M-backspace])
6657 ([?\e C-delete] [?\e C-backspace]))))
6661 (define-key local-function-key-map [delete] [deletechar])
6662 (define-key local-function-key-map [kp-delete] [?\C-d])
6663 (define-key local-function-key-map [backspace] [?\C-?])
6664 (dolist (b bindings)
6665 ;; Not sure if input-decode-map is really right, but
6666 ;; keyboard-translate-table (used below) only works
6667 ;; for integer events, and key-translation-table is
6668 ;; global (like the global-map, used earlier).
6669 (define-key input-decode-map (car b) nil)
6670 (define-key input-decode-map (cadr b) nil)))
6671 (define-key local-function-key-map [delete] [?\C-?])
6672 (define-key local-function-key-map [kp-delete] [?\C-?])
6673 (define-key local-function-key-map [backspace] [?\C-?])
6674 (dolist (b bindings)
6675 (define-key input-decode-map (car b) (cadr b))
6676 (define-key input-decode-map (cadr b) (car b))))))
6680 (keyboard-translate ?\C-h ?\C-?)
6681 (keyboard-translate ?\C-? ?\C-d))
6682 (keyboard-translate ?\C-h ?\C-h)
6683 (keyboard-translate ?\C-? ?\C-?))))
6685 (if (called-interactively-p 'interactive)
6686 (message "Delete key deletes %s"
6687 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
6688 "forward" "backward")))))
6690 (defvar vis-mode-saved-buffer-invisibility-spec nil
6691 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
6693 (define-minor-mode visible-mode
6694 "Toggle Visible mode.
6695 With argument ARG turn Visible mode on if ARG is positive, otherwise
6698 Enabling Visible mode makes all invisible text temporarily visible.
6699 Disabling Visible mode turns off that effect. Visible mode works by
6700 saving the value of `buffer-invisibility-spec' and setting it to nil."
6702 :group 'editing-basics
6703 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6704 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6705 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
6707 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6708 buffer-invisibility-spec)
6709 (setq buffer-invisibility-spec nil)))
6711 ;; Minibuffer prompt stuff.
6713 ;;(defun minibuffer-prompt-modification (start end)
6714 ;; (error "You cannot modify the prompt"))
6717 ;;(defun minibuffer-prompt-insertion (start end)
6718 ;; (let ((inhibit-modification-hooks t))
6719 ;; (delete-region start end)
6720 ;; ;; Discard undo information for the text insertion itself
6721 ;; ;; and for the text deletion.above.
6722 ;; (when (consp buffer-undo-list)
6723 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
6724 ;; (message "You cannot modify the prompt")))
6727 ;;(setq minibuffer-prompt-properties
6728 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
6729 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
6732 ;;;; Problematic external packages.
6734 ;; rms says this should be done by specifying symbols that define
6735 ;; versions together with bad values. This is therefore not as
6736 ;; flexible as it could be. See the thread:
6737 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6738 (defconst bad-packages-alist
6739 ;; Not sure exactly which semantic versions have problems.
6740 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
6741 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
6742 "The version of `semantic' loaded does not work in Emacs 22.
6743 It can cause constant high CPU load.
6744 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
6745 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6746 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6747 ;; provided the `CUA-mode' feature. Since this is no longer true,
6748 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6750 "CUA-mode is now part of the standard GNU Emacs distribution,
6751 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6753 You have loaded an older version of CUA-mode which does not work
6754 correctly with this version of Emacs. You should remove the old
6755 version and use the one distributed with Emacs."))
6756 "Alist of packages known to cause problems in this version of Emacs.
6757 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6758 PACKAGE is either a regular expression to match file names, or a
6759 symbol (a feature name); see the documentation of
6760 `after-load-alist', to which this variable adds functions.
6761 SYMBOL is either the name of a string variable, or `t'. Upon
6762 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6763 warning using STRING as the message.")
6765 (defun bad-package-check (package)
6766 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6768 (let* ((list (assoc package bad-packages-alist))
6769 (symbol (nth 1 list)))
6773 (and (stringp (setq symbol (eval symbol)))
6774 (string-match-p (nth 2 list) symbol)))
6775 (display-warning package (nth 3 list) :warning)))
6778 (mapc (lambda (elem)
6779 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6785 ;;; simple.el ends here