1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2015 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
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-lib
))
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 (defcustom idle-update-delay
0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
49 "Killing and yanking commands."
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
56 ;;; next-error support framework
58 (defgroup next-error nil
59 "`next-error' support framework."
64 '((t (:inherit region
)))
65 "Face used to highlight next error locus."
69 (defcustom next-error-highlight
0.5
70 "Highlighting of locations in selected source buffers.
71 If a number, highlight the locus in `next-error' face for the given time
72 in seconds, or until the next command is executed.
73 If t, highlight the locus until the next command is executed, or until
74 some other locus replaces it.
75 If nil, don't highlight the locus in the source buffer.
76 If `fringe-arrow', indicate the locus by the fringe arrow
77 indefinitely until some other locus replaces it."
78 :type
'(choice (number :tag
"Highlight for specified time")
79 (const :tag
"Semipermanent highlighting" t
)
80 (const :tag
"No highlighting" nil
)
81 (const :tag
"Fringe arrow" fringe-arrow
))
85 (defcustom next-error-highlight-no-select
0.5
86 "Highlighting of locations in `next-error-no-select'.
87 If number, highlight the locus in `next-error' face for given time in seconds.
88 If t, highlight the locus indefinitely until some other locus replaces it.
89 If nil, don't highlight the locus in the source buffer.
90 If `fringe-arrow', indicate the locus by the fringe arrow
91 indefinitely until some other locus replaces it."
92 :type
'(choice (number :tag
"Highlight for specified time")
93 (const :tag
"Semipermanent highlighting" t
)
94 (const :tag
"No highlighting" nil
)
95 (const :tag
"Fringe arrow" fringe-arrow
))
99 (defcustom next-error-recenter nil
100 "Display the line in the visited source file recentered as specified.
101 If non-nil, the value is passed directly to `recenter'."
102 :type
'(choice (integer :tag
"Line to recenter to")
103 (const :tag
"Center of window" (4))
104 (const :tag
"No recentering" nil
))
108 (defcustom next-error-hook nil
109 "List of hook functions run by `next-error' after visiting source file."
113 (defvar next-error-highlight-timer nil
)
115 (defvar next-error-overlay-arrow-position nil
)
116 (put 'next-error-overlay-arrow-position
'overlay-arrow-string
(purecopy "=>"))
117 (add-to-list 'overlay-arrow-variable-list
'next-error-overlay-arrow-position
)
119 (defvar next-error-last-buffer nil
120 "The most recent `next-error' buffer.
121 A buffer becomes most recent when its compilation, grep, or
122 similar mode is started, or when it is used with \\[next-error]
123 or \\[compile-goto-error].")
125 (defvar next-error-function nil
126 "Function to use to find the next error in the current buffer.
127 The function is called with 2 parameters:
128 ARG is an integer specifying by how many errors to move.
129 RESET is a boolean which, if non-nil, says to go back to the beginning
130 of the errors before moving.
131 Major modes providing compile-like functionality should set this variable
132 to indicate to `next-error' that this is a candidate buffer and how
134 (make-variable-buffer-local 'next-error-function
)
136 (defvar next-error-move-function nil
137 "Function to use to move to an error locus.
138 It takes two arguments, a buffer position in the error buffer
139 and a buffer position in the error locus buffer.
140 The buffer for the error locus should already be current.
141 nil means use goto-char using the second argument position.")
142 (make-variable-buffer-local 'next-error-move-function
)
144 (defsubst next-error-buffer-p
(buffer
145 &optional avoid-current
147 extra-test-exclusive
)
148 "Test if BUFFER is a `next-error' capable buffer.
150 If AVOID-CURRENT is non-nil, treat the current buffer
151 as an absolute last resort only.
153 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
154 that normally would not qualify. If it returns t, the buffer
155 in question is treated as usable.
157 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
158 that would normally be considered usable. If it returns nil,
159 that buffer is rejected."
160 (and (buffer-name buffer
) ;First make sure it's live.
161 (not (and avoid-current
(eq buffer
(current-buffer))))
162 (with-current-buffer buffer
163 (if next-error-function
; This is the normal test.
164 ;; Optionally reject some buffers.
165 (if extra-test-exclusive
166 (funcall extra-test-exclusive
)
168 ;; Optionally accept some other buffers.
169 (and extra-test-inclusive
170 (funcall extra-test-inclusive
))))))
172 (defun next-error-find-buffer (&optional avoid-current
174 extra-test-exclusive
)
175 "Return a `next-error' capable buffer.
177 If AVOID-CURRENT is non-nil, treat the current buffer
178 as an absolute last resort only.
180 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
181 that normally would not qualify. If it returns t, the buffer
182 in question is treated as usable.
184 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
185 that would normally be considered usable. If it returns nil,
186 that buffer is rejected."
188 ;; 1. If one window on the selected frame displays such buffer, return it.
189 (let ((window-buffers
191 (delq nil
(mapcar (lambda (w)
192 (if (next-error-buffer-p
195 extra-test-inclusive extra-test-exclusive
)
198 (if (eq (length window-buffers
) 1)
199 (car window-buffers
)))
200 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
201 (if (and next-error-last-buffer
202 (next-error-buffer-p next-error-last-buffer avoid-current
203 extra-test-inclusive extra-test-exclusive
))
204 next-error-last-buffer
)
205 ;; 3. If the current buffer is acceptable, choose it.
206 (if (next-error-buffer-p (current-buffer) avoid-current
207 extra-test-inclusive extra-test-exclusive
)
209 ;; 4. Look for any acceptable buffer.
210 (let ((buffers (buffer-list)))
212 (not (next-error-buffer-p
213 (car buffers
) avoid-current
214 extra-test-inclusive extra-test-exclusive
)))
215 (setq buffers
(cdr buffers
)))
217 ;; 5. Use the current buffer as a last resort if it qualifies,
218 ;; even despite AVOID-CURRENT.
220 (next-error-buffer-p (current-buffer) nil
221 extra-test-inclusive extra-test-exclusive
)
223 (message "This is the only buffer with error message locations")
226 (error "No buffers contain error message locations")))
228 (defun next-error (&optional arg reset
)
229 "Visit next `next-error' message and corresponding source code.
231 If all the error messages parsed so far have been processed already,
232 the message buffer is checked for new ones.
234 A prefix ARG specifies how many error messages to move;
235 negative means move back to previous error messages.
236 Just \\[universal-argument] as a prefix means reparse the error message buffer
237 and start at the first error.
239 The RESET argument specifies that we should restart from the beginning.
241 \\[next-error] normally uses the most recently started
242 compilation, grep, or occur buffer. It can also operate on any
243 buffer with output from the \\[compile], \\[grep] commands, or,
244 more generally, on any buffer in Compilation mode or with
245 Compilation Minor mode enabled, or any buffer in which
246 `next-error-function' is bound to an appropriate function.
247 To specify use of a particular buffer for error messages, type
248 \\[next-error] in that buffer when it is the only one displayed
249 in the current frame.
251 Once \\[next-error] has chosen the buffer for error messages, it
252 runs `next-error-hook' with `run-hooks', and stays with that buffer
253 until you use it in some other buffer which uses Compilation mode
254 or Compilation Minor mode.
256 To control which errors are matched, customize the variable
257 `compilation-error-regexp-alist'."
259 (if (consp arg
) (setq reset t arg nil
))
260 (when (setq next-error-last-buffer
(next-error-find-buffer))
261 ;; we know here that next-error-function is a valid symbol we can funcall
262 (with-current-buffer next-error-last-buffer
263 (funcall next-error-function
(prefix-numeric-value arg
) reset
)
264 (when next-error-recenter
265 (recenter next-error-recenter
))
266 (run-hooks 'next-error-hook
))))
268 (defun next-error-internal ()
269 "Visit the source code corresponding to the `next-error' message at point."
270 (setq next-error-last-buffer
(current-buffer))
271 ;; we know here that next-error-function is a valid symbol we can funcall
272 (with-current-buffer next-error-last-buffer
273 (funcall next-error-function
0 nil
)
274 (when next-error-recenter
275 (recenter next-error-recenter
))
276 (run-hooks 'next-error-hook
)))
278 (defalias 'goto-next-locus
'next-error
)
279 (defalias 'next-match
'next-error
)
281 (defun previous-error (&optional n
)
282 "Visit previous `next-error' message and corresponding source code.
284 Prefix arg N says how many error messages to move backwards (or
285 forwards, if negative).
287 This operates on the output from the \\[compile] and \\[grep] commands."
289 (next-error (- (or n
1))))
291 (defun first-error (&optional n
)
292 "Restart at the first error.
293 Visit corresponding source code.
294 With prefix arg N, visit the source code of the Nth error.
295 This operates on the output from the \\[compile] command, for instance."
299 (defun next-error-no-select (&optional n
)
300 "Move point to the next error in the `next-error' buffer and highlight match.
301 Prefix arg N says how many error messages to move forwards (or
302 backwards, if negative).
303 Finds and highlights the source line like \\[next-error], but does not
304 select the source buffer."
306 (let ((next-error-highlight next-error-highlight-no-select
))
308 (pop-to-buffer next-error-last-buffer
))
310 (defun previous-error-no-select (&optional n
)
311 "Move point to the previous error in the `next-error' buffer and highlight match.
312 Prefix arg N says how many error messages to move backwards (or
313 forwards, if negative).
314 Finds and highlights the source line like \\[previous-error], but does not
315 select the source buffer."
317 (next-error-no-select (- (or n
1))))
319 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
320 (defvar next-error-follow-last-line nil
)
322 (define-minor-mode next-error-follow-minor-mode
323 "Minor mode for compilation, occur and diff modes.
324 With a prefix argument ARG, enable mode if ARG is positive, and
325 disable it otherwise. If called from Lisp, enable mode if ARG is
327 When turned on, cursor motion in the compilation, grep, occur or diff
328 buffer causes automatic display of the corresponding source code location."
329 :group
'next-error
:init-value nil
:lighter
" Fol"
330 (if (not next-error-follow-minor-mode
)
331 (remove-hook 'post-command-hook
'next-error-follow-mode-post-command-hook t
)
332 (add-hook 'post-command-hook
'next-error-follow-mode-post-command-hook nil t
)
333 (make-local-variable 'next-error-follow-last-line
)))
335 ;; Used as a `post-command-hook' by `next-error-follow-mode'
336 ;; for the *Compilation* *grep* and *Occur* buffers.
337 (defun next-error-follow-mode-post-command-hook ()
338 (unless (equal next-error-follow-last-line
(line-number-at-pos))
339 (setq next-error-follow-last-line
(line-number-at-pos))
341 (let ((compilation-context-lines nil
))
342 (setq compilation-current-error
(point))
343 (next-error-no-select 0))
349 (defun fundamental-mode ()
350 "Major mode not specialized for anything in particular.
351 Other major modes are defined by comparison with this one."
353 (kill-all-local-variables)
356 ;; Special major modes to view specially formatted data rather than files.
358 (defvar special-mode-map
359 (let ((map (make-sparse-keymap)))
360 (suppress-keymap map
)
361 (define-key map
"q" 'quit-window
)
362 (define-key map
" " 'scroll-up-command
)
363 (define-key map
[?\S-\
] 'scroll-down-command
)
364 (define-key map
"\C-?" 'scroll-down-command
)
365 (define-key map
"?" 'describe-mode
)
366 (define-key map
"h" 'describe-mode
)
367 (define-key map
">" 'end-of-buffer
)
368 (define-key map
"<" 'beginning-of-buffer
)
369 (define-key map
"g" 'revert-buffer
)
372 (put 'special-mode
'mode-class
'special
)
373 (define-derived-mode special-mode nil
"Special"
374 "Parent major mode from which special major modes should inherit."
375 (setq buffer-read-only t
))
377 ;; Making and deleting lines.
379 (defvar self-insert-uses-region-functions nil
380 "Special hook to tell if `self-insert-command' will use the region.
381 It must be called via `run-hook-with-args-until-success' with no arguments.
382 Any `post-self-insert-command' which consumes the region should
383 register a function on this hook so that things like `delete-selection-mode'
384 can refrain from consuming the region.")
386 (defvar hard-newline
(propertize "\n" 'hard t
'rear-nonsticky
'(hard))
387 "Propertized string representing a hard newline character.")
389 (defun newline (&optional arg interactive
)
390 "Insert a newline, and move to left margin of the new line if it's blank.
391 If option `use-hard-newlines' is non-nil, the newline is marked with the
392 text-property `hard'.
393 With ARG, insert that many newlines.
395 If `electric-indent-mode' is enabled, this indents the final new line
396 that it adds, and reindents the preceding line. To just insert
397 a newline, use \\[electric-indent-just-newline].
399 Calls `auto-fill-function' if the current column number is greater
400 than the value of `fill-column' and ARG is nil.
401 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
402 (interactive "*P\np")
403 (barf-if-buffer-read-only)
404 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
405 ;; Set last-command-event to tell self-insert what to insert.
406 (let* ((was-page-start (and (bolp) (looking-at page-delimiter
)))
408 (last-command-event ?
\n)
409 ;; Don't auto-fill if we have a numeric argument.
410 (auto-fill-function (if arg nil auto-fill-function
))
412 ;; Do the rest in post-self-insert-hook, because we want to do it
413 ;; *before* other functions on that hook.
415 (cl-assert (eq ?
\n (char-before)))
416 ;; Mark the newline(s) `hard'.
417 (if use-hard-newlines
418 (set-hard-newline-properties
419 (- (point) (prefix-numeric-value arg
)) (point)))
420 ;; If the newline leaves the previous line blank, and we
421 ;; have a left margin, delete that from the blank line.
423 (goto-char beforepos
)
425 (and (looking-at "[ \t]$")
426 (> (current-left-margin) 0)
427 (delete-region (point)
428 (line-end-position))))
429 ;; Indent the line after the newline, except in one case:
430 ;; when we added the newline at the beginning of a line which
433 (move-to-left-margin nil t
)))))
435 (if (not interactive
)
436 ;; FIXME: For non-interactive uses, many calls actually just want
437 ;; (insert "\n"), so maybe we should do just that, so as to avoid
438 ;; the risk of filling or running abbrevs unexpectedly.
439 (let ((post-self-insert-hook (list postproc
)))
440 (self-insert-command (prefix-numeric-value arg
)))
443 (add-hook 'post-self-insert-hook postproc nil t
)
444 (self-insert-command (prefix-numeric-value arg
)))
445 ;; We first used let-binding to protect the hook, but that was naive
446 ;; since add-hook affects the symbol-default value of the variable,
447 ;; whereas the let-binding might only protect the buffer-local value.
448 (remove-hook 'post-self-insert-hook postproc t
)))
449 (cl-assert (not (member postproc post-self-insert-hook
)))
450 (cl-assert (not (member postproc
(default-value 'post-self-insert-hook
))))))
453 (defun set-hard-newline-properties (from to
)
454 (let ((sticky (get-text-property from
'rear-nonsticky
)))
455 (put-text-property from to
'hard
't
)
456 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
457 (if (and (listp sticky
) (not (memq 'hard sticky
)))
458 (put-text-property from
(point) 'rear-nonsticky
459 (cons 'hard sticky
)))))
462 "Insert a newline and leave point before it.
463 If there is a fill prefix and/or a `left-margin', insert them
464 on the new line if the line would have been blank.
465 With arg N, insert N newlines."
467 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
468 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
470 ;; Don't expand an abbrev before point.
476 (if do-left-margin
(indent-to (current-left-margin)))
477 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
483 (defun split-line (&optional arg
)
484 "Split current line, moving portion beyond point vertically down.
485 If the current line starts with `fill-prefix', insert it on the new
486 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
488 When called from Lisp code, ARG may be a prefix string to copy."
490 (skip-chars-forward " \t")
491 (let* ((col (current-column))
493 ;; What prefix should we check for (nil means don't).
494 (prefix (cond ((stringp arg
) arg
)
497 ;; Does this line start with it?
498 (have-prfx (and prefix
501 (looking-at (regexp-quote prefix
))))))
503 (if have-prfx
(insert-and-inherit prefix
))
507 (defun delete-indentation (&optional arg
)
508 "Join this line to previous and fix up whitespace at join.
509 If there is a fill prefix, delete it from the beginning of this line.
510 With argument, join this line to following line."
513 (if arg
(forward-line 1))
514 (if (eq (preceding-char) ?
\n)
516 (delete-region (point) (1- (point)))
517 ;; If the second line started with the fill prefix,
518 ;; delete the prefix.
520 (<= (+ (point) (length fill-prefix
)) (point-max))
522 (buffer-substring (point)
523 (+ (point) (length fill-prefix
)))))
524 (delete-region (point) (+ (point) (length fill-prefix
))))
525 (fixup-whitespace))))
527 (defalias 'join-line
#'delete-indentation
) ; easier to find
529 (defun delete-blank-lines ()
530 "On blank line, delete all surrounding blank lines, leaving just one.
531 On isolated blank line, delete that one.
532 On nonblank line, delete any immediately following blank lines."
534 (let (thisblank singleblank
)
537 (setq thisblank
(looking-at "[ \t]*$"))
538 ;; Set singleblank if there is just one blank line here.
541 (not (looking-at "[ \t]*\n[ \t]*$"))
543 (progn (forward-line -
1)
544 (not (looking-at "[ \t]*$")))))))
545 ;; Delete preceding blank lines, and this one too if it's the only one.
549 (if singleblank
(forward-line 1))
550 (delete-region (point)
551 (if (re-search-backward "[^ \t\n]" nil t
)
552 (progn (forward-line 1) (point))
554 ;; Delete following blank lines, unless the current line is blank
555 ;; and there are no following blank lines.
556 (if (not (and thisblank singleblank
))
560 (delete-region (point)
561 (if (re-search-forward "[^ \t\n]" nil t
)
562 (progn (beginning-of-line) (point))
564 ;; Handle the special case where point is followed by newline and eob.
565 ;; Delete the line, leaving point at eob.
566 (if (looking-at "^[ \t]*\n\\'")
567 (delete-region (point) (point-max)))))
569 (defcustom delete-trailing-lines t
570 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
571 Trailing lines are deleted only if `delete-trailing-whitespace'
572 is called on the entire buffer (rather than an active region)."
577 (defun delete-trailing-whitespace (&optional start end
)
578 "Delete trailing whitespace between START and END.
579 If called interactively, START and END are the start/end of the
580 region if the mark is active, or of the buffer's accessible
581 portion if the mark is inactive.
583 This command deletes whitespace characters after the last
584 non-whitespace character in each line between START and END. It
585 does not consider formfeed characters to be whitespace.
587 If this command acts on the entire buffer (i.e. if called
588 interactively with the mark inactive, or called from Lisp with
589 END nil), it also deletes all trailing lines at the end of the
590 buffer if the variable `delete-trailing-lines' is non-nil."
592 (barf-if-buffer-read-only)
594 (list (region-beginning) (region-end))
598 (let ((end-marker (copy-marker (or end
(point-max))))
599 (start (or start
(point-min))))
601 (while (re-search-forward "\\s-$" end-marker t
)
602 (skip-syntax-backward "-" (line-beginning-position))
603 ;; Don't delete formfeeds, even if they are considered whitespace.
604 (if (looking-at-p ".*\f")
605 (goto-char (match-end 0)))
606 (delete-region (point) (match-end 0)))
607 ;; Delete trailing empty lines.
608 (goto-char end-marker
)
610 delete-trailing-lines
611 ;; Really the end of buffer.
612 (= (point-max) (1+ (buffer-size)))
613 (<= (skip-chars-backward "\n") -
2))
614 (delete-region (1+ (point)) end-marker
))
615 (set-marker end-marker nil
))))
616 ;; Return nil for the benefit of `write-file-functions'.
619 (defun newline-and-indent ()
620 "Insert a newline, then indent according to major mode.
621 Indentation is done using the value of `indent-line-function'.
622 In programming language modes, this is the same as TAB.
623 In some text modes, where TAB inserts a tab, this command indents to the
624 column specified by the function `current-left-margin'."
626 (delete-horizontal-space t
)
628 (indent-according-to-mode))
630 (defun reindent-then-newline-and-indent ()
631 "Reindent current line, insert newline, then indent the new line.
632 Indentation of both lines is done according to the current major mode,
633 which means calling the current value of `indent-line-function'.
634 In programming language modes, this is the same as TAB.
635 In some text modes, where TAB inserts a tab, this indents to the
636 column specified by the function `current-left-margin'."
639 ;; Be careful to insert the newline before indenting the line.
640 ;; Otherwise, the indentation might be wrong.
644 ;; We are at EOL before the call to indent-according-to-mode, and
645 ;; after it we usually are as well, but not always. We tried to
646 ;; address it with `save-excursion' but that uses a normal marker
647 ;; whereas we need `move after insertion', so we do the save/restore
649 (setq pos
(copy-marker pos t
))
650 (indent-according-to-mode)
652 ;; Remove the trailing white-space after indentation because
653 ;; indentation may introduce the whitespace.
654 (delete-horizontal-space t
))
655 (indent-according-to-mode)))
657 (defcustom read-quoted-char-radix
8
658 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
659 Legitimate radix values are 8, 10 and 16."
660 :type
'(choice (const 8) (const 10) (const 16))
661 :group
'editing-basics
)
663 (defun read-quoted-char (&optional prompt
)
664 "Like `read-char', but do not allow quitting.
665 Also, if the first character read is an octal digit,
666 we read any number of octal digits and return the
667 specified character code. Any nondigit terminates the sequence.
668 If the terminator is RET, it is discarded;
669 any other terminator is used itself as input.
671 The optional argument PROMPT specifies a string to use to prompt the user.
672 The variable `read-quoted-char-radix' controls which radix to use
674 (let ((message-log-max nil
)
675 (help-events (delq nil
(mapcar (lambda (c) (unless (characterp c
) c
))
677 done
(first t
) (code 0) translated
)
679 (let ((inhibit-quit first
)
680 ;; Don't let C-h or other help chars get the help
681 ;; message--only help function keys. See bug#16617.
683 (help-event-list help-events
)
685 "Type the special character you want to use,
686 or the octal character code.
687 RET terminates the character code and is discarded;
688 any other non-digit terminates the character code and is then used as input."))
689 (setq translated
(read-key (and prompt
(format "%s-" prompt
))))
690 (if inhibit-quit
(setq quit-flag nil
)))
691 (if (integerp translated
)
692 (setq translated
(char-resolve-modifiers translated
)))
693 (cond ((null translated
))
694 ((not (integerp translated
))
695 (setq unread-command-events
696 (listify-key-sequence (this-single-command-raw-keys))
698 ((/= (logand translated ?\M-\^
@) 0)
699 ;; Turn a meta-character into a character with the 0200 bit set.
700 (setq code
(logior (logand translated
(lognot ?\M-\^
@)) 128)
702 ((and (<= ?
0 translated
)
703 (< translated
(+ ?
0 (min 10 read-quoted-char-radix
))))
704 (setq code
(+ (* code read-quoted-char-radix
) (- translated ?
0)))
705 (and prompt
(setq prompt
(message "%s %c" prompt translated
))))
706 ((and (<= ?a
(downcase translated
))
707 (< (downcase translated
)
708 (+ ?a -
10 (min 36 read-quoted-char-radix
))))
709 (setq code
(+ (* code read-quoted-char-radix
)
710 (+ 10 (- (downcase translated
) ?a
))))
711 (and prompt
(setq prompt
(message "%s %c" prompt translated
))))
712 ((and (not first
) (eq translated ?\C-m
))
715 (setq unread-command-events
716 (listify-key-sequence (this-single-command-raw-keys))
718 (t (setq code translated
723 (defun quoted-insert (arg)
724 "Read next input character and insert it.
725 This is useful for inserting control characters.
726 With argument, insert ARG copies of the character.
728 If the first character you type after this command is an octal digit,
729 you should type a sequence of octal digits which specify a character code.
730 Any nondigit terminates the sequence. If the terminator is a RET,
731 it is discarded; any other terminator is used itself as input.
732 The variable `read-quoted-char-radix' specifies the radix for this feature;
733 set it to 10 or 16 to use decimal or hex instead of octal.
735 In overwrite mode, this function inserts the character anyway, and
736 does not handle octal digits specially. This means that if you use
737 overwrite as your normal editing mode, you can use this function to
738 insert characters when necessary.
740 In binary overwrite mode, this function does overwrite, and octal
741 digits are interpreted as a character code. This is intended to be
742 useful for editing binary files."
745 ;; Avoid "obsolete" warnings for translation-table-for-input.
747 (let (translation-table-for-input input-method-function
)
748 (if (or (not overwrite-mode
)
749 (eq overwrite-mode
'overwrite-mode-binary
))
752 ;; This used to assume character codes 0240 - 0377 stand for
753 ;; characters in some single-byte character set, and converted them
754 ;; to Emacs characters. But in 23.1 this feature is deprecated
755 ;; in favor of inserting the corresponding Unicode characters.
756 ;; (if (and enable-multibyte-characters
759 ;; (setq char (unibyte-char-to-multibyte char)))
760 (unless (characterp char
)
761 (user-error "%s is not a valid character"
762 (key-description (vector char
))))
764 (if (eq overwrite-mode
'overwrite-mode-binary
)
767 (insert-and-inherit char
)
768 (setq arg
(1- arg
)))))
770 (defun forward-to-indentation (&optional arg
)
771 "Move forward ARG lines and position at first nonblank character."
773 (forward-line (or arg
1))
774 (skip-chars-forward " \t"))
776 (defun backward-to-indentation (&optional arg
)
777 "Move backward ARG lines and position at first nonblank character."
779 (forward-line (- (or arg
1)))
780 (skip-chars-forward " \t"))
782 (defun back-to-indentation ()
783 "Move point to the first non-whitespace character on this line."
785 (beginning-of-line 1)
786 (skip-syntax-forward " " (line-end-position))
787 ;; Move back over chars that have whitespace syntax but have the p flag.
788 (backward-prefix-chars))
790 (defun fixup-whitespace ()
791 "Fixup white space between objects around point.
792 Leave one space or none, according to the context."
795 (delete-horizontal-space)
796 (if (or (looking-at "^\\|\\s)")
797 (save-excursion (forward-char -
1)
798 (looking-at "$\\|\\s(\\|\\s'")))
802 (defun delete-horizontal-space (&optional backward-only
)
803 "Delete all spaces and tabs around point.
804 If BACKWARD-ONLY is non-nil, only delete them before point."
806 (let ((orig-pos (point)))
811 (skip-chars-forward " \t")
812 (constrain-to-field nil orig-pos t
)))
814 (skip-chars-backward " \t")
815 (constrain-to-field nil orig-pos
)))))
817 (defun just-one-space (&optional n
)
818 "Delete all spaces and tabs around point, leaving one space (or N spaces).
819 If N is negative, delete newlines as well, leaving -N spaces.
820 See also `cycle-spacing'."
822 (cycle-spacing n nil
'single-shot
))
824 (defvar cycle-spacing--context nil
825 "Store context used in consecutive calls to `cycle-spacing' command.
826 The first time `cycle-spacing' runs, it saves in this variable:
827 its N argument, the original point position, and the original spacing
830 (defun cycle-spacing (&optional n preserve-nl-back mode
)
831 "Manipulate whitespace around point in a smart way.
832 In interactive use, this function behaves differently in successive
835 The first call in a sequence acts like `just-one-space'.
836 It deletes all spaces and tabs around point, leaving one space
837 \(or N spaces). N is the prefix argument. If N is negative,
838 it deletes newlines as well, leaving -N spaces.
839 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
841 The second call in a sequence deletes all spaces.
843 The third call in a sequence restores the original whitespace (and point).
845 If MODE is `single-shot', it only performs the first step in the sequence.
846 If MODE is `fast' and the first step would not result in any change
847 \(i.e., there are exactly (abs N) spaces around point),
848 the function goes straight to the second step.
850 Repeatedly calling the function with different values of N starts a
851 new sequence each time."
853 (let ((orig-pos (point))
854 (skip-characters (if (and n
(< n
0)) " \t\n\r" " \t"))
855 (num (abs (or n
1))))
856 (skip-chars-backward (if preserve-nl-back
" \t" skip-characters
))
857 (constrain-to-field nil orig-pos
)
859 ;; Command run for the first time, single-shot mode or different argument
860 ((or (eq 'single-shot mode
)
861 (not (equal last-command this-command
))
862 (not cycle-spacing--context
)
863 (not (eq (car cycle-spacing--context
) n
)))
864 (let* ((start (point))
865 (num (- num
(skip-chars-forward " " (+ num
(point)))))
868 (skip-chars-forward skip-characters
)
869 (constrain-to-field nil orig-pos t
))))
870 (setq cycle-spacing--context
;; Save for later.
871 ;; Special handling for case where there was no space at all.
872 (unless (= start end
)
873 (cons n
(cons orig-pos
(buffer-substring start
(point))))))
874 ;; If this run causes no change in buffer content, delete all spaces,
875 ;; otherwise delete all excess spaces.
876 (delete-region (if (and (eq mode
'fast
) (zerop num
) (= mid end
))
878 (insert (make-string num ?\s
))))
880 ;; Command run for the second time.
881 ((not (equal orig-pos
(point)))
882 (delete-region (point) orig-pos
))
884 ;; Command run for the third time.
886 (insert (cddr cycle-spacing--context
))
887 (goto-char (cadr cycle-spacing--context
))
888 (setq cycle-spacing--context nil
)))))
890 (defun beginning-of-buffer (&optional arg
)
891 "Move point to the beginning of the buffer.
892 With numeric arg N, put point N/10 of the way from the beginning.
893 If the buffer is narrowed, this command uses the beginning of the
894 accessible part of the buffer.
896 If Transient Mark mode is disabled, leave mark at previous
897 position, unless a \\[universal-argument] prefix is supplied."
898 (declare (interactive-only "use `(goto-char (point-min))' instead."))
903 (let ((size (- (point-max) (point-min))))
904 (goto-char (if (and arg
(not (consp arg
)))
907 ;; Avoid overflow for large buffer sizes!
908 (* (prefix-numeric-value arg
)
910 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
912 (if (and arg
(not (consp arg
))) (forward-line 1)))
914 (defun end-of-buffer (&optional arg
)
915 "Move point to the end of the buffer.
916 With numeric arg N, put point N/10 of the way from the end.
917 If the buffer is narrowed, this command uses the end of the
918 accessible part of the buffer.
920 If Transient Mark mode is disabled, leave mark at previous
921 position, unless a \\[universal-argument] prefix is supplied."
922 (declare (interactive-only "use `(goto-char (point-max))' instead."))
924 (or (consp arg
) (region-active-p) (push-mark))
925 (let ((size (- (point-max) (point-min))))
926 (goto-char (if (and arg
(not (consp arg
)))
929 ;; Avoid overflow for large buffer sizes!
930 (* (prefix-numeric-value arg
)
932 (/ (* size
(prefix-numeric-value arg
)) 10)))
934 ;; If we went to a place in the middle of the buffer,
935 ;; adjust it to the beginning of a line.
936 (cond ((and arg
(not (consp arg
))) (forward-line 1))
937 ((and (eq (current-buffer) (window-buffer))
938 (> (point) (window-end nil t
)))
939 ;; If the end of the buffer is not already on the screen,
940 ;; then scroll specially to put it near, but not at, the bottom.
941 (overlay-recenter (point))
944 (defcustom delete-active-region t
945 "Whether single-char deletion commands delete an active region.
946 This has an effect only if Transient Mark mode is enabled, and
947 affects `delete-forward-char' and `delete-backward-char', though
950 If the value is the symbol `kill', the active region is killed
952 :type
'(choice (const :tag
"Delete active region" t
)
953 (const :tag
"Kill active region" kill
)
954 (const :tag
"Do ordinary deletion" nil
))
958 (defvar region-extract-function
960 (when (region-beginning)
961 (if (eq delete
'delete-only
)
962 (delete-region (region-beginning) (region-end))
963 (filter-buffer-substring (region-beginning) (region-end) delete
))))
964 "Function to get the region's content.
965 Called with one argument DELETE.
966 If DELETE is `delete-only', then only delete the region and the return value
967 is undefined. If DELETE is nil, just return the content as a string.
968 If anything else, delete the region and return its content as a string.")
970 (defun delete-backward-char (n &optional killflag
)
971 "Delete the previous N characters (following if N is negative).
972 If Transient Mark mode is enabled, the mark is active, and N is 1,
973 delete the text in the region and deactivate the mark instead.
974 To disable this, set option `delete-active-region' to nil.
976 Optional second arg KILLFLAG, if non-nil, means to kill (save in
977 kill ring) instead of delete. Interactively, N is the prefix
978 arg, and KILLFLAG is set if N is explicitly specified.
980 In Overwrite mode, single character backward deletion may replace
981 tabs with spaces so as to back over columns, unless point is at
982 the end of the line."
983 (declare (interactive-only delete-char
))
986 (signal 'wrong-type-argument
(list 'integerp n
)))
987 (cond ((and (use-region-p)
990 ;; If a region is active, kill or delete it.
991 (if (eq delete-active-region
'kill
)
992 (kill-region (region-beginning) (region-end) 'region
)
993 (funcall region-extract-function
'delete-only
)))
994 ;; In Overwrite mode, maybe untabify while deleting
995 ((null (or (null overwrite-mode
)
997 (memq (char-before) '(?
\t ?
\n))
999 (eq (char-after) ?
\n)))
1000 (let ((ocol (current-column)))
1001 (delete-char (- n
) killflag
)
1003 (insert-char ?\s
(- ocol
(current-column)) nil
))))
1004 ;; Otherwise, do simple deletion.
1005 (t (delete-char (- n
) killflag
))))
1007 (defun delete-forward-char (n &optional killflag
)
1008 "Delete the following N characters (previous if N is negative).
1009 If Transient Mark mode is enabled, the mark is active, and N is 1,
1010 delete the text in the region and deactivate the mark instead.
1011 To disable this, set variable `delete-active-region' to nil.
1013 Optional second arg KILLFLAG non-nil means to kill (save in kill
1014 ring) instead of delete. Interactively, N is the prefix arg, and
1015 KILLFLAG is set if N was explicitly specified."
1016 (declare (interactive-only delete-char
))
1017 (interactive "p\nP")
1018 (unless (integerp n
)
1019 (signal 'wrong-type-argument
(list 'integerp n
)))
1020 (cond ((and (use-region-p)
1021 delete-active-region
1023 ;; If a region is active, kill or delete it.
1024 (if (eq delete-active-region
'kill
)
1025 (kill-region (region-beginning) (region-end) 'region
)
1026 (funcall region-extract-function
'delete-only
)))
1028 ;; Otherwise, do simple deletion.
1029 (t (delete-char n killflag
))))
1031 (defun mark-whole-buffer ()
1032 "Put point at beginning and mark at end of buffer.
1033 If narrowing is in effect, only uses the accessible part of the buffer.
1034 You probably should not use this function in Lisp programs;
1035 it is usually a mistake for a Lisp function to use any subroutine
1036 that uses or sets the mark."
1037 (declare (interactive-only t
))
1040 (push-mark (point-max) nil t
)
1041 (goto-char (point-min)))
1044 ;; Counting lines, one way or another.
1046 (defun goto-line (line &optional buffer
)
1047 "Go to LINE, counting from line 1 at beginning of buffer.
1048 If called interactively, a numeric prefix argument specifies
1049 LINE; without a numeric prefix argument, read LINE from the
1052 If optional argument BUFFER is non-nil, switch to that buffer and
1053 move to line LINE there. If called interactively with \\[universal-argument]
1054 as argument, BUFFER is the most recently selected other buffer.
1056 Prior to moving point, this function sets the mark (without
1057 activating it), unless Transient Mark mode is enabled and the
1058 mark is already active.
1060 This function is usually the wrong thing to use in a Lisp program.
1061 What you probably want instead is something like:
1062 (goto-char (point-min))
1063 (forward-line (1- N))
1064 If at all possible, an even better solution is to use char counts
1065 rather than line counts."
1066 (declare (interactive-only forward-line
))
1068 (if (and current-prefix-arg
(not (consp current-prefix-arg
)))
1069 (list (prefix-numeric-value current-prefix-arg
))
1070 ;; Look for a default, a number in the buffer at point.
1073 (skip-chars-backward "0-9")
1074 (if (looking-at "[0-9]")
1076 (buffer-substring-no-properties
1078 (progn (skip-chars-forward "0-9")
1080 ;; Decide if we're switching buffers.
1082 (if (consp current-prefix-arg
)
1083 (other-buffer (current-buffer) t
)))
1086 (concat " in " (buffer-name buffer
))
1088 ;; Read the argument, offering that number (if any) as default.
1089 (list (read-number (format "Goto line%s: " buffer-prompt
)
1090 (list default
(line-number-at-pos)))
1092 ;; Switch to the desired buffer, one way or another.
1094 (let ((window (get-buffer-window buffer
)))
1095 (if window
(select-window window
)
1096 (switch-to-buffer-other-window buffer
))))
1097 ;; Leave mark at previous position
1098 (or (region-active-p) (push-mark))
1099 ;; Move to the specified line number in that buffer.
1102 (goto-char (point-min))
1103 (if (eq selective-display t
)
1104 (re-search-forward "[\n\C-m]" nil
'end
(1- line
))
1105 (forward-line (1- line
)))))
1107 (defun count-words-region (start end
&optional arg
)
1108 "Count the number of words in the region.
1109 If called interactively, print a message reporting the number of
1110 lines, words, and characters in the region (whether or not the
1111 region is active); with prefix ARG, report for the entire buffer
1112 rather than the region.
1114 If called from Lisp, return the number of words between positions
1116 (interactive (if current-prefix-arg
1117 (list nil nil current-prefix-arg
)
1118 (list (region-beginning) (region-end) nil
)))
1119 (cond ((not (called-interactively-p 'any
))
1120 (count-words start end
))
1122 (count-words--buffer-message))
1124 (count-words--message "Region" start end
))))
1126 (defun count-words (start end
)
1127 "Count words between START and END.
1128 If called interactively, START and END are normally the start and
1129 end of the buffer; but if the region is active, START and END are
1130 the start and end of the region. Print a message reporting the
1131 number of lines, words, and chars.
1133 If called from Lisp, return the number of words between START and
1134 END, without printing any message."
1135 (interactive (list nil nil
))
1136 (cond ((not (called-interactively-p 'any
))
1140 (narrow-to-region start end
)
1141 (goto-char (point-min))
1142 (while (forward-word 1)
1143 (setq words
(1+ words
)))))
1146 (call-interactively 'count-words-region
))
1148 (count-words--buffer-message))))
1150 (defun count-words--buffer-message ()
1151 (count-words--message
1152 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1153 (point-min) (point-max)))
1155 (defun count-words--message (str start end
)
1156 (let ((lines (count-lines start end
))
1157 (words (count-words start end
))
1158 (chars (- end start
)))
1159 (message "%s has %d line%s, %d word%s, and %d character%s."
1161 lines
(if (= lines
1) "" "s")
1162 words
(if (= words
1) "" "s")
1163 chars
(if (= chars
1) "" "s"))))
1165 (define-obsolete-function-alias 'count-lines-region
'count-words-region
"24.1")
1168 "Print the current buffer line number and narrowed line number of point."
1170 (let ((start (point-min))
1171 (n (line-number-at-pos)))
1173 (message "Line %d" n
)
1177 (message "line %d (narrowed line %d)"
1178 (+ n
(line-number-at-pos start
) -
1) n
))))))
1180 (defun count-lines (start end
)
1181 "Return number of lines between START and END.
1182 This is usually the number of newlines between them,
1183 but can be one more if START is not equal to END
1184 and the greater of them is not at the start of a line."
1187 (narrow-to-region start end
)
1188 (goto-char (point-min))
1189 (if (eq selective-display t
)
1192 (while (re-search-forward "[\n\C-m]" nil t
40)
1193 (setq done
(+ 40 done
)))
1194 (while (re-search-forward "[\n\C-m]" nil t
1)
1195 (setq done
(+ 1 done
)))
1196 (goto-char (point-max))
1197 (if (and (/= start end
)
1201 (- (buffer-size) (forward-line (buffer-size)))))))
1203 (defun line-number-at-pos (&optional pos
)
1204 "Return (narrowed) buffer line number at position POS.
1205 If POS is nil, use current buffer location.
1206 Counting starts at (point-min), so the value refers
1207 to the contents of the accessible portion of the buffer."
1208 (let ((opoint (or pos
(point))) start
)
1210 (goto-char (point-min))
1211 (setq start
(point))
1214 (1+ (count-lines start
(point))))))
1216 (defun what-cursor-position (&optional detail
)
1217 "Print info on cursor position (on screen and within buffer).
1218 Also describe the character after point, and give its character code
1219 in octal, decimal and hex.
1221 For a non-ASCII multibyte character, also give its encoding in the
1222 buffer's selected coding system if the coding system encodes the
1223 character safely. If the character is encoded into one byte, that
1224 code is shown in hex. If the character is encoded into more than one
1225 byte, just \"...\" is shown.
1227 In addition, with prefix argument, show details about that character
1228 in *Help* buffer. See also the command `describe-char'."
1230 (let* ((char (following-char))
1232 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1233 ;; start a directional embedding, which could completely
1234 ;; disrupt the rest of the line (e.g., RLO will display the
1235 ;; rest of the line right-to-left). So we put an invisible
1236 ;; PDF character after these characters, to end the
1237 ;; embedding, which eliminates any effects on the rest of
1238 ;; the line. For RLE and RLO we also append an invisible
1239 ;; LRM, to avoid reordering the following numerical
1240 ;; characters. For LRI/RLI/FSI we append a PDI.
1241 (cond ((memq char
'(?
\x202a ?
\x202d
))
1242 (propertize (string ?
\x202c
) 'invisible t
))
1243 ((memq char
'(?
\x202b ?
\x202e
))
1244 (propertize (string ?
\x202c ?
\x200e
) 'invisible t
))
1245 ((memq char
'(?
\x2066 ?
\x2067 ?
\x2068
))
1246 (propertize (string ?
\x2069
) 'invisible t
))
1247 ;; Strong right-to-left characters cause reordering of
1248 ;; the following numerical characters which show the
1249 ;; codepoint, so append LRM to countermand that.
1250 ((memq (get-char-code-property char
'bidi-class
) '(R AL
))
1251 (propertize (string ?
\x200e
) 'invisible t
))
1257 (total (buffer-size))
1258 (percent (round (* 100.0 (1- pos
)) (max 1 total
)))
1259 (hscroll (if (= (window-hscroll) 0)
1261 (format " Hscroll=%d" (window-hscroll))))
1262 (col (current-column)))
1264 (if (or (/= beg
1) (/= end
(1+ total
)))
1265 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1266 pos total percent beg end col hscroll
)
1267 (message "point=%d of %d (EOB) column=%d%s"
1268 pos total col hscroll
))
1269 (let ((coding buffer-file-coding-system
)
1270 encoded encoding-msg display-prop under-display
)
1271 (if (or (not coding
)
1272 (eq (coding-system-type coding
) t
))
1273 (setq coding
(default-value 'buffer-file-coding-system
)))
1274 (if (eq (char-charset char
) 'eight-bit
)
1276 (format "(%d, #o%o, #x%x, raw-byte)" char char char
))
1277 ;; Check if the character is displayed with some `display'
1278 ;; text property. In that case, set under-display to the
1279 ;; buffer substring covered by that property.
1280 (setq display-prop
(get-char-property pos
'display
))
1282 (let ((to (or (next-single-char-property-change pos
'display
)
1284 (if (< to
(+ pos
4))
1285 (setq under-display
"")
1286 (setq under-display
"..."
1289 (concat (buffer-substring-no-properties pos to
)
1291 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
1294 (if (not (stringp display-prop
))
1295 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1296 char char char under-display
)
1297 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1298 char char char under-display display-prop
))
1300 (format "(%d, #o%o, #x%x, file %s)"
1302 (if (> (length encoded
) 1)
1304 (encoded-string-description encoded coding
)))
1305 (format "(%d, #o%o, #x%x)" char char char
)))))
1307 ;; We show the detailed information about CHAR.
1308 (describe-char (point)))
1309 (if (or (/= beg
1) (/= end
(1+ total
)))
1310 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1312 (single-key-description char
)
1313 (buffer-substring-no-properties (point) (1+ (point))))
1315 encoding-msg pos total percent beg end col hscroll
)
1316 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1317 (if enable-multibyte-characters
1319 (single-key-description char
)
1320 (buffer-substring-no-properties (point) (1+ (point))))
1321 (single-key-description char
))
1322 bidi-fixer encoding-msg pos total percent col hscroll
))))))
1324 ;; Initialize read-expression-map. It is defined at C level.
1325 (defvar read-expression-map
1326 (let ((m (make-sparse-keymap)))
1327 (define-key m
"\M-\t" 'completion-at-point
)
1328 ;; Might as well bind TAB to completion, since inserting a TAB char is
1329 ;; much too rarely useful.
1330 (define-key m
"\t" 'completion-at-point
)
1331 (set-keymap-parent m minibuffer-local-map
)
1334 (defun read-minibuffer (prompt &optional initial-contents
)
1335 "Return a Lisp object read using the minibuffer, unevaluated.
1336 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1337 is a string to insert in the minibuffer before reading.
1338 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1339 Such arguments are used as in `read-from-minibuffer'.)"
1340 ;; Used for interactive spec `x'.
1341 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1342 t
'minibuffer-history
))
1344 (defun eval-minibuffer (prompt &optional initial-contents
)
1345 "Return value of Lisp expression read using the minibuffer.
1346 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1347 is a string to insert in the minibuffer before reading.
1348 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1349 Such arguments are used as in `read-from-minibuffer'.)"
1350 ;; Used for interactive spec `X'.
1351 (eval (read--expression prompt initial-contents
)))
1353 (defvar minibuffer-completing-symbol nil
1354 "Non-nil means completing a Lisp symbol in the minibuffer.")
1355 (make-obsolete-variable 'minibuffer-completing-symbol nil
"24.1" 'get
)
1357 (defvar minibuffer-default nil
1358 "The current default value or list of default values in the minibuffer.
1359 The functions `read-from-minibuffer' and `completing-read' bind
1360 this variable locally.")
1362 (defcustom eval-expression-print-level
4
1363 "Value for `print-level' while printing value in `eval-expression'.
1364 A value of nil means no limit."
1366 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1369 (defcustom eval-expression-print-length
12
1370 "Value for `print-length' while printing value in `eval-expression'.
1371 A value of nil means no limit."
1373 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1376 (defcustom eval-expression-debug-on-error t
1377 "If non-nil set `debug-on-error' to t in `eval-expression'.
1378 If nil, don't change the value of `debug-on-error'."
1383 (defun eval-expression-print-format (value)
1384 "Format VALUE as a result of evaluated expression.
1385 Return a formatted string which is displayed in the echo area
1386 in addition to the value printed by prin1 in functions which
1387 display the result of expression evaluation."
1388 (if (and (integerp value
)
1389 (or (eq standard-output t
)
1390 (zerop (prefix-numeric-value current-prefix-arg
))))
1392 (if (and (characterp value
)
1393 (char-displayable-p value
))
1394 (prin1-char value
))))
1396 (format " (#o%o, #x%x, %s)" value value char-string
)
1397 (format " (#o%o, #x%x)" value value
)))))
1399 (defvar eval-expression-minibuffer-setup-hook nil
1400 "Hook run by `eval-expression' when entering the minibuffer.")
1402 (defun read--expression (prompt &optional initial-contents
)
1403 (let ((minibuffer-completing-symbol t
))
1404 (minibuffer-with-setup-hook
1406 ;; FIXME: call emacs-lisp-mode?
1407 (add-function :before-until
(local 'eldoc-documentation-function
)
1408 #'elisp-eldoc-documentation-function
)
1409 (add-hook 'completion-at-point-functions
1410 #'elisp-completion-at-point nil t
)
1411 (run-hooks 'eval-expression-minibuffer-setup-hook
))
1412 (read-from-minibuffer prompt initial-contents
1413 read-expression-map t
1414 'read-expression-history
))))
1416 ;; We define this, rather than making `eval' interactive,
1417 ;; for the sake of completion of names like eval-region, eval-buffer.
1418 (defun eval-expression (exp &optional insert-value
)
1419 "Evaluate EXP and print value in the echo area.
1420 When called interactively, read an Emacs Lisp expression and evaluate it.
1421 Value is also consed on to front of the variable `values'.
1422 Optional argument INSERT-VALUE non-nil (interactively, with prefix
1423 argument) means insert the result into the current buffer instead of
1424 printing it in the echo area.
1426 Normally, this function truncates long output according to the value
1427 of the variables `eval-expression-print-length' and
1428 `eval-expression-print-level'. With a prefix argument of zero,
1429 however, there is no such truncation. Such a prefix argument
1430 also causes integers to be printed in several additional formats
1431 \(octal, hexadecimal, and character).
1433 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1436 If `eval-expression-debug-on-error' is non-nil, which is the default,
1437 this command arranges for all errors to enter the debugger."
1439 (list (read--expression "Eval: ")
1440 current-prefix-arg
))
1442 (if (null eval-expression-debug-on-error
)
1443 (push (eval exp lexical-binding
) values
)
1444 (let ((old-value (make-symbol "t")) new-value
)
1445 ;; Bind debug-on-error to something unique so that we can
1446 ;; detect when evalled code changes it.
1447 (let ((debug-on-error old-value
))
1448 (push (eval (macroexpand-all exp
) lexical-binding
) values
)
1449 (setq new-value debug-on-error
))
1450 ;; If evalled code has changed the value of debug-on-error,
1451 ;; propagate that change to the global binding.
1452 (unless (eq old-value new-value
)
1453 (setq debug-on-error new-value
))))
1455 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value
)))
1456 eval-expression-print-length
))
1457 (print-level (and (not (zerop (prefix-numeric-value insert-value
)))
1458 eval-expression-print-level
))
1462 (let ((standard-output (current-buffer)))
1464 (prin1 (car values
))
1465 (when (zerop (prefix-numeric-value insert-value
))
1466 (let ((str (eval-expression-print-format (car values
))))
1467 (if str
(princ str
)))))))
1469 (prin1 (car values
) t
)
1470 (let ((str (eval-expression-print-format (car values
))))
1471 (if str
(princ str t
)))))))
1473 (defun edit-and-eval-command (prompt command
)
1474 "Prompting with PROMPT, let user edit COMMAND and eval result.
1475 COMMAND is a Lisp expression. Let user edit that expression in
1476 the minibuffer, then read and evaluate the result."
1478 (let ((print-level nil
)
1479 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1481 (read-from-minibuffer prompt
1482 (prin1-to-string command
)
1483 read-expression-map t
1485 ;; If command was added to command-history as a string,
1486 ;; get rid of that. We want only evaluable expressions there.
1487 (if (stringp (car command-history
))
1488 (setq command-history
(cdr command-history
)))))))
1490 ;; If command to be redone does not match front of history,
1491 ;; add it to the history.
1492 (or (equal command
(car command-history
))
1493 (setq command-history
(cons command command-history
)))
1496 (defun repeat-complex-command (arg)
1497 "Edit and re-evaluate last complex command, or ARGth from last.
1498 A complex command is one which used the minibuffer.
1499 The command is placed in the minibuffer as a Lisp form for editing.
1500 The result is executed, repeating the command as changed.
1501 If the command has been changed or is not the most recent previous
1502 command it is added to the front of the command history.
1503 You can use the minibuffer history commands \
1504 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1505 to get different commands to edit and resubmit."
1507 (let ((elt (nth (1- arg
) command-history
))
1512 (let ((print-level nil
)
1513 (minibuffer-history-position arg
)
1514 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1516 (read-from-minibuffer
1517 "Redo: " (prin1-to-string elt
) read-expression-map t
1518 (cons 'command-history arg
))
1520 ;; If command was added to command-history as a
1521 ;; string, get rid of that. We want only
1522 ;; evaluable expressions there.
1523 (if (stringp (car command-history
))
1524 (setq command-history
(cdr command-history
))))))
1526 ;; If command to be redone does not match front of history,
1527 ;; add it to the history.
1528 (or (equal newcmd
(car command-history
))
1529 (setq command-history
(cons newcmd command-history
)))
1530 (apply #'funcall-interactively
1532 (mapcar (lambda (e) (eval e t
)) (cdr newcmd
))))
1534 (error "Argument %d is beyond length of command history" arg
)
1535 (error "There are no previous complex commands to repeat")))))
1538 (defvar extended-command-history nil
)
1539 (defvar execute-extended-command--last-typed nil
)
1541 (defun read-extended-command ()
1542 "Read command name to invoke in `execute-extended-command'."
1543 (minibuffer-with-setup-hook
1545 (add-hook 'post-self-insert-hook
1547 (setq execute-extended-command--last-typed
1548 (minibuffer-contents)))
1550 (set (make-local-variable 'minibuffer-default-add-function
)
1552 ;; Get a command name at point in the original buffer
1553 ;; to propose it after M-n.
1554 (with-current-buffer (window-buffer (minibuffer-selected-window))
1555 (and (commandp (function-called-at-point))
1556 (format "%S" (function-called-at-point)))))))
1557 ;; Read a string, completing from and restricting to the set of
1558 ;; all defined commands. Don't provide any initial input.
1559 ;; Save the command read on the extended-command history list.
1562 ((eq current-prefix-arg
'-
) "- ")
1563 ((and (consp current-prefix-arg
)
1564 (eq (car current-prefix-arg
) 4)) "C-u ")
1565 ((and (consp current-prefix-arg
)
1566 (integerp (car current-prefix-arg
)))
1567 (format "%d " (car current-prefix-arg
)))
1568 ((integerp current-prefix-arg
)
1569 (format "%d " current-prefix-arg
)))
1570 ;; This isn't strictly correct if `execute-extended-command'
1571 ;; is bound to anything else (e.g. [menu]).
1572 ;; It could use (key-description (this-single-command-keys)),
1573 ;; but actually a prompt other than "M-x" would be confusing,
1574 ;; because "M-x" is a well-known prompt to read a command
1575 ;; and it serves as a shorthand for "Extended command: ".
1577 (lambda (string pred action
)
1579 (if (memq action
'(nil t
))
1580 ;; Exclude obsolete commands from completions.
1582 (and (funcall pred sym
)
1583 (or (equal string
(symbol-name sym
))
1584 (not (get sym
'byte-obsolete-info
)))))
1586 (complete-with-action action obarray string pred
)))
1587 #'commandp t nil
'extended-command-history
)))
1589 (defcustom suggest-key-bindings t
1590 "Non-nil means show the equivalent key-binding when M-x command has one.
1591 The value can be a length of time to show the message for.
1592 If the value is non-nil and not a number, we wait 2 seconds."
1594 :type
'(choice (const :tag
"off" nil
)
1595 (integer :tag
"time" 2)
1598 (defun execute-extended-command--shorter-1 (name length
)
1600 ((zerop length
) (list ""))
1601 ((equal name
"") nil
)
1603 (nconc (mapcar (lambda (s) (concat (substring name
0 1) s
))
1604 (execute-extended-command--shorter-1
1605 (substring name
1) (1- length
)))
1606 (when (string-match "\\`\\(-\\)?[^-]*" name
)
1607 (execute-extended-command--shorter-1
1608 (substring name
(match-end 0)) length
))))))
1610 (defun execute-extended-command--shorter (name typed
)
1611 (let ((candidates '())
1612 (max (length typed
))
1615 (while (and (not binding
)
1619 (setq candidates
(execute-extended-command--shorter-1
1621 ;; Don't show the help message if the binding isn't
1622 ;; significantly shorter than the M-x command the user typed.
1624 (let ((candidate (pop candidates
)))
1626 (car-safe (completion-try-completion
1627 candidate obarray
'commandp len
)))
1628 (setq binding candidate
))))
1631 (defun execute-extended-command (prefixarg &optional command-name typed
)
1632 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1633 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1634 "Read a command name, then read the arguments and call the command.
1635 To pass a prefix argument to the command you are
1636 invoking, give a prefix argument to `execute-extended-command'."
1637 (declare (interactive-only command-execute
))
1638 ;; FIXME: Remember the actual text typed by the user before completion,
1639 ;; so that we don't later on suggest the same shortening.
1641 (let ((execute-extended-command--last-typed nil
))
1642 (list current-prefix-arg
1643 (read-extended-command)
1644 execute-extended-command--last-typed
)))
1645 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1646 (unless command-name
1647 (let ((current-prefix-arg prefixarg
) ; for prompt
1648 (execute-extended-command--last-typed nil
))
1649 (setq command-name
(read-extended-command))
1650 (setq typed execute-extended-command--last-typed
)))
1651 (let* ((function (and (stringp command-name
) (intern-soft command-name
)))
1652 (binding (and suggest-key-bindings
1653 (not executing-kbd-macro
)
1654 (where-is-internal function overriding-local-map t
))))
1655 (unless (commandp function
)
1656 (error "`%s' is not a valid command name" command-name
))
1657 (setq this-command function
)
1658 ;; Normally `real-this-command' should never be changed, but here we really
1659 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1660 ;; binding" for <cmd>, so the command the user really wanted to run is
1661 ;; `function' and not `execute-extended-command'. The difference is
1662 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1663 (setq real-this-command function
)
1664 (let ((prefix-arg prefixarg
))
1665 (command-execute function
'record
))
1666 ;; If enabled, show which key runs this command.
1667 ;; But first wait, and skip the message if there is input.
1669 ;; If this command displayed something in the echo area;
1670 ;; wait a few seconds, then display our suggestion message.
1671 ;; FIXME: Wait *after* running post-command-hook!
1672 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1673 ;; find a better answer anyway!
1674 (when suggest-key-bindings
1676 ((zerop (length (current-message))) 0)
1677 ((numberp suggest-key-bindings
) suggest-key-bindings
)
1679 (when (and waited
(not (consp unread-command-events
)))
1680 (unless (or binding executing-kbd-macro
(not (symbolp function
))
1681 (<= (length (symbol-name function
)) 2))
1682 ;; There's no binding for CMD. Let's try and find the shortest
1683 ;; string to use in M-x.
1684 ;; FIXME: Can be slow. Cache it maybe?
1686 (setq binding
(execute-extended-command--shorter
1687 (symbol-name function
) typed
))))
1690 (format "You can run the command `%s' with %s"
1692 (if (stringp binding
)
1693 (concat "M-x " binding
" RET")
1694 (key-description binding
)))
1695 (sit-for (if (numberp suggest-key-bindings
)
1696 suggest-key-bindings
1699 (defun command-execute (cmd &optional record-flag keys special
)
1700 ;; BEWARE: Called directly from the C code.
1701 "Execute CMD as an editor command.
1702 CMD must be a symbol that satisfies the `commandp' predicate.
1703 Optional second arg RECORD-FLAG non-nil
1704 means unconditionally put this command in the variable `command-history'.
1705 Otherwise, that is done only if an arg is read using the minibuffer.
1706 The argument KEYS specifies the value to use instead of (this-command-keys)
1707 when reading the arguments; if it is nil, (this-command-keys) is used.
1708 The argument SPECIAL, if non-nil, means that this command is executing
1709 a special event, so ignore the prefix argument and don't clear it."
1710 (setq debug-on-next-call nil
)
1711 (let ((prefixarg (unless special
1713 (setq current-prefix-arg prefix-arg
)
1714 (setq prefix-arg nil
)))))
1715 (if (and (symbolp cmd
)
1717 disabled-command-function
)
1718 ;; FIXME: Weird calling convention!
1719 (run-hooks 'disabled-command-function
)
1723 (setq final
(indirect-function final
))
1724 (if (autoloadp final
)
1725 (setq final
(autoload-do-load final cmd
)))))
1728 ;; If requested, place the macro in the command history. For
1729 ;; other sorts of commands, call-interactively takes care of this.
1731 (push `(execute-kbd-macro ,final
,prefixarg
) command-history
)
1732 ;; Don't keep command history around forever.
1733 (when (and (numberp history-length
) (> history-length
0))
1734 (let ((cell (nthcdr history-length command-history
)))
1735 (if (consp cell
) (setcdr cell nil
)))))
1736 (execute-kbd-macro final prefixarg
))
1738 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1739 (prog1 (call-interactively cmd record-flag keys
)
1740 (when (and (symbolp cmd
)
1741 (get cmd
'byte-obsolete-info
)
1742 (not (get cmd
'command-execute-obsolete-warned
)))
1743 (put cmd
'command-execute-obsolete-warned t
)
1744 (message "%s" (macroexp--obsolete-warning
1745 cmd
(get cmd
'byte-obsolete-info
) "command"))))))))))
1747 (defvar minibuffer-history nil
1748 "Default minibuffer history list.
1749 This is used for all minibuffer input
1750 except when an alternate history list is specified.
1752 Maximum length of the history list is determined by the value
1753 of `history-length', which see.")
1754 (defvar minibuffer-history-sexp-flag nil
1755 "Control whether history list elements are expressions or strings.
1756 If the value of this variable equals current minibuffer depth,
1757 they are expressions; otherwise they are strings.
1758 \(That convention is designed to do the right thing for
1759 recursive uses of the minibuffer.)")
1760 (setq minibuffer-history-variable
'minibuffer-history
)
1761 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1762 (defvar minibuffer-history-search-history nil
)
1764 (defvar minibuffer-text-before-history nil
1765 "Text that was in this minibuffer before any history commands.
1766 This is nil if there have not yet been any history commands
1767 in this use of the minibuffer.")
1769 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1771 (defun minibuffer-history-initialize ()
1772 (setq minibuffer-text-before-history nil
))
1774 (defun minibuffer-avoid-prompt (_new _old
)
1775 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1776 (declare (obsolete cursor-intangible-mode
"25.1"))
1777 (constrain-to-field nil
(point-max)))
1779 (defcustom minibuffer-history-case-insensitive-variables nil
1780 "Minibuffer history variables for which matching should ignore case.
1781 If a history variable is a member of this list, then the
1782 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1783 commands ignore case when searching it, regardless of `case-fold-search'."
1784 :type
'(repeat variable
)
1787 (defun previous-matching-history-element (regexp n
)
1788 "Find the previous history element that matches REGEXP.
1789 \(Previous history elements refer to earlier actions.)
1790 With prefix argument N, search for Nth previous match.
1791 If N is negative, find the next or Nth next match.
1792 Normally, history elements are matched case-insensitively if
1793 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1794 makes the search case-sensitive.
1795 See also `minibuffer-history-case-insensitive-variables'."
1797 (let* ((enable-recursive-minibuffers t
)
1798 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1800 minibuffer-local-map
1802 'minibuffer-history-search-history
1803 (car minibuffer-history-search-history
))))
1804 ;; Use the last regexp specified, by default, if input is empty.
1805 (list (if (string= regexp
"")
1806 (if minibuffer-history-search-history
1807 (car minibuffer-history-search-history
)
1808 (user-error "No previous history search regexp"))
1810 (prefix-numeric-value current-prefix-arg
))))
1812 (if (and (zerop minibuffer-history-position
)
1813 (null minibuffer-text-before-history
))
1814 (setq minibuffer-text-before-history
1815 (minibuffer-contents-no-properties)))
1816 (let ((history (symbol-value minibuffer-history-variable
))
1818 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1819 ;; On some systems, ignore case for file names.
1820 (if (memq minibuffer-history-variable
1821 minibuffer-history-case-insensitive-variables
)
1823 ;; Respect the user's setting for case-fold-search:
1829 (pos minibuffer-history-position
))
1832 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1833 (when (= pos prevpos
)
1834 (user-error (if (= pos
1)
1835 "No later matching history item"
1836 "No earlier matching history item")))
1838 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1839 (let ((print-level nil
))
1840 (prin1-to-string (nth (1- pos
) history
)))
1841 (nth (1- pos
) history
)))
1844 (and (string-match regexp match-string
)
1846 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1847 (match-beginning 1))))
1849 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1850 (setq minibuffer-history-position pos
)
1851 (goto-char (point-max))
1852 (delete-minibuffer-contents)
1853 (insert match-string
)
1854 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1855 (if (memq (car (car command-history
)) '(previous-matching-history-element
1856 next-matching-history-element
))
1857 (setq command-history
(cdr command-history
))))
1859 (defun next-matching-history-element (regexp n
)
1860 "Find the next history element that matches REGEXP.
1861 \(The next history element refers to a more recent action.)
1862 With prefix argument N, search for Nth next match.
1863 If N is negative, find the previous or Nth previous match.
1864 Normally, history elements are matched case-insensitively if
1865 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1866 makes the search case-sensitive."
1868 (let* ((enable-recursive-minibuffers t
)
1869 (regexp (read-from-minibuffer "Next element matching (regexp): "
1871 minibuffer-local-map
1873 'minibuffer-history-search-history
1874 (car minibuffer-history-search-history
))))
1875 ;; Use the last regexp specified, by default, if input is empty.
1876 (list (if (string= regexp
"")
1877 (if minibuffer-history-search-history
1878 (car minibuffer-history-search-history
)
1879 (user-error "No previous history search regexp"))
1881 (prefix-numeric-value current-prefix-arg
))))
1882 (previous-matching-history-element regexp
(- n
)))
1884 (defvar minibuffer-temporary-goal-position nil
)
1886 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
1887 "Function run by `goto-history-element' before consuming default values.
1888 This is useful to dynamically add more elements to the list of default values
1889 when `goto-history-element' reaches the end of this list.
1890 Before calling this function `goto-history-element' sets the variable
1891 `minibuffer-default-add-done' to t, so it will call this function only
1892 once. In special cases, when this function needs to be called more
1893 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1894 overriding the setting of this variable to t in `goto-history-element'.")
1896 (defvar minibuffer-default-add-done nil
1897 "When nil, add more elements to the end of the list of default values.
1898 The value nil causes `goto-history-element' to add more elements to
1899 the list of defaults when it reaches the end of this list. It does
1900 this by calling a function defined by `minibuffer-default-add-function'.")
1902 (make-variable-buffer-local 'minibuffer-default-add-done
)
1904 (defun minibuffer-default-add-completions ()
1905 "Return a list of all completions without the default value.
1906 This function is used to add all elements of the completion table to
1907 the end of the list of defaults just after the default value."
1908 (let ((def minibuffer-default
)
1909 (all (all-completions ""
1910 minibuffer-completion-table
1911 minibuffer-completion-predicate
)))
1914 (cons def
(delete def all
)))))
1916 (defun goto-history-element (nabs)
1917 "Puts element of the minibuffer history in the minibuffer.
1918 The argument NABS specifies the absolute history position."
1920 (when (and (not minibuffer-default-add-done
)
1921 (functionp minibuffer-default-add-function
)
1922 (< nabs
(- (if (listp minibuffer-default
)
1923 (length minibuffer-default
)
1925 (setq minibuffer-default-add-done t
1926 minibuffer-default
(funcall minibuffer-default-add-function
)))
1927 (let ((minimum (if minibuffer-default
1928 (- (if (listp minibuffer-default
)
1929 (length minibuffer-default
)
1932 elt minibuffer-returned-to-present
)
1933 (if (and (zerop minibuffer-history-position
)
1934 (null minibuffer-text-before-history
))
1935 (setq minibuffer-text-before-history
1936 (minibuffer-contents-no-properties)))
1937 (if (< nabs minimum
)
1938 (user-error (if minibuffer-default
1939 "End of defaults; no next item"
1940 "End of history; no default available")))
1941 (if (> nabs
(if (listp (symbol-value minibuffer-history-variable
))
1942 (length (symbol-value minibuffer-history-variable
))
1944 (user-error "Beginning of history; no preceding item"))
1945 (unless (memq last-command
'(next-history-element
1946 previous-history-element
))
1947 (let ((prompt-end (minibuffer-prompt-end)))
1948 (set (make-local-variable 'minibuffer-temporary-goal-position
)
1949 (cond ((<= (point) prompt-end
) prompt-end
)
1952 (goto-char (point-max))
1953 (delete-minibuffer-contents)
1954 (setq minibuffer-history-position nabs
)
1956 (setq elt
(if (listp minibuffer-default
)
1957 (nth (1- (abs nabs
)) minibuffer-default
)
1958 minibuffer-default
)))
1960 (setq elt
(or minibuffer-text-before-history
""))
1961 (setq minibuffer-returned-to-present t
)
1962 (setq minibuffer-text-before-history nil
))
1963 (t (setq elt
(nth (1- minibuffer-history-position
)
1964 (symbol-value minibuffer-history-variable
)))))
1966 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1967 (not minibuffer-returned-to-present
))
1968 (let ((print-level nil
))
1969 (prin1-to-string elt
))
1971 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
1973 (defun next-history-element (n)
1974 "Puts next element of the minibuffer history in the minibuffer.
1975 With argument N, it uses the Nth following element."
1978 (goto-history-element (- minibuffer-history-position n
))))
1980 (defun previous-history-element (n)
1981 "Puts previous element of the minibuffer history in the minibuffer.
1982 With argument N, it uses the Nth previous element."
1985 (goto-history-element (+ minibuffer-history-position n
))))
1987 (defun next-line-or-history-element (&optional arg
)
1988 "Move cursor vertically down ARG lines, or to the next history element.
1989 When point moves over the bottom line of multi-line minibuffer, puts ARGth
1990 next element of the minibuffer history in the minibuffer."
1992 (or arg
(setq arg
1))
1993 (let* ((old-point (point))
1994 ;; Remember the original goal column of possibly multi-line input
1995 ;; excluding the length of the prompt on the first line.
1996 (prompt-end (minibuffer-prompt-end))
1997 (old-column (unless (and (eolp) (> (point) prompt-end
))
1998 (if (= (line-number-at-pos) 1)
1999 (max (- (current-column) (1- prompt-end
)) 0)
2000 (current-column)))))
2005 ;; Restore old position since `line-move-visual' moves point to
2006 ;; the end of the line when it fails to go to the next line.
2007 (goto-char old-point
)
2008 (next-history-element arg
)
2009 ;; Restore the original goal column on the last line
2010 ;; of possibly multi-line input.
2011 (goto-char (point-max))
2013 (if (= (line-number-at-pos) 1)
2014 (move-to-column (+ old-column
(1- (minibuffer-prompt-end))))
2015 (move-to-column old-column
)))))))
2017 (defun previous-line-or-history-element (&optional arg
)
2018 "Move cursor vertically up ARG lines, or to the previous history element.
2019 When point moves over the top line of multi-line minibuffer, puts ARGth
2020 previous element of the minibuffer history in the minibuffer."
2022 (or arg
(setq arg
1))
2023 (let* ((old-point (point))
2024 ;; Remember the original goal column of possibly multi-line input
2025 ;; excluding the length of the prompt on the first line.
2026 (prompt-end (minibuffer-prompt-end))
2027 (old-column (unless (and (eolp) (> (point) prompt-end
))
2028 (if (= (line-number-at-pos) 1)
2029 (max (- (current-column) (1- prompt-end
)) 0)
2030 (current-column)))))
2033 (previous-line arg
))
2034 (beginning-of-buffer
2035 ;; Restore old position since `line-move-visual' moves point to
2036 ;; the beginning of the line when it fails to go to the previous line.
2037 (goto-char old-point
)
2038 (previous-history-element arg
)
2039 ;; Restore the original goal column on the first line
2040 ;; of possibly multi-line input.
2041 (goto-char (minibuffer-prompt-end))
2043 (if (= (line-number-at-pos) 1)
2044 (move-to-column (+ old-column
(1- (minibuffer-prompt-end))))
2045 (move-to-column old-column
))
2046 (goto-char (line-end-position)))))))
2048 (defun next-complete-history-element (n)
2049 "Get next history element which completes the minibuffer before the point.
2050 The contents of the minibuffer after the point are deleted, and replaced
2051 by the new completion."
2053 (let ((point-at-start (point)))
2054 (next-matching-history-element
2056 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2058 ;; next-matching-history-element always puts us at (point-min).
2059 ;; Move to the position we were at before changing the buffer contents.
2060 ;; This is still sensible, because the text before point has not changed.
2061 (goto-char point-at-start
)))
2063 (defun previous-complete-history-element (n)
2065 Get previous history element which completes the minibuffer before the point.
2066 The contents of the minibuffer after the point are deleted, and replaced
2067 by the new completion."
2069 (next-complete-history-element (- n
)))
2071 ;; For compatibility with the old subr of the same name.
2072 (defun minibuffer-prompt-width ()
2073 "Return the display width of the minibuffer prompt.
2074 Return 0 if current buffer is not a minibuffer."
2075 ;; Return the width of everything before the field at the end of
2076 ;; the buffer; this should be 0 for normal buffers.
2077 (1- (minibuffer-prompt-end)))
2079 ;; isearch minibuffer history
2080 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
2082 (defvar minibuffer-history-isearch-message-overlay
)
2083 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
2085 (defun minibuffer-history-isearch-setup ()
2086 "Set up a minibuffer for using isearch to search the minibuffer history.
2087 Intended to be added to `minibuffer-setup-hook'."
2088 (set (make-local-variable 'isearch-search-fun-function
)
2089 'minibuffer-history-isearch-search
)
2090 (set (make-local-variable 'isearch-message-function
)
2091 'minibuffer-history-isearch-message
)
2092 (set (make-local-variable 'isearch-wrap-function
)
2093 'minibuffer-history-isearch-wrap
)
2094 (set (make-local-variable 'isearch-push-state-function
)
2095 'minibuffer-history-isearch-push-state
)
2096 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
2098 (defun minibuffer-history-isearch-end ()
2099 "Clean up the minibuffer after terminating isearch in the minibuffer."
2100 (if minibuffer-history-isearch-message-overlay
2101 (delete-overlay minibuffer-history-isearch-message-overlay
)))
2103 (defun minibuffer-history-isearch-search ()
2104 "Return the proper search function, for isearch in minibuffer history."
2105 (lambda (string bound noerror
)
2107 ;; Use standard functions to search within minibuffer text
2108 (isearch-search-fun-default))
2110 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2111 ;; searching forward. Lazy-highlight calls this lambda with the
2112 ;; bound arg, so skip the minibuffer prompt.
2113 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
2114 (goto-char (minibuffer-prompt-end)))
2116 ;; 1. First try searching in the initial minibuffer text
2117 (funcall search-fun string
2118 (if isearch-forward bound
(minibuffer-prompt-end))
2120 ;; 2. If the above search fails, start putting next/prev history
2121 ;; elements in the minibuffer successively, and search the string
2122 ;; in them. Do this only when bound is nil (i.e. not while
2123 ;; lazy-highlighting search strings in the current minibuffer text).
2128 (cond (isearch-forward
2129 (next-history-element 1)
2130 (goto-char (minibuffer-prompt-end)))
2132 (previous-history-element 1)
2133 (goto-char (point-max))))
2134 (setq isearch-barrier
(point) isearch-opoint
(point))
2135 ;; After putting the next/prev history element, search
2136 ;; the string in them again, until next-history-element
2137 ;; or previous-history-element raises an error at the
2138 ;; beginning/end of history.
2139 (setq found
(funcall search-fun string
2140 (unless isearch-forward
2141 ;; For backward search, don't search
2142 ;; in the minibuffer prompt
2143 (minibuffer-prompt-end))
2145 ;; Return point of the new search result
2147 ;; Return nil when next(prev)-history-element fails
2150 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
2151 "Display the minibuffer history search prompt.
2152 If there are no search errors, this function displays an overlay with
2153 the isearch prompt which replaces the original minibuffer prompt.
2154 Otherwise, it displays the standard isearch message returned from
2155 the function `isearch-message'."
2156 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
2157 ;; Use standard function `isearch-message' when not in the minibuffer,
2158 ;; or search fails, or has an error (like incomplete regexp).
2159 ;; This function overwrites minibuffer text with isearch message,
2160 ;; so it's possible to see what is wrong in the search string.
2161 (isearch-message c-q-hack ellipsis
)
2162 ;; Otherwise, put the overlay with the standard isearch prompt over
2163 ;; the initial minibuffer prompt.
2164 (if (overlayp minibuffer-history-isearch-message-overlay
)
2165 (move-overlay minibuffer-history-isearch-message-overlay
2166 (point-min) (minibuffer-prompt-end))
2167 (setq minibuffer-history-isearch-message-overlay
2168 (make-overlay (point-min) (minibuffer-prompt-end)))
2169 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
2170 (overlay-put minibuffer-history-isearch-message-overlay
2171 'display
(isearch-message-prefix c-q-hack ellipsis
))
2172 ;; And clear any previous isearch message.
2175 (defun minibuffer-history-isearch-wrap ()
2176 "Wrap the minibuffer history search when search fails.
2177 Move point to the first history element for a forward search,
2178 or to the last history element for a backward search."
2179 ;; When `minibuffer-history-isearch-search' fails on reaching the
2180 ;; beginning/end of the history, wrap the search to the first/last
2181 ;; minibuffer history element.
2183 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
2184 (goto-history-element 0))
2185 (setq isearch-success t
)
2186 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
2188 (defun minibuffer-history-isearch-push-state ()
2189 "Save a function restoring the state of minibuffer history search.
2190 Save `minibuffer-history-position' to the additional state parameter
2191 in the search status stack."
2192 (let ((pos minibuffer-history-position
))
2194 (minibuffer-history-isearch-pop-state cmd pos
))))
2196 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos
)
2197 "Restore the minibuffer history search state.
2198 Go to the history element by the absolute history position HIST-POS."
2199 (goto-history-element hist-pos
))
2202 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2203 (define-obsolete-function-alias 'advertised-undo
'undo
"23.2")
2205 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
2206 "Table mapping redo records to the corresponding undo one.
2207 A redo record for undo-in-region maps to t.
2208 A redo record for ordinary undo maps to the following (earlier) undo.")
2210 (defvar undo-in-region nil
2211 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2213 (defvar undo-no-redo nil
2214 "If t, `undo' doesn't go through redo entries.")
2216 (defvar pending-undo-list nil
2217 "Within a run of consecutive undo commands, list remaining to be undone.
2218 If t, we undid all the way to the end of it.")
2220 (defun undo (&optional arg
)
2221 "Undo some previous changes.
2222 Repeat this command to undo more changes.
2223 A numeric ARG serves as a repeat count.
2225 In Transient Mark mode when the mark is active, only undo changes within
2226 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2227 as an argument limits undo to changes within the current region."
2229 ;; Make last-command indicate for the next command that this was an undo.
2230 ;; That way, another undo will undo more.
2231 ;; If we get to the end of the undo history and get an error,
2232 ;; another undo command will find the undo history empty
2233 ;; and will get another error. To begin undoing the undos,
2234 ;; you must type some other command.
2235 (let* ((modified (buffer-modified-p))
2236 ;; For an indirect buffer, look in the base buffer for the
2238 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2239 (recent-save (with-current-buffer base-buffer
2240 (recent-auto-save-p)))
2242 ;; If we get an error in undo-start,
2243 ;; the next command should not be a "consecutive undo".
2244 ;; So set `this-command' to something other than `undo'.
2245 (setq this-command
'undo-start
)
2247 (unless (and (eq last-command
'undo
)
2248 (or (eq pending-undo-list t
)
2249 ;; If something (a timer or filter?) changed the buffer
2250 ;; since the previous command, don't continue the undo seq.
2251 (let ((list buffer-undo-list
))
2252 (while (eq (car list
) nil
)
2253 (setq list
(cdr list
)))
2254 ;; If the last undo record made was made by undo
2255 ;; it shows nothing else happened in between.
2256 (gethash list undo-equiv-table
))))
2257 (setq undo-in-region
2258 (or (region-active-p) (and arg
(not (numberp arg
)))))
2260 (undo-start (region-beginning) (region-end))
2262 ;; get rid of initial undo boundary
2264 ;; If we got this far, the next command should be a consecutive undo.
2265 (setq this-command
'undo
)
2266 ;; Check to see whether we're hitting a redo record, and if
2267 ;; so, ask the user whether she wants to skip the redo/undo pair.
2268 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
2269 (or (eq (selected-window) (minibuffer-window))
2270 (setq message
(format "%s%s!"
2271 (if (or undo-no-redo
(not equiv
))
2273 (if undo-in-region
" in region" ""))))
2274 (when (and (consp equiv
) undo-no-redo
)
2275 ;; The equiv entry might point to another redo record if we have done
2276 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2277 (while (let ((next (gethash equiv undo-equiv-table
)))
2278 (if next
(setq equiv next
))))
2279 (setq pending-undo-list equiv
)))
2282 (prefix-numeric-value arg
)
2284 ;; Record the fact that the just-generated undo records come from an
2285 ;; undo operation--that is, they are redo records.
2286 ;; In the ordinary case (not within a region), map the redo
2287 ;; record to the following undos.
2288 ;; I don't know how to do that in the undo-in-region case.
2289 (let ((list buffer-undo-list
))
2290 ;; Strip any leading undo boundaries there might be, like we do
2291 ;; above when checking.
2292 (while (eq (car list
) nil
)
2293 (setq list
(cdr list
)))
2295 ;; Prevent identity mapping. This can happen if
2296 ;; consecutive nils are erroneously in undo list.
2297 (if (or undo-in-region
(eq list pending-undo-list
))
2301 ;; Don't specify a position in the undo record for the undo command.
2302 ;; Instead, undoing this should move point to where the change is.
2303 (let ((tail buffer-undo-list
)
2306 (when (integerp (car tail
))
2307 (let ((pos (car tail
)))
2309 (setcdr prev
(cdr tail
))
2310 (setq buffer-undo-list
(cdr tail
)))
2311 (setq tail
(cdr tail
))
2313 (if (eq pos
(car tail
))
2315 (setcdr prev
(cdr tail
))
2316 (setq buffer-undo-list
(cdr tail
)))
2318 (setq tail
(cdr tail
)))
2320 (setq prev tail tail
(cdr tail
))))
2321 ;; Record what the current undo list says,
2322 ;; so the next command can tell if the buffer was modified in between.
2323 (and modified
(not (buffer-modified-p))
2324 (with-current-buffer base-buffer
2325 (delete-auto-save-file-if-necessary recent-save
)))
2326 ;; Display a message announcing success.
2328 (message "%s" message
))))
2330 (defun buffer-disable-undo (&optional buffer
)
2331 "Make BUFFER stop keeping undo information.
2332 No argument or nil as argument means do this for the current buffer."
2334 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
2335 (setq buffer-undo-list t
)))
2337 (defun undo-only (&optional arg
)
2338 "Undo some previous changes.
2339 Repeat this command to undo more changes.
2340 A numeric ARG serves as a repeat count.
2341 Contrary to `undo', this will not redo a previous undo."
2343 (let ((undo-no-redo t
)) (undo arg
)))
2345 (defvar undo-in-progress nil
2346 "Non-nil while performing an undo.
2347 Some change-hooks test this variable to do something different.")
2349 (defun undo-more (n)
2350 "Undo back N undo-boundaries beyond what was already undone recently.
2351 Call `undo-start' to get ready to undo recent changes,
2352 then call `undo-more' one or more times to undo them."
2353 (or (listp pending-undo-list
)
2354 (user-error (concat "No further undo information"
2355 (and undo-in-region
" for region"))))
2356 (let ((undo-in-progress t
))
2357 ;; Note: The following, while pulling elements off
2358 ;; `pending-undo-list' will call primitive change functions which
2359 ;; will push more elements onto `buffer-undo-list'.
2360 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
2361 (if (null pending-undo-list
)
2362 (setq pending-undo-list t
))))
2364 (defun primitive-undo (n list
)
2365 "Undo N records from the front of the list LIST.
2366 Return what remains of the list."
2368 ;; This is a good feature, but would make undo-start
2369 ;; unable to do what is expected.
2370 ;;(when (null (car (list)))
2371 ;; ;; If the head of the list is a boundary, it is the boundary
2372 ;; ;; preceding this command. Get rid of it and don't count it.
2373 ;; (setq list (cdr list))))
2376 ;; In a writable buffer, enable undoing read-only text that is
2377 ;; so because of text properties.
2378 (inhibit-read-only t
)
2379 ;; Don't let `intangible' properties interfere with undo.
2380 (inhibit-point-motion-hooks t
)
2381 ;; We use oldlist only to check for EQ. ++kfs
2382 (oldlist buffer-undo-list
)
2386 (while (setq next
(pop list
)) ;Exit inner loop at undo boundary.
2387 ;; Handle an integer by setting point to that value.
2389 ((pred integerp
) (goto-char next
))
2390 ;; Element (t . TIME) records previous modtime.
2391 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2392 ;; UNKNOWN_MODTIME_NSECS.
2394 ;; If this records an obsolete save
2395 ;; (not matching the actual disk file)
2396 ;; then don't mark unmodified.
2397 (when (or (equal time
(visited-file-modtime))
2399 (equal (list (car time
) (cdr time
))
2400 (visited-file-modtime))))
2401 (when (fboundp 'unlock-buffer
)
2403 (set-buffer-modified-p nil
)))
2404 ;; Element (nil PROP VAL BEG . END) is property change.
2405 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2406 (when (or (> (point-min) beg
) (< (point-max) end
))
2407 (error "Changes to be undone are outside visible portion of buffer"))
2408 (put-text-property beg end prop val
))
2409 ;; Element (BEG . END) means range was inserted.
2410 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2411 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2412 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2413 (when (or (> (point-min) beg
) (< (point-max) end
))
2414 (error "Changes to be undone are outside visible portion of buffer"))
2415 ;; Set point first thing, so that undoing this undo
2416 ;; does not send point back to where it is now.
2418 (delete-region beg end
))
2419 ;; Element (apply FUN . ARGS) means call FUN to undo.
2420 (`(apply .
,fun-args
)
2421 (let ((currbuff (current-buffer)))
2422 (if (integerp (car fun-args
))
2423 ;; Long format: (apply DELTA START END FUN . ARGS).
2424 (pcase-let* ((`(,delta
,start
,end
,fun .
,args
) fun-args
)
2425 (start-mark (copy-marker start nil
))
2426 (end-mark (copy-marker end t
)))
2427 (when (or (> (point-min) start
) (< (point-max) end
))
2428 (error "Changes to be undone are outside visible portion of buffer"))
2429 (apply fun args
) ;; Use `save-current-buffer'?
2430 ;; Check that the function did what the entry
2431 ;; said it would do.
2432 (unless (and (= start start-mark
)
2433 (= (+ delta end
) end-mark
))
2434 (error "Changes to be undone by function different than announced"))
2435 (set-marker start-mark nil
)
2436 (set-marker end-mark nil
))
2438 (unless (eq currbuff
(current-buffer))
2439 (error "Undo function switched buffer"))
2440 (setq did-apply t
)))
2441 ;; Element (STRING . POS) means STRING was deleted.
2442 (`(,(and string
(pred stringp
)) .
,(and pos
(pred integerp
)))
2443 (when (let ((apos (abs pos
)))
2444 (or (< apos
(point-min)) (> apos
(point-max))))
2445 (error "Changes to be undone are outside visible portion of buffer"))
2446 (let (valid-marker-adjustments)
2447 ;; Check that marker adjustments which were recorded
2448 ;; with the (STRING . POS) record are still valid, ie
2449 ;; the markers haven't moved. We check their validity
2450 ;; before reinserting the string so as we don't need to
2451 ;; mind marker insertion-type.
2452 (while (and (markerp (car-safe (car list
)))
2453 (integerp (cdr-safe (car list
))))
2454 (let* ((marker-adj (pop list
))
2455 (m (car marker-adj
)))
2456 (and (eq (marker-buffer m
) (current-buffer))
2458 (push marker-adj valid-marker-adjustments
))))
2459 ;; Insert string and adjust point
2467 ;; Adjust the valid marker adjustments
2468 (dolist (adj valid-marker-adjustments
)
2469 (set-marker (car adj
)
2470 (- (car adj
) (cdr adj
))))))
2471 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2472 (`(,(and marker
(pred markerp
)) .
,(and offset
(pred integerp
)))
2473 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2475 ;; Even though these elements are not expected in the undo
2476 ;; list, adjust them to be conservative for the 24.4
2477 ;; release. (Bug#16818)
2478 (when (marker-buffer marker
)
2481 (marker-buffer marker
))))
2482 (_ (error "Unrecognized entry in undo list %S" next
))))
2483 (setq arg
(1- arg
)))
2484 ;; Make sure an apply entry produces at least one undo entry,
2485 ;; so the test in `undo' for continuing an undo series
2488 (eq oldlist buffer-undo-list
))
2489 (setq buffer-undo-list
2490 (cons (list 'apply
'cdr nil
) buffer-undo-list
))))
2493 ;; Deep copy of a list
2494 (defun undo-copy-list (list)
2495 "Make a copy of undo list LIST."
2496 (mapcar 'undo-copy-list-1 list
))
2498 (defun undo-copy-list-1 (elt)
2500 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
2503 (defun undo-start (&optional beg end
)
2504 "Set `pending-undo-list' to the front of the undo list.
2505 The next call to `undo-more' will undo the most recently made change.
2506 If BEG and END are specified, then only undo elements
2507 that apply to text between BEG and END are used; other undo elements
2508 are ignored. If BEG and END are nil, all undo elements are used."
2509 (if (eq buffer-undo-list t
)
2510 (user-error "No undo information in this buffer"))
2511 (setq pending-undo-list
2512 (if (and beg end
(not (= beg end
)))
2513 (undo-make-selective-list (min beg end
) (max beg end
))
2516 ;; The positions given in elements of the undo list are the positions
2517 ;; as of the time that element was recorded to undo history. In
2518 ;; general, subsequent buffer edits render those positions invalid in
2519 ;; the current buffer, unless adjusted according to the intervening
2522 ;; Undo in region is a use case that requires adjustments to undo
2523 ;; elements. It must adjust positions of elements in the region based
2524 ;; on newer elements not in the region so as they may be correctly
2525 ;; applied in the current buffer. undo-make-selective-list
2526 ;; accomplishes this with its undo-deltas list of adjustments. An
2527 ;; example undo history from oldest to newest:
2530 ;; 123456789 buffer-undo-list undo-deltas
2531 ;; --------- ---------------- -----------
2532 ;; aaa (1 . 4) (1 . -3)
2533 ;; aaba (3 . 4) N/A (in region)
2534 ;; ccaaba (1 . 3) (1 . -2)
2535 ;; ccaabaddd (7 . 10) (7 . -3)
2536 ;; ccaabdd ("ad" . 6) (6 . 2)
2537 ;; ccaabaddd (6 . 8) (6 . -2)
2538 ;; | |<-- region: "caab", from 2 to 6
2540 ;; When the user starts a run of undos in region,
2541 ;; undo-make-selective-list is called to create the full list of in
2542 ;; region elements. Each element is adjusted forward chronologically
2543 ;; through undo-deltas to determine if it is in the region.
2545 ;; In the above example, the insertion of "b" is (3 . 4) in the
2546 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2547 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2548 ;; . 6) is assessed as in the region and placed in the selective list.
2549 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2550 ;; due to the selected element. The "b" insertion is the only element
2551 ;; fully in the region, so in this example undo-make-selective-list
2552 ;; returns (nil (5 . 6)).
2554 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2555 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2556 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2557 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2558 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2560 ;; More interesting is how to adjust the "ddd" insertion due to the
2561 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2562 ;; If the reinsertion was a manual retyping of "ad", then the total
2563 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2564 ;; the reinsertion was due to undo, one might expect the first "d"
2565 ;; character would again be a part of the "ddd" text, meaning its
2566 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2568 ;; undo-make-selective-list assumes in this situation that "ad" was a
2569 ;; new edit, even if it was inserted because of an undo.
2570 ;; Consequently, if the user undos in region "8 to 10" of the
2571 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2572 ;; "ccaabad", as though the first "d" became detached from the
2573 ;; original "ddd" insertion. This quirk is a FIXME.
2575 (defun undo-make-selective-list (start end
)
2576 "Return a list of undo elements for the region START to END.
2577 The elements come from `buffer-undo-list', but we keep only the
2578 elements inside this region, and discard those outside this
2579 region. The elements' positions are adjusted so as the returned
2580 list can be applied to the current buffer."
2581 (let ((ulist buffer-undo-list
)
2582 ;; A list of position adjusted undo elements in the region.
2583 (selective-list (list nil
))
2584 ;; A list of undo-deltas for out of region undo elements.
2589 (while (gethash ulist undo-equiv-table
)
2590 (setq ulist
(gethash ulist undo-equiv-table
))))
2591 (setq undo-elt
(car ulist
))
2594 ;; Don't put two nils together in the list
2595 (when (car selective-list
)
2596 (push nil selective-list
)))
2597 ((and (consp undo-elt
) (eq (car undo-elt
) t
))
2598 ;; This is a "was unmodified" element. Keep it
2599 ;; if we have kept everything thus far.
2600 (when (not undo-deltas
)
2601 (push undo-elt selective-list
)))
2602 ;; Skip over marker adjustments, instead relying
2603 ;; on finding them after (TEXT . POS) elements
2604 ((markerp (car-safe undo-elt
))
2607 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2609 (if (undo-elt-in-region adjusted-undo-elt start end
)
2611 (setq end
(+ end
(cdr (undo-delta adjusted-undo-elt
))))
2612 (push adjusted-undo-elt selective-list
)
2613 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2614 ;; kept. primitive-undo may discard them later.
2615 (when (and (stringp (car-safe adjusted-undo-elt
))
2616 (integerp (cdr-safe adjusted-undo-elt
)))
2617 (let ((list-i (cdr ulist
)))
2618 (while (markerp (car-safe (car list-i
)))
2619 (push (pop list-i
) selective-list
)))))
2620 (let ((delta (undo-delta undo-elt
)))
2621 (when (/= 0 (cdr delta
))
2622 (push delta undo-deltas
)))))))
2624 (nreverse selective-list
)))
2626 (defun undo-elt-in-region (undo-elt start end
)
2627 "Determine whether UNDO-ELT falls inside the region START ... END.
2628 If it crosses the edge, we return nil.
2630 Generally this function is not useful for determining
2631 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2632 because markers can be arbitrarily relocated. Instead, pass the
2633 marker adjustment's corresponding (TEXT . POS) element."
2634 (cond ((integerp undo-elt
)
2635 (and (>= undo-elt start
)
2641 ((stringp (car undo-elt
))
2642 ;; (TEXT . POSITION)
2643 (and (>= (abs (cdr undo-elt
)) start
)
2644 (<= (abs (cdr undo-elt
)) end
)))
2645 ((and (consp undo-elt
) (markerp (car undo-elt
)))
2646 ;; (MARKER . ADJUSTMENT)
2647 (<= start
(car undo-elt
) end
))
2648 ((null (car undo-elt
))
2649 ;; (nil PROPERTY VALUE BEG . END)
2650 (let ((tail (nthcdr 3 undo-elt
)))
2651 (and (>= (car tail
) start
)
2652 (<= (cdr tail
) end
))))
2653 ((integerp (car undo-elt
))
2655 (and (>= (car undo-elt
) start
)
2656 (<= (cdr undo-elt
) end
)))))
2658 (defun undo-elt-crosses-region (undo-elt start end
)
2659 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2660 This assumes we have already decided that UNDO-ELT
2661 is not *inside* the region START...END."
2662 (declare (obsolete nil
"25.1"))
2663 (cond ((atom undo-elt
) nil
)
2664 ((null (car undo-elt
))
2665 ;; (nil PROPERTY VALUE BEG . END)
2666 (let ((tail (nthcdr 3 undo-elt
)))
2667 (and (< (car tail
) end
)
2668 (> (cdr tail
) start
))))
2669 ((integerp (car undo-elt
))
2671 (and (< (car undo-elt
) end
)
2672 (> (cdr undo-elt
) start
)))))
2674 (defun undo-adjust-elt (elt deltas
)
2675 "Return adjustment of undo element ELT by the undo DELTAS
2680 (undo-adjust-pos elt deltas
))
2682 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2683 (undo-adjust-beg-end beg end deltas
))
2684 ;; (TEXT . POSITION)
2685 (`(,(and text
(pred stringp
)) .
,(and pos
(pred integerp
)))
2686 (cons text
(* (if (< pos
0) -
1 1)
2687 (undo-adjust-pos (abs pos
) deltas
))))
2688 ;; (nil PROPERTY VALUE BEG . END)
2689 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2690 `(nil ,prop
,val .
,(undo-adjust-beg-end beg end deltas
)))
2691 ;; (apply DELTA START END FUN . ARGS)
2693 ;; All others return same elt
2696 ;; (BEG . END) can adjust to the same positions, commonly when an
2697 ;; insertion was undone and they are out of region, for example:
2700 ;; 123456789 buffer-undo-list undo-deltas
2701 ;; --------- ---------------- -----------
2703 ;; abbaa (2 . 4) (2 . -2)
2704 ;; aaa ("bb" . 2) (2 . 2)
2707 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2708 ;; undo. Further adjustments to such an element should be the same as
2709 ;; for (TEXT . POSITION) elements. The options are:
2711 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2712 ;; analogous to marker insertion-type t.
2714 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2715 ;; marker insertion-type nil.
2717 ;; There was no strong reason to prefer one or the other, except that
2718 ;; the first is more consistent with prior undo in region behavior.
2719 (defun undo-adjust-beg-end (beg end deltas
)
2720 "Return cons of adjustments to BEG and END by the undo DELTAS
2722 (let ((adj-beg (undo-adjust-pos beg deltas
)))
2723 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2725 (max adj-beg
(undo-adjust-pos end deltas t
)))))
2727 (defun undo-adjust-pos (pos deltas
&optional use-
<)
2728 "Return adjustment of POS by the undo DELTAS list, comparing
2729 with < or <= based on USE-<."
2730 (dolist (d deltas pos
)
2735 ;; Don't allow pos to become less than the undo-delta
2736 ;; position. This edge case is described in the overview
2738 (max (car d
) (- pos
(cdr d
)))))))
2740 ;; Return the first affected buffer position and the delta for an undo element
2741 ;; delta is defined as the change in subsequent buffer positions if we *did*
2743 (defun undo-delta (undo-elt)
2744 (if (consp undo-elt
)
2745 (cond ((stringp (car undo-elt
))
2746 ;; (TEXT . POSITION)
2747 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
2748 ((integerp (car undo-elt
))
2750 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
2755 (defcustom undo-ask-before-discard nil
2756 "If non-nil ask about discarding undo info for the current command.
2757 Normally, Emacs discards the undo info for the current command if
2758 it exceeds `undo-outer-limit'. But if you set this option
2759 non-nil, it asks in the echo area whether to discard the info.
2760 If you answer no, there is a slight risk that Emacs might crash, so
2761 only do it if you really want to undo the command.
2763 This option is mainly intended for debugging. You have to be
2764 careful if you use it for other purposes. Garbage collection is
2765 inhibited while the question is asked, meaning that Emacs might
2766 leak memory. So you should make sure that you do not wait
2767 excessively long before answering the question."
2772 (defvar undo-extra-outer-limit nil
2773 "If non-nil, an extra level of size that's ok in an undo item.
2774 We don't ask the user about truncating the undo list until the
2775 current item gets bigger than this amount.
2777 This variable only matters if `undo-ask-before-discard' is non-nil.")
2778 (make-variable-buffer-local 'undo-extra-outer-limit
)
2780 ;; When the first undo batch in an undo list is longer than
2781 ;; undo-outer-limit, this function gets called to warn the user that
2782 ;; the undo info for the current command was discarded. Garbage
2783 ;; collection is inhibited around the call, so it had better not do a
2785 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
2786 (defun undo-outer-limit-truncate (size)
2787 (if undo-ask-before-discard
2788 (when (or (null undo-extra-outer-limit
)
2789 (> size undo-extra-outer-limit
))
2790 ;; Don't ask the question again unless it gets even bigger.
2791 ;; This applies, in particular, if the user quits from the question.
2792 ;; Such a quit quits out of GC, but something else will call GC
2793 ;; again momentarily. It will call this function again,
2794 ;; but we don't want to ask the question again.
2795 (setq undo-extra-outer-limit
(+ size
50000))
2796 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
2797 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2798 (buffer-name) size
)))
2799 (progn (setq buffer-undo-list nil
)
2800 (setq undo-extra-outer-limit nil
)
2803 (display-warning '(undo discard-info
)
2805 (format "Buffer `%s' undo info was %d bytes long.\n"
2807 "The undo info was discarded because it exceeded \
2810 This is normal if you executed a command that made a huge change
2811 to the buffer. In that case, to prevent similar problems in the
2812 future, set `undo-outer-limit' to a value that is large enough to
2813 cover the maximum size of normal changes you expect a single
2814 command to make, but not so large that it might exceed the
2815 maximum memory allotted to Emacs.
2817 If you did not execute any such command, the situation is
2818 probably due to a bug and you should report it.
2820 You can disable the popping up of this buffer by adding the entry
2821 \(undo discard-info) to the user option `warning-suppress-types',
2822 which is defined in the `warnings' library.\n")
2824 (setq buffer-undo-list nil
)
2827 (defcustom password-word-equivalents
2828 '("password" "passcode" "passphrase" "pass phrase"
2829 ; These are sorted according to the GNU en_US locale.
2832 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
2858 "пароль" ; kk, ru, uk
2873 "List of words equivalent to \"password\".
2874 This is used by Shell mode and other parts of Emacs to recognize
2875 password prompts, including prompts in languages other than
2876 English. Different case choices should not be assumed to be
2877 included; callers should bind `case-fold-search' to t."
2878 :type
'(repeat string
)
2882 (defvar shell-command-history nil
2883 "History list for some commands that read shell commands.
2885 Maximum length of the history list is determined by the value
2886 of `history-length', which see.")
2888 (defvar shell-command-switch
(purecopy "-c")
2889 "Switch used to have the shell execute its command line argument.")
2891 (defvar shell-command-default-error-buffer nil
2892 "Buffer name for `shell-command' and `shell-command-on-region' error output.
2893 This buffer is used when `shell-command' or `shell-command-on-region'
2894 is run interactively. A value of nil means that output to stderr and
2895 stdout will be intermixed in the output stream.")
2897 (declare-function mailcap-file-default-commands
"mailcap" (files))
2898 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
2900 (defun minibuffer-default-add-shell-commands ()
2901 "Return a list of all commands associated with the current file.
2902 This function is used to add all related commands retrieved by `mailcap'
2903 to the end of the list of defaults just after the default value."
2905 (let* ((filename (if (listp minibuffer-default
)
2906 (car minibuffer-default
)
2907 minibuffer-default
))
2908 (commands (and filename
(require 'mailcap nil t
)
2909 (mailcap-file-default-commands (list filename
)))))
2910 (setq commands
(mapcar (lambda (command)
2911 (concat command
" " filename
))
2913 (if (listp minibuffer-default
)
2914 (append minibuffer-default commands
)
2915 (cons minibuffer-default commands
))))
2917 (declare-function shell-completion-vars
"shell" ())
2919 (defvar minibuffer-local-shell-command-map
2920 (let ((map (make-sparse-keymap)))
2921 (set-keymap-parent map minibuffer-local-map
)
2922 (define-key map
"\t" 'completion-at-point
)
2924 "Keymap used for completing shell commands in minibuffer.")
2926 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
2927 "Read a shell command from the minibuffer.
2928 The arguments are the same as the ones of `read-from-minibuffer',
2929 except READ and KEYMAP are missing and HIST defaults
2930 to `shell-command-history'."
2932 (minibuffer-with-setup-hook
2934 (shell-completion-vars)
2935 (set (make-local-variable 'minibuffer-default-add-function
)
2936 'minibuffer-default-add-shell-commands
))
2937 (apply 'read-from-minibuffer prompt initial-contents
2938 minibuffer-local-shell-command-map
2940 (or hist
'shell-command-history
)
2943 (defcustom async-shell-command-buffer
'confirm-new-buffer
2944 "What to do when the output buffer is used by another shell command.
2945 This option specifies how to resolve the conflict where a new command
2946 wants to direct its output to the buffer `*Async Shell Command*',
2947 but this buffer is already taken by another running shell command.
2949 The value `confirm-kill-process' is used to ask for confirmation before
2950 killing the already running process and running a new process
2951 in the same buffer, `confirm-new-buffer' for confirmation before running
2952 the command in a new buffer with a name other than the default buffer name,
2953 `new-buffer' for doing the same without confirmation,
2954 `confirm-rename-buffer' for confirmation before renaming the existing
2955 output buffer and running a new command in the default buffer,
2956 `rename-buffer' for doing the same without confirmation."
2957 :type
'(choice (const :tag
"Confirm killing of running command"
2958 confirm-kill-process
)
2959 (const :tag
"Confirm creation of a new buffer"
2961 (const :tag
"Create a new buffer"
2963 (const :tag
"Confirm renaming of existing buffer"
2964 confirm-rename-buffer
)
2965 (const :tag
"Rename the existing buffer"
2970 (defun async-shell-command (command &optional output-buffer error-buffer
)
2971 "Execute string COMMAND asynchronously in background.
2973 Like `shell-command', but adds `&' at the end of COMMAND
2974 to execute it asynchronously.
2976 The output appears in the buffer `*Async Shell Command*'.
2977 That buffer is in shell mode.
2979 You can configure `async-shell-command-buffer' to specify what to do in
2980 case when `*Async Shell Command*' buffer is already taken by another
2981 running shell command. To run COMMAND without displaying the output
2982 in a window you can configure `display-buffer-alist' to use the action
2983 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
2985 In Elisp, you will often be better served by calling `start-process'
2986 directly, since it offers more control and does not impose the use of a
2987 shell (with its need to quote arguments)."
2990 (read-shell-command "Async shell command: " nil nil
2994 ((eq major-mode
'dired-mode
)
2995 (dired-get-filename nil t
)))))
2996 (and filename
(file-relative-name filename
))))
2998 shell-command-default-error-buffer
))
2999 (unless (string-match "&[ \t]*\\'" command
)
3000 (setq command
(concat command
" &")))
3001 (shell-command command output-buffer error-buffer
))
3003 (defun shell-command (command &optional output-buffer error-buffer
)
3004 "Execute string COMMAND in inferior shell; display output, if any.
3005 With prefix argument, insert the COMMAND's output at point.
3007 If COMMAND ends in `&', execute it asynchronously.
3008 The output appears in the buffer `*Async Shell Command*'.
3009 That buffer is in shell mode. You can also use
3010 `async-shell-command' that automatically adds `&'.
3012 Otherwise, COMMAND is executed synchronously. The output appears in
3013 the buffer `*Shell Command Output*'. If the output is short enough to
3014 display in the echo area (which is determined by the variables
3015 `resize-mini-windows' and `max-mini-window-height'), it is shown
3016 there, but it is nonetheless available in buffer `*Shell Command
3017 Output*' even though that buffer is not automatically displayed.
3019 To specify a coding system for converting non-ASCII characters
3020 in the shell command output, use \\[universal-coding-system-argument] \
3021 before this command.
3023 Noninteractive callers can specify coding systems by binding
3024 `coding-system-for-read' and `coding-system-for-write'.
3026 The optional second argument OUTPUT-BUFFER, if non-nil,
3027 says to put the output in some other buffer.
3028 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
3029 If OUTPUT-BUFFER is not a buffer and not nil,
3030 insert output in current buffer. (This cannot be done asynchronously.)
3031 In either case, the buffer is first erased, and the output is
3032 inserted after point (leaving mark after it).
3034 If the command terminates without error, but generates output,
3035 and you did not specify \"insert it in the current buffer\",
3036 the output can be displayed in the echo area or in its buffer.
3037 If the output is short enough to display in the echo area
3038 \(determined by the variable `max-mini-window-height' if
3039 `resize-mini-windows' is non-nil), it is shown there.
3040 Otherwise,the buffer containing the output is displayed.
3042 If there is output and an error, and you did not specify \"insert it
3043 in the current buffer\", a message about the error goes at the end
3046 If there is no output, or if output is inserted in the current buffer,
3047 then `*Shell Command Output*' is deleted.
3049 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3050 or buffer name to which to direct the command's standard error output.
3051 If it is nil, error output is mingled with regular output.
3052 In an interactive call, the variable `shell-command-default-error-buffer'
3053 specifies the value of ERROR-BUFFER.
3055 In Elisp, you will often be better served by calling `call-process' or
3056 `start-process' directly, since it offers more control and does not impose
3057 the use of a shell (with its need to quote arguments)."
3061 (read-shell-command "Shell command: " nil nil
3065 ((eq major-mode
'dired-mode
)
3066 (dired-get-filename nil t
)))))
3067 (and filename
(file-relative-name filename
))))
3069 shell-command-default-error-buffer
))
3070 ;; Look for a handler in case default-directory is a remote file name.
3072 (find-file-name-handler (directory-file-name default-directory
)
3075 (funcall handler
'shell-command command output-buffer error-buffer
)
3076 (if (and output-buffer
3077 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
3078 ;; Output goes in current buffer.
3082 (expand-file-name "scor"
3083 (or small-temporary-file-directory
3084 temporary-file-directory
)))
3086 (barf-if-buffer-read-only)
3088 ;; We do not use -f for csh; we will not support broken use of
3089 ;; .cshrcs. Even the BSD csh manual says to use
3090 ;; "if ($?prompt) exit" before things which are not useful
3091 ;; non-interactively. Besides, if someone wants their other
3092 ;; aliases for shell commands then they can still have them.
3093 (call-process shell-file-name nil
3097 nil shell-command-switch command
)
3098 (when (and error-file
(file-exists-p error-file
))
3099 (if (< 0 (nth 7 (file-attributes error-file
)))
3100 (with-current-buffer (get-buffer-create error-buffer
)
3101 (let ((pos-from-end (- (point-max) (point))))
3104 ;; Do no formatting while reading error file,
3105 ;; because that can run a shell command, and we
3106 ;; don't want that to cause an infinite recursion.
3107 (format-insert-file error-file nil
)
3108 ;; Put point after the inserted errors.
3109 (goto-char (- (point-max) pos-from-end
)))
3110 (display-buffer (current-buffer))))
3111 (delete-file error-file
))
3112 ;; This is like exchange-point-and-mark, but doesn't
3113 ;; activate the mark. It is cleaner to avoid activation,
3114 ;; even though the command loop would deactivate the mark
3115 ;; because we inserted text.
3116 (goto-char (prog1 (mark t
)
3117 (set-marker (mark-marker) (point)
3118 (current-buffer)))))
3119 ;; Output goes in a separate buffer.
3120 ;; Preserve the match data in case called from a program.
3122 (if (string-match "[ \t]*&[ \t]*\\'" command
)
3123 ;; Command ending with ampersand means asynchronous.
3124 (let ((buffer (get-buffer-create
3125 (or output-buffer
"*Async Shell Command*")))
3126 (directory default-directory
)
3128 ;; Remove the ampersand.
3129 (setq command
(substring command
0 (match-beginning 0)))
3130 ;; Ask the user what to do with already running process.
3131 (setq proc
(get-buffer-process buffer
))
3134 ((eq async-shell-command-buffer
'confirm-kill-process
)
3135 ;; If will kill a process, query first.
3136 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3138 (error "Shell command in progress")))
3139 ((eq async-shell-command-buffer
'confirm-new-buffer
)
3140 ;; If will create a new buffer, query first.
3141 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3142 (setq buffer
(generate-new-buffer
3143 (or (and (bufferp output-buffer
) (buffer-name output-buffer
))
3144 output-buffer
"*Async Shell Command*")))
3145 (error "Shell command in progress")))
3146 ((eq async-shell-command-buffer
'new-buffer
)
3147 ;; It will create a new buffer.
3148 (setq buffer
(generate-new-buffer
3149 (or (and (bufferp output-buffer
) (buffer-name output-buffer
))
3150 output-buffer
"*Async Shell Command*"))))
3151 ((eq async-shell-command-buffer
'confirm-rename-buffer
)
3152 ;; If will rename the buffer, query first.
3153 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3155 (with-current-buffer buffer
3157 (setq buffer
(get-buffer-create
3158 (or output-buffer
"*Async Shell Command*"))))
3159 (error "Shell command in progress")))
3160 ((eq async-shell-command-buffer
'rename-buffer
)
3161 ;; It will rename the buffer.
3162 (with-current-buffer buffer
3164 (setq buffer
(get-buffer-create
3165 (or output-buffer
"*Async Shell Command*"))))))
3166 (with-current-buffer buffer
3167 (setq buffer-read-only nil
)
3168 ;; Setting buffer-read-only to nil doesn't suffice
3169 ;; if some text has a non-nil read-only property,
3170 ;; which comint sometimes adds for prompts.
3171 (let ((inhibit-read-only t
))
3173 (display-buffer buffer
'(nil (allow-no-window . t
)))
3174 (setq default-directory directory
)
3175 (setq proc
(start-process "Shell" buffer shell-file-name
3176 shell-command-switch command
))
3177 (setq mode-line-process
'(":%s"))
3178 (require 'shell
) (shell-mode)
3179 (set-process-sentinel proc
'shell-command-sentinel
)
3180 ;; Use the comint filter for proper handling of carriage motion
3181 ;; (see `comint-inhibit-carriage-motion'),.
3182 (set-process-filter proc
'comint-output-filter
)
3184 ;; Otherwise, command is executed synchronously.
3185 (shell-command-on-region (point) (point) command
3186 output-buffer nil error-buffer
)))))))
3188 (defun display-message-or-buffer (message
3189 &optional buffer-name not-this-window frame
)
3190 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3191 MESSAGE may be either a string or a buffer.
3193 A buffer is displayed using `display-buffer' if MESSAGE is too long for
3194 the maximum height of the echo area, as defined by `max-mini-window-height'
3195 if `resize-mini-windows' is non-nil.
3197 Returns either the string shown in the echo area, or when a pop-up
3198 buffer is used, the window used to display it.
3200 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3201 name of the buffer used to display it in the case where a pop-up buffer
3202 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3203 string and it is displayed in the echo area, it is not specified whether
3204 the contents are inserted into the buffer anyway.
3206 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
3207 and only used if a buffer is displayed."
3208 (cond ((and (stringp message
) (not (string-match "\n" message
)))
3209 ;; Trivial case where we can use the echo area
3210 (message "%s" message
))
3211 ((and (stringp message
)
3212 (= (string-match "\n" message
) (1- (length message
))))
3213 ;; Trivial case where we can just remove single trailing newline
3214 (message "%s" (substring message
0 (1- (length message
)))))
3217 (with-current-buffer
3218 (if (bufferp message
)
3220 (get-buffer-create (or buffer-name
"*Message*")))
3222 (unless (bufferp message
)
3227 (if (= (buffer-size) 0)
3229 (count-screen-lines nil nil nil
(minibuffer-window)))))
3231 ((and (or (<= lines
1)
3233 (if resize-mini-windows
3234 (cond ((floatp max-mini-window-height
)
3236 max-mini-window-height
))
3237 ((integerp max-mini-window-height
)
3238 max-mini-window-height
)
3242 ;; Don't use the echo area if the output buffer is
3243 ;; already displayed in the selected frame.
3244 (not (get-buffer-window (current-buffer))))
3246 (goto-char (point-max))
3249 (message "%s" (buffer-substring (point-min) (point))))
3252 (goto-char (point-min))
3253 (display-buffer (current-buffer)
3254 not-this-window frame
))))))))
3257 ;; We have a sentinel to prevent insertion of a termination message
3258 ;; in the buffer itself.
3259 (defun shell-command-sentinel (process signal
)
3260 (if (memq (process-status process
) '(exit signal
))
3262 (car (cdr (cdr (process-command process
))))
3263 (substring signal
0 -
1))))
3265 (defun shell-command-on-region (start end command
3266 &optional output-buffer replace
3267 error-buffer display-error-buffer
)
3268 "Execute string COMMAND in inferior shell with region as input.
3269 Normally display output (if any) in temp buffer `*Shell Command Output*';
3270 Prefix arg means replace the region with it. Return the exit code of
3273 To specify a coding system for converting non-ASCII characters
3274 in the input and output to the shell command, use \\[universal-coding-system-argument]
3275 before this command. By default, the input (from the current buffer)
3276 is encoded using coding-system specified by `process-coding-system-alist',
3277 falling back to `default-process-coding-system' if no match for COMMAND
3278 is found in `process-coding-system-alist'.
3280 Noninteractive callers can specify coding systems by binding
3281 `coding-system-for-read' and `coding-system-for-write'.
3283 If the command generates output, the output may be displayed
3284 in the echo area or in a buffer.
3285 If the output is short enough to display in the echo area
3286 \(determined by the variable `max-mini-window-height' if
3287 `resize-mini-windows' is non-nil), it is shown there.
3288 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3289 The output is available in that buffer in both cases.
3291 If there is output and an error, a message about the error
3292 appears at the end of the output. If there is no output, or if
3293 output is inserted in the current buffer, the buffer `*Shell
3294 Command Output*' is deleted.
3296 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3297 command's output. If the value is a buffer or buffer name,
3298 put the output there. If the value is nil, use the buffer
3299 `*Shell Command Output*'. Any other value, excluding nil,
3300 means to insert the output in the current buffer. In either case,
3301 the output is inserted after point (leaving mark after it).
3303 Optional fifth arg REPLACE, if non-nil, means to insert the
3304 output in place of text from START to END, putting point and mark
3307 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3308 or buffer name to which to direct the command's standard error
3309 output. If nil, error output is mingled with regular output.
3310 When called interactively, `shell-command-default-error-buffer'
3311 is used for ERROR-BUFFER.
3313 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3314 display the error buffer if there were any errors. When called
3315 interactively, this is t."
3316 (interactive (let (string)
3318 (user-error "The mark is not set now, so there is no region"))
3319 ;; Do this before calling region-beginning
3320 ;; and region-end, in case subprocess output
3321 ;; relocates them while we are in the minibuffer.
3322 (setq string
(read-shell-command "Shell command on region: "))
3323 ;; call-interactively recognizes region-beginning and
3324 ;; region-end specially, leaving them in the history.
3325 (list (region-beginning) (region-end)
3329 shell-command-default-error-buffer
3334 (expand-file-name "scor"
3335 (or small-temporary-file-directory
3336 temporary-file-directory
)))
3341 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
3342 ;; Replace specified region with output from command.
3343 (let ((swap (and replace
(< start end
))))
3344 ;; Don't muck with mark unless REPLACE says we should.
3346 (and replace
(push-mark (point) 'nomsg
))
3348 (call-process-region start end shell-file-name replace
3352 nil shell-command-switch command
))
3353 ;; It is rude to delete a buffer which the command is not using.
3354 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3355 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3356 ;; (kill-buffer shell-buffer)))
3357 ;; Don't muck with mark unless REPLACE says we should.
3358 (and replace swap
(exchange-point-and-mark)))
3359 ;; No prefix argument: put the output in a temp buffer,
3360 ;; replacing its entire contents.
3361 (let ((buffer (get-buffer-create
3362 (or output-buffer
"*Shell Command Output*"))))
3364 (if (eq buffer
(current-buffer))
3365 ;; If the input is the same buffer as the output,
3366 ;; delete everything but the specified region,
3367 ;; then replace that region with the output.
3368 (progn (setq buffer-read-only nil
)
3369 (delete-region (max start end
) (point-max))
3370 (delete-region (point-min) (min start end
))
3372 (call-process-region (point-min) (point-max)
3377 nil shell-command-switch
3379 ;; Clear the output buffer, then run the command with
3381 (let ((directory default-directory
))
3382 (with-current-buffer buffer
3383 (setq buffer-read-only nil
)
3384 (if (not output-buffer
)
3385 (setq default-directory directory
))
3388 (call-process-region start end shell-file-name nil
3390 (list buffer error-file
)
3392 nil shell-command-switch command
)))
3393 ;; Report the output.
3394 (with-current-buffer buffer
3395 (setq mode-line-process
3396 (cond ((null exit-status
)
3398 ((stringp exit-status
)
3399 (format " - Signal [%s]" exit-status
))
3400 ((not (equal 0 exit-status
))
3401 (format " - Exit [%d]" exit-status
)))))
3402 (if (with-current-buffer buffer
(> (point-max) (point-min)))
3403 ;; There's some output, display it
3404 (display-message-or-buffer buffer
)
3405 ;; No output; error?
3408 (< 0 (nth 7 (file-attributes error-file
))))
3409 (format "some error output%s"
3410 (if shell-command-default-error-buffer
3411 (format " to the \"%s\" buffer"
3412 shell-command-default-error-buffer
)
3415 (cond ((null exit-status
)
3416 (message "(Shell command failed with error)"))
3417 ((equal 0 exit-status
)
3418 (message "(Shell command succeeded with %s)"
3420 ((stringp exit-status
)
3421 (message "(Shell command killed by signal %s)"
3424 (message "(Shell command failed with code %d and %s)"
3425 exit-status output
))))
3426 ;; Don't kill: there might be useful info in the undo-log.
3427 ;; (kill-buffer buffer)
3430 (when (and error-file
(file-exists-p error-file
))
3431 (if (< 0 (nth 7 (file-attributes error-file
)))
3432 (with-current-buffer (get-buffer-create error-buffer
)
3433 (let ((pos-from-end (- (point-max) (point))))
3436 ;; Do no formatting while reading error file,
3437 ;; because that can run a shell command, and we
3438 ;; don't want that to cause an infinite recursion.
3439 (format-insert-file error-file nil
)
3440 ;; Put point after the inserted errors.
3441 (goto-char (- (point-max) pos-from-end
)))
3442 (and display-error-buffer
3443 (display-buffer (current-buffer)))))
3444 (delete-file error-file
))
3447 (defun shell-command-to-string (command)
3448 "Execute shell command COMMAND and return its output as a string."
3449 (with-output-to-string
3450 (with-current-buffer
3452 (process-file shell-file-name nil t nil shell-command-switch command
))))
3454 (defun process-file (program &optional infile buffer display
&rest args
)
3455 "Process files synchronously in a separate process.
3456 Similar to `call-process', but may invoke a file handler based on
3457 `default-directory'. The current working directory of the
3458 subprocess is `default-directory'.
3460 File names in INFILE and BUFFER are handled normally, but file
3461 names in ARGS should be relative to `default-directory', as they
3462 are passed to the process verbatim. (This is a difference to
3463 `call-process' which does not support file handlers for INFILE
3466 Some file handlers might not support all variants, for example
3467 they might behave as if DISPLAY was nil, regardless of the actual
3469 (let ((fh (find-file-name-handler default-directory
'process-file
))
3472 (if fh
(apply fh
'process-file program infile buffer display args
)
3473 (when infile
(setq lc
(file-local-copy infile
)))
3474 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
3475 (make-temp-file "emacs")))
3477 (apply 'call-process program
3479 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
3481 (when stderr-file
(copy-file stderr-file
(cadr buffer
) t
))))
3482 (when stderr-file
(delete-file stderr-file
))
3483 (when lc
(delete-file lc
)))))
3485 (defvar process-file-side-effects t
3486 "Whether a call of `process-file' changes remote files.
3488 By default, this variable is always set to t, meaning that a
3489 call of `process-file' could potentially change any file on a
3490 remote host. When set to nil, a file handler could optimize
3491 its behavior with respect to remote file attribute caching.
3493 You should only ever change this variable with a let-binding;
3494 never with `setq'.")
3496 (defun start-file-process (name buffer program
&rest program-args
)
3497 "Start a program in a subprocess. Return the process object for it.
3499 Similar to `start-process', but may invoke a file handler based on
3500 `default-directory'. See Info node `(elisp)Magic File Names'.
3502 This handler ought to run PROGRAM, perhaps on the local host,
3503 perhaps on a remote host that corresponds to `default-directory'.
3504 In the latter case, the local part of `default-directory' becomes
3505 the working directory of the process.
3507 PROGRAM and PROGRAM-ARGS might be file names. They are not
3508 objects of file handler invocation. File handlers might not
3509 support pty association, if PROGRAM is nil."
3510 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
3511 (if fh
(apply fh
'start-file-process name buffer program program-args
)
3512 (apply 'start-process name buffer program program-args
))))
3516 (defvar tabulated-list-format
)
3517 (defvar tabulated-list-entries
)
3518 (defvar tabulated-list-sort-key
)
3519 (declare-function tabulated-list-init-header
"tabulated-list" ())
3520 (declare-function tabulated-list-print
"tabulated-list"
3521 (&optional remember-pos update
))
3523 (defvar process-menu-query-only nil
)
3525 (defvar process-menu-mode-map
3526 (let ((map (make-sparse-keymap)))
3527 (define-key map
[?d
] 'process-menu-delete-process
)
3530 (define-derived-mode process-menu-mode tabulated-list-mode
"Process Menu"
3531 "Major mode for listing the processes called by Emacs."
3532 (setq tabulated-list-format
[("Process" 15 t
)
3537 (make-local-variable 'process-menu-query-only
)
3538 (setq tabulated-list-sort-key
(cons "Process" nil
))
3539 (add-hook 'tabulated-list-revert-hook
'list-processes--refresh nil t
)
3540 (tabulated-list-init-header))
3542 (defun process-menu-delete-process ()
3543 "Kill process at point in a `list-processes' buffer."
3545 (delete-process (tabulated-list-get-id))
3548 (defun list-processes--refresh ()
3549 "Recompute the list of processes for the Process List buffer.
3550 Also, delete any process that is exited or signaled."
3551 (setq tabulated-list-entries nil
)
3552 (dolist (p (process-list))
3553 (cond ((memq (process-status p
) '(exit signal closed
))
3555 ((or (not process-menu-query-only
)
3556 (process-query-on-exit-flag p
))
3557 (let* ((buf (process-buffer p
))
3558 (type (process-type p
))
3559 (name (process-name p
))
3560 (status (symbol-name (process-status p
)))
3561 (buf-label (if (buffer-live-p buf
)
3562 `(,(buffer-name buf
)
3564 help-echo
,(concat "Visit buffer `"
3565 (buffer-name buf
) "'")
3568 action process-menu-visit-buffer
)
3570 (tty (or (process-tty-name p
) "--"))
3572 (if (memq type
'(network serial
))
3573 (let ((contact (process-contact p t
)))
3574 (if (eq type
'network
)
3576 (if (plist-get contact
:type
)
3579 (if (plist-get contact
:server
)
3580 (format "server on %s"
3582 (plist-get contact
:host
)
3583 (plist-get contact
:local
)))
3584 (format "connection to %s"
3585 (plist-get contact
:host
))))
3586 (format "(serial port %s%s)"
3587 (or (plist-get contact
:port
) "?")
3588 (let ((speed (plist-get contact
:speed
)))
3590 (format " at %s b/s" speed
)
3592 (mapconcat 'identity
(process-command p
) " "))))
3593 (push (list p
(vector name status buf-label tty cmd
))
3594 tabulated-list-entries
))))))
3596 (defun process-menu-visit-buffer (button)
3597 (display-buffer (button-get button
'process-buffer
)))
3599 (defun list-processes (&optional query-only buffer
)
3600 "Display a list of all processes that are Emacs sub-processes.
3601 If optional argument QUERY-ONLY is non-nil, only processes with
3602 the query-on-exit flag set are listed.
3603 Any process listed as exited or signaled is actually eliminated
3604 after the listing is made.
3605 Optional argument BUFFER specifies a buffer to use, instead of
3607 The return value is always nil.
3609 This function lists only processes that were launched by Emacs. To
3610 see other processes running on the system, use `list-system-processes'."
3612 (or (fboundp 'process-list
)
3613 (error "Asynchronous subprocesses are not supported on this system"))
3614 (unless (bufferp buffer
)
3615 (setq buffer
(get-buffer-create "*Process List*")))
3616 (with-current-buffer buffer
3618 (setq process-menu-query-only query-only
)
3619 (list-processes--refresh)
3620 (tabulated-list-print))
3621 (display-buffer buffer
)
3624 (defvar universal-argument-map
3625 (let ((map (make-sparse-keymap))
3626 (universal-argument-minus
3627 ;; For backward compatibility, minus with no modifiers is an ordinary
3628 ;; command if digits have already been entered.
3629 `(menu-item "" negative-argument
3630 :filter
,(lambda (cmd)
3631 (if (integerp prefix-arg
) nil cmd
)))))
3632 (define-key map
[switch-frame
]
3633 (lambda (e) (interactive "e")
3634 (handle-switch-frame e
) (universal-argument--mode)))
3635 (define-key map
[?\C-u
] 'universal-argument-more
)
3636 (define-key map
[?-
] universal-argument-minus
)
3637 (define-key map
[?
0] 'digit-argument
)
3638 (define-key map
[?
1] 'digit-argument
)
3639 (define-key map
[?
2] 'digit-argument
)
3640 (define-key map
[?
3] 'digit-argument
)
3641 (define-key map
[?
4] 'digit-argument
)
3642 (define-key map
[?
5] 'digit-argument
)
3643 (define-key map
[?
6] 'digit-argument
)
3644 (define-key map
[?
7] 'digit-argument
)
3645 (define-key map
[?
8] 'digit-argument
)
3646 (define-key map
[?
9] 'digit-argument
)
3647 (define-key map
[kp-0
] 'digit-argument
)
3648 (define-key map
[kp-1
] 'digit-argument
)
3649 (define-key map
[kp-2
] 'digit-argument
)
3650 (define-key map
[kp-3
] 'digit-argument
)
3651 (define-key map
[kp-4
] 'digit-argument
)
3652 (define-key map
[kp-5
] 'digit-argument
)
3653 (define-key map
[kp-6
] 'digit-argument
)
3654 (define-key map
[kp-7
] 'digit-argument
)
3655 (define-key map
[kp-8
] 'digit-argument
)
3656 (define-key map
[kp-9
] 'digit-argument
)
3657 (define-key map
[kp-subtract
] universal-argument-minus
)
3659 "Keymap used while processing \\[universal-argument].")
3661 (defun universal-argument--mode ()
3662 (set-transient-map universal-argument-map
))
3664 (defun universal-argument ()
3665 "Begin a numeric argument for the following command.
3666 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3667 \\[universal-argument] following the digits or minus sign ends the argument.
3668 \\[universal-argument] without digits or minus sign provides 4 as argument.
3669 Repeating \\[universal-argument] without digits or minus sign
3670 multiplies the argument by 4 each time.
3671 For some commands, just \\[universal-argument] by itself serves as a flag
3672 which is different in effect from any particular numeric argument.
3673 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3675 (setq prefix-arg
(list 4))
3676 (universal-argument--mode))
3678 (defun universal-argument-more (arg)
3679 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3680 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3682 (setq prefix-arg
(if (consp arg
)
3683 (list (* 4 (car arg
)))
3687 (when (consp prefix-arg
) (universal-argument--mode)))
3689 (defun negative-argument (arg)
3690 "Begin a negative numeric argument for the next command.
3691 \\[universal-argument] following digits or minus sign ends the argument."
3693 (setq prefix-arg
(cond ((integerp arg
) (- arg
))
3696 (universal-argument--mode))
3698 (defun digit-argument (arg)
3699 "Part of the numeric argument for the next command.
3700 \\[universal-argument] following digits or minus sign ends the argument."
3702 (let* ((char (if (integerp last-command-event
)
3704 (get last-command-event
'ascii-character
)))
3705 (digit (- (logand char ?
\177) ?
0)))
3706 (setq prefix-arg
(cond ((integerp arg
)
3708 (if (< arg
0) (- digit
) digit
)))
3710 ;; Treat -0 as just -, so that -01 will work.
3711 (if (zerop digit
) '-
(- digit
)))
3714 (universal-argument--mode))
3717 (defvar filter-buffer-substring-functions nil
3718 "This variable is a wrapper hook around `buffer-substring--filter'.")
3719 (make-obsolete-variable 'filter-buffer-substring-functions
3720 'filter-buffer-substring-function
"24.4")
3722 (defvar filter-buffer-substring-function
#'buffer-substring--filter
3723 "Function to perform the filtering in `filter-buffer-substring'.
3724 The function is called with the same 3 arguments (BEG END DELETE)
3725 that `filter-buffer-substring' received. It should return the
3726 buffer substring between BEG and END, after filtering. If DELETE is
3727 non-nil, it should delete the text between BEG and END from the buffer.")
3729 (defvar buffer-substring-filters nil
3730 "List of filter functions for `buffer-substring--filter'.
3731 Each function must accept a single argument, a string, and return a string.
3732 The buffer substring is passed to the first function in the list,
3733 and the return value of each function is passed to the next.
3734 As a special convention, point is set to the start of the buffer text
3735 being operated on (i.e., the first argument of `buffer-substring--filter')
3736 before these functions are called.")
3737 (make-obsolete-variable 'buffer-substring-filters
3738 'filter-buffer-substring-function
"24.1")
3740 (defun filter-buffer-substring (beg end
&optional delete
)
3741 "Return the buffer substring between BEG and END, after filtering.
3742 If DELETE is non-nil, delete the text between BEG and END from the buffer.
3744 This calls the function that `filter-buffer-substring-function' specifies
3745 \(passing the same three arguments that it received) to do the work,
3746 and returns whatever it does. The default function does no filtering,
3747 unless a hook has been set.
3749 Use `filter-buffer-substring' instead of `buffer-substring',
3750 `buffer-substring-no-properties', or `delete-and-extract-region' when
3751 you want to allow filtering to take place. For example, major or minor
3752 modes can use `filter-buffer-substring-function' to extract characters
3753 that are special to a buffer, and should not be copied into other buffers."
3754 (funcall filter-buffer-substring-function beg end delete
))
3756 (defun buffer-substring--filter (beg end
&optional delete
)
3757 "Default function to use for `filter-buffer-substring-function'.
3758 Its arguments and return value are as specified for `filter-buffer-substring'.
3759 This respects the wrapper hook `filter-buffer-substring-functions',
3760 and the abnormal hook `buffer-substring-filters'.
3761 No filtering is done unless a hook says to."
3762 (with-wrapper-hook filter-buffer-substring-functions
(beg end delete
)
3764 ((or delete buffer-substring-filters
)
3767 (let ((string (if delete
(delete-and-extract-region beg end
)
3768 (buffer-substring beg end
))))
3769 (dolist (filter buffer-substring-filters
)
3770 (setq string
(funcall filter string
)))
3773 (buffer-substring beg end
)))))
3776 ;;;; Window system cut and paste hooks.
3778 (defvar interprogram-cut-function
#'gui-select-text
3779 "Function to call to make a killed region available to other programs.
3780 Most window systems provide a facility for cutting and pasting
3781 text between different programs, such as the clipboard on X and
3782 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3784 This variable holds a function that Emacs calls whenever text is
3785 put in the kill ring, to make the new kill available to other
3786 programs. The function takes one argument, TEXT, which is a
3787 string containing the text which should be made available.")
3789 (defvar interprogram-paste-function
#'gui-selection-value
3790 "Function to call to get text cut from other programs.
3791 Most window systems provide a facility for cutting and pasting
3792 text between different programs, such as the clipboard on X and
3793 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3795 This variable holds a function that Emacs calls to obtain text
3796 that other programs have provided for pasting. The function is
3797 called with no arguments. If no other program has provided text
3798 to paste, the function should return nil (in which case the
3799 caller, usually `current-kill', should use the top of the Emacs
3800 kill ring). If another program has provided text to paste, the
3801 function should return that text as a string (in which case the
3802 caller should put this string in the kill ring as the latest
3805 The function may also return a list of strings if the window
3806 system supports multiple selections. The first string will be
3807 used as the pasted text, but the other will be placed in the kill
3808 ring for easy access via `yank-pop'.
3810 Note that the function should return a string only if a program
3811 other than Emacs has provided a string for pasting; if Emacs
3812 provided the most recent string, the function should return nil.
3813 If it is difficult to tell whether Emacs or some other program
3814 provided the current string, it is probably good enough to return
3815 nil if the string is equal (according to `string=') to the last
3816 text Emacs provided.")
3820 ;;;; The kill ring data structure.
3822 (defvar kill-ring nil
3823 "List of killed text sequences.
3824 Since the kill ring is supposed to interact nicely with cut-and-paste
3825 facilities offered by window systems, use of this variable should
3826 interact nicely with `interprogram-cut-function' and
3827 `interprogram-paste-function'. The functions `kill-new',
3828 `kill-append', and `current-kill' are supposed to implement this
3829 interaction; you may want to use them instead of manipulating the kill
3832 (defcustom kill-ring-max
60
3833 "Maximum length of kill ring before oldest elements are thrown away."
3837 (defvar kill-ring-yank-pointer nil
3838 "The tail of the kill ring whose car is the last thing yanked.")
3840 (defcustom save-interprogram-paste-before-kill nil
3841 "Save clipboard strings into kill ring before replacing them.
3842 When one selects something in another program to paste it into Emacs,
3843 but kills something in Emacs before actually pasting it,
3844 this selection is gone unless this variable is non-nil,
3845 in which case the other program's selection is saved in the `kill-ring'
3846 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3851 (defcustom kill-do-not-save-duplicates nil
3852 "Do not add a new string to `kill-ring' if it duplicates the last one.
3853 The comparison is done using `equal-including-properties'."
3858 (defun kill-new (string &optional replace
)
3859 "Make STRING the latest kill in the kill ring.
3860 Set `kill-ring-yank-pointer' to point to it.
3861 If `interprogram-cut-function' is non-nil, apply it to STRING.
3862 Optional second argument REPLACE non-nil means that STRING will replace
3863 the front of the kill ring, rather than being added to the list.
3865 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3866 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3869 When the yank handler has a non-nil PARAM element, the original STRING
3870 argument is not used by `insert-for-yank'. However, since Lisp code
3871 may access and use elements from the kill ring directly, the STRING
3872 argument should still be a \"useful\" string for such uses."
3873 (unless (and kill-do-not-save-duplicates
3874 ;; Due to text properties such as 'yank-handler that
3875 ;; can alter the contents to yank, comparison using
3876 ;; `equal' is unsafe.
3877 (equal-including-properties string
(car kill-ring
)))
3878 (if (fboundp 'menu-bar-update-yank-menu
)
3879 (menu-bar-update-yank-menu string
(and replace
(car kill-ring
)))))
3880 (when save-interprogram-paste-before-kill
3881 (let ((interprogram-paste (and interprogram-paste-function
3882 (funcall interprogram-paste-function
))))
3883 (when interprogram-paste
3884 (dolist (s (if (listp interprogram-paste
)
3885 (nreverse interprogram-paste
)
3886 (list interprogram-paste
)))
3887 (unless (and kill-do-not-save-duplicates
3888 (equal-including-properties s
(car kill-ring
)))
3889 (push s kill-ring
))))))
3890 (unless (and kill-do-not-save-duplicates
3891 (equal-including-properties string
(car kill-ring
)))
3892 (if (and replace kill-ring
)
3893 (setcar kill-ring string
)
3894 (push string kill-ring
)
3895 (if (> (length kill-ring
) kill-ring-max
)
3896 (setcdr (nthcdr (1- kill-ring-max
) kill-ring
) nil
))))
3897 (setq kill-ring-yank-pointer kill-ring
)
3898 (if interprogram-cut-function
3899 (funcall interprogram-cut-function string
)))
3901 ;; It has been argued that this should work similar to `self-insert-command'
3902 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
3903 (defcustom kill-append-merge-undo nil
3904 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
3909 (defun kill-append (string before-p
)
3910 "Append STRING to the end of the latest kill in the kill ring.
3911 If BEFORE-P is non-nil, prepend STRING to the kill.
3912 Also removes the last undo boundary in the current buffer,
3913 depending on `kill-append-merge-undo'.
3914 If `interprogram-cut-function' is set, pass the resulting kill to it."
3915 (let* ((cur (car kill-ring
)))
3916 (kill-new (if before-p
(concat string cur
) (concat cur string
))
3917 (or (= (length cur
) 0)
3918 (equal nil
(get-text-property 0 'yank-handler cur
))))
3919 (when (and kill-append-merge-undo
(not buffer-read-only
))
3920 (let ((prev buffer-undo-list
)
3921 (next (cdr buffer-undo-list
)))
3922 ;; find the next undo boundary
3926 ;; remove this undo boundary
3928 (setcdr prev
(cdr next
)))))))
3930 (defcustom yank-pop-change-selection nil
3931 "Whether rotating the kill ring changes the window system selection.
3932 If non-nil, whenever the kill ring is rotated (usually via the
3933 `yank-pop' command), Emacs also calls `interprogram-cut-function'
3934 to copy the new kill to the window system selection."
3939 (defun current-kill (n &optional do-not-move
)
3940 "Rotate the yanking point by N places, and then return that kill.
3941 If N is zero and `interprogram-paste-function' is set to a
3942 function that returns a string or a list of strings, and if that
3943 function doesn't return nil, then that string (or list) is added
3944 to the front of the kill ring and the string (or first string in
3945 the list) is returned as the latest kill.
3947 If N is not zero, and if `yank-pop-change-selection' is
3948 non-nil, use `interprogram-cut-function' to transfer the
3949 kill at the new yank point into the window system selection.
3951 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3952 move the yanking point; just return the Nth kill forward."
3954 (let ((interprogram-paste (and (= n
0)
3955 interprogram-paste-function
3956 (funcall interprogram-paste-function
))))
3957 (if interprogram-paste
3959 ;; Disable the interprogram cut function when we add the new
3960 ;; text to the kill ring, so Emacs doesn't try to own the
3961 ;; selection, with identical text.
3962 (let ((interprogram-cut-function nil
))
3963 (if (listp interprogram-paste
)
3964 (mapc 'kill-new
(nreverse interprogram-paste
))
3965 (kill-new interprogram-paste
)))
3967 (or kill-ring
(error "Kill ring is empty"))
3968 (let ((ARGth-kill-element
3969 (nthcdr (mod (- n
(length kill-ring-yank-pointer
))
3973 (setq kill-ring-yank-pointer ARGth-kill-element
)
3974 (when (and yank-pop-change-selection
3976 interprogram-cut-function
)
3977 (funcall interprogram-cut-function
(car ARGth-kill-element
))))
3978 (car ARGth-kill-element
)))))
3982 ;;;; Commands for manipulating the kill ring.
3984 (defcustom kill-read-only-ok nil
3985 "Non-nil means don't signal an error for killing read-only text."
3989 (defun kill-region (beg end
&optional region
)
3990 "Kill (\"cut\") text between point and mark.
3991 This deletes the text from the buffer and saves it in the kill ring.
3992 The command \\[yank] can retrieve it from there.
3993 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3995 If you want to append the killed region to the last killed text,
3996 use \\[append-next-kill] before \\[kill-region].
3998 If the buffer is read-only, Emacs will beep and refrain from deleting
3999 the text, but put the text in the kill ring anyway. This means that
4000 you can use the killing commands to copy text from a read-only buffer.
4002 Lisp programs should use this function for killing text.
4003 (To delete text, use `delete-region'.)
4004 Supply two arguments, character positions indicating the stretch of text
4006 Any command that calls this function is a \"kill command\".
4007 If the previous command was also a kill command,
4008 the text killed this time appends to the text killed last time
4009 to make one entry in the kill ring.
4011 The optional argument REGION if non-nil, indicates that we're not just killing
4012 some text between BEG and END, but we're killing the region."
4013 ;; Pass mark first, then point, because the order matters when
4014 ;; calling `kill-append'.
4015 (interactive (list (mark) (point) 'region
))
4016 (unless (and beg end
)
4017 (user-error "The mark is not set now, so there is no region"))
4019 (let ((string (if region
4020 (funcall region-extract-function
'delete
)
4021 (filter-buffer-substring beg end
'delete
))))
4022 (when string
;STRING is nil if BEG = END
4023 ;; Add that string to the kill ring, one way or another.
4024 (if (eq last-command
'kill-region
)
4025 (kill-append string
(< end beg
))
4027 (when (or string
(eq last-command
'kill-region
))
4028 (setq this-command
'kill-region
))
4029 (setq deactivate-mark t
)
4031 ((buffer-read-only text-read-only
)
4032 ;; The code above failed because the buffer, or some of the characters
4033 ;; in the region, are read-only.
4034 ;; We should beep, in case the user just isn't aware of this.
4035 ;; However, there's no harm in putting
4036 ;; the region's text in the kill ring, anyway.
4037 (copy-region-as-kill beg end region
)
4038 ;; Set this-command now, so it will be set even if we get an error.
4039 (setq this-command
'kill-region
)
4040 ;; This should barf, if appropriate, and give us the correct error.
4041 (if kill-read-only-ok
4042 (progn (message "Read only text copied to kill ring") nil
)
4043 ;; Signal an error if the buffer is read-only.
4044 (barf-if-buffer-read-only)
4045 ;; If the buffer isn't read-only, the text is.
4046 (signal 'text-read-only
(list (current-buffer)))))))
4048 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4049 ;; to get two copies of the text when the user accidentally types M-w and
4050 ;; then corrects it with the intended C-w.
4051 (defun copy-region-as-kill (beg end
&optional region
)
4052 "Save the region as if killed, but don't kill it.
4053 In Transient Mark mode, deactivate the mark.
4054 If `interprogram-cut-function' is non-nil, also save the text for a window
4055 system cut and paste.
4057 The optional argument REGION if non-nil, indicates that we're not just copying
4058 some text between BEG and END, but we're copying the region.
4060 This command's old key binding has been given to `kill-ring-save'."
4061 ;; Pass mark first, then point, because the order matters when
4062 ;; calling `kill-append'.
4063 (interactive (list (mark) (point)
4064 (prefix-numeric-value current-prefix-arg
)))
4065 (let ((str (if region
4066 (funcall region-extract-function nil
)
4067 (filter-buffer-substring beg end
))))
4068 (if (eq last-command
'kill-region
)
4069 (kill-append str
(< end beg
))
4071 (setq deactivate-mark t
)
4074 (defun kill-ring-save (beg end
&optional region
)
4075 "Save the region as if killed, but don't kill it.
4076 In Transient Mark mode, deactivate the mark.
4077 If `interprogram-cut-function' is non-nil, also save the text for a window
4078 system cut and paste.
4080 If you want to append the killed line to the last killed text,
4081 use \\[append-next-kill] before \\[kill-ring-save].
4083 The optional argument REGION if non-nil, indicates that we're not just copying
4084 some text between BEG and END, but we're copying the region.
4086 This command is similar to `copy-region-as-kill', except that it gives
4087 visual feedback indicating the extent of the region being copied."
4088 ;; Pass mark first, then point, because the order matters when
4089 ;; calling `kill-append'.
4090 (interactive (list (mark) (point)
4091 (prefix-numeric-value current-prefix-arg
)))
4092 (copy-region-as-kill beg end region
)
4093 ;; This use of called-interactively-p is correct because the code it
4094 ;; controls just gives the user visual feedback.
4095 (if (called-interactively-p 'interactive
)
4096 (indicate-copied-region)))
4098 (defun indicate-copied-region (&optional message-len
)
4099 "Indicate that the region text has been copied interactively.
4100 If the mark is visible in the selected window, blink the cursor
4101 between point and mark if there is currently no active region
4104 If the mark lies outside the selected window, display an
4105 informative message containing a sample of the copied text. The
4106 optional argument MESSAGE-LEN, if non-nil, specifies the length
4107 of this sample text; it defaults to 40."
4108 (let ((mark (mark t
))
4110 ;; Inhibit quitting so we can make a quit here
4111 ;; look like a C-g typed as a command.
4113 (if (pos-visible-in-window-p mark
(selected-window))
4114 ;; Swap point-and-mark quickly so as to show the region that
4115 ;; was selected. Don't do it if the region is highlighted.
4116 (unless (and (region-active-p)
4117 (face-background 'region
))
4118 ;; Swap point and mark.
4119 (set-marker (mark-marker) (point) (current-buffer))
4121 (sit-for blink-matching-delay
)
4123 (set-marker (mark-marker) mark
(current-buffer))
4125 ;; If user quit, deactivate the mark
4126 ;; as C-g would as a command.
4127 (and quit-flag
(region-active-p)
4129 (let ((len (min (abs (- mark point
))
4130 (or message-len
40))))
4132 ;; Don't say "killed"; that is misleading.
4133 (message "Saved text until \"%s\""
4134 (buffer-substring-no-properties (- mark len
) mark
))
4135 (message "Saved text from \"%s\""
4136 (buffer-substring-no-properties mark
(+ mark len
))))))))
4138 (defun append-next-kill (&optional interactive
)
4139 "Cause following command, if it kills, to add to previous kill.
4140 If the next command kills forward from point, the kill is
4141 appended to the previous killed text. If the command kills
4142 backward, the kill is prepended. Kill commands that act on the
4143 region, such as `kill-region', are regarded as killing forward if
4144 point is after mark, and killing backward if point is before
4147 If the next command is not a kill command, `append-next-kill' has
4150 The argument is used for internal purposes; do not supply one."
4152 ;; We don't use (interactive-p), since that breaks kbd macros.
4155 (setq this-command
'kill-region
)
4156 (message "If the next command is a kill, it will append"))
4157 (setq last-command
'kill-region
)))
4159 (defvar bidi-directional-controls-chars
"\x202a-\x202e\x2066-\x2069"
4160 "Character set that matches bidirectional formatting control characters.")
4162 (defvar bidi-directional-non-controls-chars
"^\x202a-\x202e\x2066-\x2069"
4163 "Character set that matches any character except bidirectional controls.")
4165 (defun squeeze-bidi-context-1 (from to category replacement
)
4166 "A subroutine of `squeeze-bidi-context'.
4167 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4168 (let ((pt (copy-marker from
))
4169 (limit (copy-marker to
))
4178 ;; L and R categories include embedding and
4179 ;; override controls, but we don't want to
4180 ;; replace them, because that might change
4181 ;; the visual order. Likewise with PDF and
4182 ;; isolate controls.
4183 (+ pt
(skip-chars-forward
4184 bidi-directional-non-controls-chars
4186 ;; Replace any run of non-RTL characters by a single LRM.
4187 (if (null (re-search-forward category lim1 t
))
4188 ;; No more characters of CATEGORY, we are done.
4190 (replace-match replacement nil t
)
4191 (move-marker pt
(point)))
4193 ;; Skip directional controls, if any.
4195 pt
(+ pt
(skip-chars-forward bidi-directional-controls-chars limit
))))))
4197 (defun squeeze-bidi-context (from to
)
4198 "Replace characters between FROM and TO while keeping bidi context.
4200 This function replaces the region of text with as few characters
4201 as possible, while preserving the effect that region will have on
4202 bidirectional display before and after the region."
4203 (let ((start (set-marker (make-marker)
4204 (if (> from
0) from
(+ (point-max) from
))))
4205 (end (set-marker (make-marker) to
))
4206 ;; This is for when they copy text with read-only text
4208 (inhibit-read-only t
))
4209 (if (null (marker-position end
))
4210 (setq end
(point-max-marker)))
4211 ;; Replace each run of non-RTL characters with a single LRM.
4212 (squeeze-bidi-context-1 start end
"\\CR+" "\x200e")
4213 ;; Replace each run of non-LTR characters with a single RLM. Note
4214 ;; that the \cR category includes both the Arabic Letter (AL) and
4215 ;; R characters; here we ignore the distinction between them,
4216 ;; because that distinction only affects Arabic Number (AN)
4217 ;; characters, which are weak and don't affect the reordering.
4218 (squeeze-bidi-context-1 start end
"\\CL+" "\x200f")))
4220 (defun line-substring-with-bidi-context (start end
&optional no-properties
)
4221 "Return buffer text between START and END with its bidi context.
4223 START and END are assumed to belong to the same physical line
4224 of buffer text. This function prepends and appends to the text
4225 between START and END bidi control characters that preserve the
4226 visual order of that text when it is inserted at some other place."
4227 (if (or (< start
(point-min))
4228 (> end
(point-max)))
4229 (signal 'args-out-of-range
(list (current-buffer) start end
)))
4230 (let ((buf (current-buffer))
4231 substr para-dir from to
)
4234 (setq para-dir
(current-bidi-paragraph-direction))
4235 (setq from
(line-beginning-position)
4236 to
(line-end-position))
4238 ;; If we don't have any mixed directional characters in the
4239 ;; entire line, we can just copy the substring without adding
4241 (if (or (looking-at-p "\\CR*$")
4242 (looking-at-p "\\CL*$"))
4243 (setq substr
(if no-properties
4244 (buffer-substring-no-properties start end
)
4245 (buffer-substring start end
)))
4249 (insert-buffer-substring-no-properties buf from to
)
4250 (insert-buffer-substring buf from to
))
4251 (squeeze-bidi-context 1 (1+ (- start from
)))
4252 (squeeze-bidi-context (- end to
) nil
)
4253 (buffer-substring 1 (point-max)))))
4255 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4256 ;; (1) force the string to have the same base embedding
4257 ;; direction as the paragraph direction at the source, no matter
4258 ;; what is the paragraph direction at destination; and (2) avoid
4259 ;; affecting the visual order of the surrounding text at
4260 ;; destination if there are characters of different
4261 ;; directionality there.
4262 (concat (if (eq para-dir
'left-to-right
) "\x2066" "\x2067")
4265 (defun buffer-substring-with-bidi-context (start end
&optional no-properties
)
4266 "Return portion of current buffer between START and END with bidi context.
4268 This function works similar to `buffer-substring', but it prepends and
4269 appends to the text bidi directional control characters necessary to
4270 preserve the visual appearance of the text if it is inserted at another
4271 place. This is useful when the buffer substring includes bidirectional
4272 text and control characters that cause non-trivial reordering on display.
4273 If copied verbatim, such text can have a very different visual appearance,
4274 and can also change the visual appearance of the surrounding text at the
4275 destination of the copy.
4277 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4278 the text properties."
4279 (let (line-end substr
)
4280 (if (or (< start
(point-min))
4281 (> end
(point-max)))
4282 (signal 'args-out-of-range
(list (current-buffer) start end
)))
4285 (setq line-end
(min end
(line-end-position)))
4286 (while (< start end
)
4290 (line-substring-with-bidi-context start line-end
4293 (setq start
(point))
4294 (setq line-end
(min end
(line-end-position))))
4299 (defcustom yank-handled-properties
4300 '((font-lock-face . yank-handle-font-lock-face-property
)
4301 (category . yank-handle-category-property
))
4302 "List of special text property handling conditions for yanking.
4303 Each element should have the form (PROP . FUN), where PROP is a
4304 property symbol and FUN is a function. When the `yank' command
4305 inserts text into the buffer, it scans the inserted text for
4306 stretches of text that have `eq' values of the text property
4307 PROP; for each such stretch of text, FUN is called with three
4308 arguments: the property's value in that text, and the start and
4309 end positions of the text.
4311 This is done prior to removing the properties specified by
4312 `yank-excluded-properties'."
4314 :type
'(repeat (cons (symbol :tag
"property symbol")
4318 ;; This is actually used in subr.el but defcustom does not work there.
4319 (defcustom yank-excluded-properties
4320 '(category field follow-link fontified font-lock-face help-echo
4321 intangible invisible keymap local-map mouse-face read-only
4323 "Text properties to discard when yanking.
4324 The value should be a list of text properties to discard or t,
4325 which means to discard all text properties.
4327 See also `yank-handled-properties'."
4328 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
4332 (defvar yank-window-start nil
)
4333 (defvar yank-undo-function nil
4334 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4335 Function is called with two parameters, START and END corresponding to
4336 the value of the mark and point; it is guaranteed that START <= END.
4337 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4339 (defun yank-pop (&optional arg
)
4340 "Replace just-yanked stretch of killed text with a different stretch.
4341 This command is allowed only immediately after a `yank' or a `yank-pop'.
4342 At such a time, the region contains a stretch of reinserted
4343 previously-killed text. `yank-pop' deletes that text and inserts in its
4344 place a different stretch of killed text.
4346 With no argument, the previous kill is inserted.
4347 With argument N, insert the Nth previous kill.
4348 If N is negative, this is a more recent kill.
4350 The sequence of kills wraps around, so that after the oldest one
4351 comes the newest one.
4353 When this command inserts killed text into the buffer, it honors
4354 `yank-excluded-properties' and `yank-handler' as described in the
4355 doc string for `insert-for-yank-1', which see."
4357 (if (not (eq last-command
'yank
))
4358 (user-error "Previous command was not a yank"))
4359 (setq this-command
'yank
)
4360 (unless arg
(setq arg
1))
4361 (let ((inhibit-read-only t
)
4362 (before (< (point) (mark t
))))
4364 (funcall (or yank-undo-function
'delete-region
) (point) (mark t
))
4365 (funcall (or yank-undo-function
'delete-region
) (mark t
) (point)))
4366 (setq yank-undo-function nil
)
4367 (set-marker (mark-marker) (point) (current-buffer))
4368 (insert-for-yank (current-kill arg
))
4369 ;; Set the window start back where it was in the yank command,
4371 (set-window-start (selected-window) yank-window-start t
)
4373 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4374 ;; It is cleaner to avoid activation, even though the command
4375 ;; loop would deactivate the mark because we inserted text.
4376 (goto-char (prog1 (mark t
)
4377 (set-marker (mark-marker) (point) (current-buffer))))))
4380 (defun yank (&optional arg
)
4381 "Reinsert (\"paste\") the last stretch of killed text.
4382 More precisely, reinsert the most recent kill, which is the
4383 stretch of killed text most recently killed OR yanked. Put point
4384 at the end, and set mark at the beginning without activating it.
4385 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4386 With argument N, reinsert the Nth most recent kill.
4388 When this command inserts text into the buffer, it honors the
4389 `yank-handled-properties' and `yank-excluded-properties'
4390 variables, and the `yank-handler' text property. See
4391 `insert-for-yank-1' for details.
4393 See also the command `yank-pop' (\\[yank-pop])."
4395 (setq yank-window-start
(window-start))
4396 ;; If we don't get all the way thru, make last-command indicate that
4397 ;; for the following command.
4398 (setq this-command t
)
4400 (insert-for-yank (current-kill (cond
4405 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4406 ;; It is cleaner to avoid activation, even though the command
4407 ;; loop would deactivate the mark because we inserted text.
4408 (goto-char (prog1 (mark t
)
4409 (set-marker (mark-marker) (point) (current-buffer)))))
4410 ;; If we do get all the way thru, make this-command indicate that.
4411 (if (eq this-command t
)
4412 (setq this-command
'yank
))
4415 (defun rotate-yank-pointer (arg)
4416 "Rotate the yanking point in the kill ring.
4417 With ARG, rotate that many kills forward (or backward, if negative)."
4421 ;; Some kill commands.
4423 ;; Internal subroutine of delete-char
4424 (defun kill-forward-chars (arg)
4425 (if (listp arg
) (setq arg
(car arg
)))
4426 (if (eq arg
'-
) (setq arg -
1))
4427 (kill-region (point) (+ (point) arg
)))
4429 ;; Internal subroutine of backward-delete-char
4430 (defun kill-backward-chars (arg)
4431 (if (listp arg
) (setq arg
(car arg
)))
4432 (if (eq arg
'-
) (setq arg -
1))
4433 (kill-region (point) (- (point) arg
)))
4435 (defcustom backward-delete-char-untabify-method
'untabify
4436 "The method for untabifying when deleting backward.
4437 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4438 `hungry' -- delete all whitespace, both tabs and spaces;
4439 `all' -- delete all whitespace, including tabs, spaces and newlines;
4440 nil -- just delete one character."
4441 :type
'(choice (const untabify
) (const hungry
) (const all
) (const nil
))
4445 (defun backward-delete-char-untabify (arg &optional killp
)
4446 "Delete characters backward, changing tabs into spaces.
4447 The exact behavior depends on `backward-delete-char-untabify-method'.
4448 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4449 Interactively, ARG is the prefix arg (default 1)
4450 and KILLP is t if a prefix arg was specified."
4451 (interactive "*p\nP")
4452 (when (eq backward-delete-char-untabify-method
'untabify
)
4455 (while (and (> count
0) (not (bobp)))
4456 (if (= (preceding-char) ?
\t)
4457 (let ((col (current-column)))
4459 (setq col
(- col
(current-column)))
4460 (insert-char ?\s col
)
4463 (setq count
(1- count
))))))
4464 (let* ((skip (cond ((eq backward-delete-char-untabify-method
'hungry
) " \t")
4465 ((eq backward-delete-char-untabify-method
'all
)
4468 (let* ((oldpt (point))
4469 (wh (- oldpt
(save-excursion
4470 (skip-chars-backward skip
)
4471 (constrain-to-field nil oldpt
)))))
4472 (+ arg
(if (zerop wh
) 0 (1- wh
))))
4474 ;; Avoid warning about delete-backward-char
4475 (with-no-warnings (delete-backward-char n killp
))))
4477 (defun zap-to-char (arg char
)
4478 "Kill up to and including ARGth occurrence of CHAR.
4479 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4480 Goes backward if ARG is negative; error if CHAR not found."
4481 (interactive (list (prefix-numeric-value current-prefix-arg
)
4482 (read-char "Zap to char: " t
)))
4483 ;; Avoid "obsolete" warnings for translation-table-for-input.
4485 (if (char-table-p translation-table-for-input
)
4486 (setq char
(or (aref translation-table-for-input char
) char
))))
4487 (kill-region (point) (progn
4488 (search-forward (char-to-string char
) nil nil arg
)
4491 ;; kill-line and its subroutines.
4493 (defcustom kill-whole-line nil
4494 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4498 (defun kill-line (&optional arg
)
4499 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4500 With prefix argument ARG, kill that many lines from point.
4501 Negative arguments kill lines backward.
4502 With zero argument, kills the text before point on the current line.
4504 When calling from a program, nil means \"no arg\",
4505 a number counts as a prefix arg.
4507 To kill a whole line, when point is not at the beginning, type \
4508 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4510 If `show-trailing-whitespace' is non-nil, this command will just
4511 kill the rest of the current line, even if there are only
4514 If option `kill-whole-line' is non-nil, then this command kills the whole line
4515 including its terminating newline, when used at the beginning of a line
4516 with no argument. As a consequence, you can always kill a whole line
4517 by typing \\[move-beginning-of-line] \\[kill-line].
4519 If you want to append the killed line to the last killed text,
4520 use \\[append-next-kill] before \\[kill-line].
4522 If the buffer is read-only, Emacs will beep and refrain from deleting
4523 the line, but put the line in the kill ring anyway. This means that
4524 you can use this command to copy text from a read-only buffer.
4525 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4528 (kill-region (point)
4529 ;; It is better to move point to the other end of the kill
4530 ;; before killing. That way, in a read-only buffer, point
4531 ;; moves across the text that is copied to the kill ring.
4532 ;; The choice has no effect on undo now that undo records
4533 ;; the value of point from before the command was run.
4536 (forward-visible-line (prefix-numeric-value arg
))
4538 (signal 'end-of-buffer nil
))
4541 (end-of-visible-line) (point))))
4542 (if (or (save-excursion
4543 ;; If trailing whitespace is visible,
4544 ;; don't treat it as nothing.
4545 (unless show-trailing-whitespace
4546 (skip-chars-forward " \t" end
))
4548 (and kill-whole-line
(bolp)))
4549 (forward-visible-line 1)
4553 (defun kill-whole-line (&optional arg
)
4555 With prefix ARG, kill that many lines starting from the current line.
4556 If ARG is negative, kill backward. Also kill the preceding newline.
4557 \(This is meant to make \\[repeat] work well with negative arguments.)
4558 If ARG is zero, kill current line but exclude the trailing newline."
4560 (or arg
(setq arg
1))
4561 (if (and (> arg
0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4562 (signal 'end-of-buffer nil
))
4563 (if (and (< arg
0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4564 (signal 'beginning-of-buffer nil
))
4565 (unless (eq last-command
'kill-region
)
4567 (setq last-command
'kill-region
))
4569 ;; We need to kill in two steps, because the previous command
4570 ;; could have been a kill command, in which case the text
4571 ;; before point needs to be prepended to the current kill
4572 ;; ring entry and the text after point appended. Also, we
4573 ;; need to use save-excursion to avoid copying the same text
4574 ;; twice to the kill ring in read-only buffers.
4576 (kill-region (point) (progn (forward-visible-line 0) (point))))
4577 (kill-region (point) (progn (end-of-visible-line) (point))))
4580 (kill-region (point) (progn (end-of-visible-line) (point))))
4581 (kill-region (point)
4582 (progn (forward-visible-line (1+ arg
))
4583 (unless (bobp) (backward-char))
4587 (kill-region (point) (progn (forward-visible-line 0) (point))))
4588 (kill-region (point)
4589 (progn (forward-visible-line arg
) (point))))))
4591 (defun forward-visible-line (arg)
4592 "Move forward by ARG lines, ignoring currently invisible newlines only.
4593 If ARG is negative, move backward -ARG lines.
4594 If ARG is zero, move to the beginning of the current line."
4599 (or (zerop (forward-line 1))
4600 (signal 'end-of-buffer nil
))
4601 ;; If the newline we just skipped is invisible,
4604 (get-char-property (1- (point)) 'invisible
)))
4605 (if (if (eq buffer-invisibility-spec t
)
4607 (or (memq prop buffer-invisibility-spec
)
4608 (assq prop buffer-invisibility-spec
)))
4609 (setq arg
(1+ arg
))))
4610 (setq arg
(1- arg
)))
4611 ;; If invisible text follows, and it is a number of complete lines,
4613 (let ((opoint (point)))
4614 (while (and (not (eobp))
4616 (get-char-property (point) 'invisible
)))
4617 (if (eq buffer-invisibility-spec t
)
4619 (or (memq prop buffer-invisibility-spec
)
4620 (assq prop buffer-invisibility-spec
)))))
4622 (if (get-text-property (point) 'invisible
)
4623 (or (next-single-property-change (point) 'invisible
)
4625 (next-overlay-change (point)))))
4627 (goto-char opoint
))))
4629 (while (or first
(<= arg
0))
4632 (or (zerop (forward-line -
1))
4633 (signal 'beginning-of-buffer nil
)))
4634 ;; If the newline we just moved to is invisible,
4638 (get-char-property (1- (point)) 'invisible
)))
4639 (unless (if (eq buffer-invisibility-spec t
)
4641 (or (memq prop buffer-invisibility-spec
)
4642 (assq prop buffer-invisibility-spec
)))
4643 (setq arg
(1+ arg
)))))
4645 ;; If invisible text follows, and it is a number of complete lines,
4647 (let ((opoint (point)))
4648 (while (and (not (bobp))
4650 (get-char-property (1- (point)) 'invisible
)))
4651 (if (eq buffer-invisibility-spec t
)
4653 (or (memq prop buffer-invisibility-spec
)
4654 (assq prop buffer-invisibility-spec
)))))
4656 (if (get-text-property (1- (point)) 'invisible
)
4657 (or (previous-single-property-change (point) 'invisible
)
4659 (previous-overlay-change (point)))))
4661 (goto-char opoint
)))))
4662 ((beginning-of-buffer end-of-buffer
)
4665 (defun end-of-visible-line ()
4666 "Move to end of current visible line."
4668 ;; If the following character is currently invisible,
4669 ;; skip all characters with that same `invisible' property value,
4670 ;; then find the next newline.
4671 (while (and (not (eobp))
4673 (skip-chars-forward "^\n")
4675 (get-char-property (point) 'invisible
)))
4676 (if (eq buffer-invisibility-spec t
)
4678 (or (memq prop buffer-invisibility-spec
)
4679 (assq prop buffer-invisibility-spec
))))))
4680 (skip-chars-forward "^\n")
4681 (if (get-text-property (point) 'invisible
)
4682 (goto-char (or (next-single-property-change (point) 'invisible
)
4684 (goto-char (next-overlay-change (point))))
4687 (defun insert-buffer (buffer)
4688 "Insert after point the contents of BUFFER.
4689 Puts mark after the inserted text.
4690 BUFFER may be a buffer or a buffer name."
4691 (declare (interactive-only insert-buffer-substring
))
4695 (barf-if-buffer-read-only)
4696 (read-buffer "Insert buffer: "
4697 (if (eq (selected-window) (next-window))
4698 (other-buffer (current-buffer))
4699 (window-buffer (next-window)))
4703 (insert-buffer-substring (get-buffer buffer
))
4707 (defun append-to-buffer (buffer start end
)
4708 "Append to specified buffer the text of the region.
4709 It is inserted into that buffer before its point.
4711 When calling from a program, give three arguments:
4712 BUFFER (or buffer name), START and END.
4713 START and END specify the portion of the current buffer to be copied."
4715 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t
))
4716 (region-beginning) (region-end)))
4717 (let* ((oldbuf (current-buffer))
4718 (append-to (get-buffer-create buffer
))
4719 (windows (get-buffer-window-list append-to t t
))
4722 (with-current-buffer append-to
4723 (setq point
(point))
4724 (barf-if-buffer-read-only)
4725 (insert-buffer-substring oldbuf start end
)
4726 (dolist (window windows
)
4727 (when (= (window-point window
) point
)
4728 (set-window-point window
(point))))))))
4730 (defun prepend-to-buffer (buffer start end
)
4731 "Prepend to specified buffer the text of the region.
4732 It is inserted into that buffer after its point.
4734 When calling from a program, give three arguments:
4735 BUFFER (or buffer name), START and END.
4736 START and END specify the portion of the current buffer to be copied."
4737 (interactive "BPrepend to buffer: \nr")
4738 (let ((oldbuf (current-buffer)))
4739 (with-current-buffer (get-buffer-create buffer
)
4740 (barf-if-buffer-read-only)
4742 (insert-buffer-substring oldbuf start end
)))))
4744 (defun copy-to-buffer (buffer start end
)
4745 "Copy to specified buffer the text of the region.
4746 It is inserted into that buffer, replacing existing text there.
4748 When calling from a program, give three arguments:
4749 BUFFER (or buffer name), START and END.
4750 START and END specify the portion of the current buffer to be copied."
4751 (interactive "BCopy to buffer: \nr")
4752 (let ((oldbuf (current-buffer)))
4753 (with-current-buffer (get-buffer-create buffer
)
4754 (barf-if-buffer-read-only)
4757 (insert-buffer-substring oldbuf start end
)))))
4759 (define-error 'mark-inactive
(purecopy "The mark is not active now"))
4761 (defvar activate-mark-hook nil
4762 "Hook run when the mark becomes active.
4763 It is also run at the end of a command, if the mark is active and
4764 it is possible that the region may have changed.")
4766 (defvar deactivate-mark-hook nil
4767 "Hook run when the mark becomes inactive.")
4769 (defun mark (&optional force
)
4770 "Return this buffer's mark value as integer, or nil if never set.
4772 In Transient Mark mode, this function signals an error if
4773 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
4774 or the argument FORCE is non-nil, it disregards whether the mark
4775 is active, and returns an integer or nil in the usual way.
4777 If you are using this in an editing command, you are most likely making
4778 a mistake; see the documentation of `set-mark'."
4779 (if (or force
(not transient-mark-mode
) mark-active mark-even-if-inactive
)
4780 (marker-position (mark-marker))
4781 (signal 'mark-inactive nil
)))
4783 ;; Behind display-selections-p.
4785 (defun deactivate-mark (&optional force
)
4786 "Deactivate the mark.
4787 If Transient Mark mode is disabled, this function normally does
4788 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
4790 Deactivating the mark sets `mark-active' to nil, updates the
4791 primary selection according to `select-active-regions', and runs
4792 `deactivate-mark-hook'.
4794 If Transient Mark mode was temporarily enabled, reset the value
4795 of the variable `transient-mark-mode'; if this causes Transient
4796 Mark mode to be disabled, don't change `mark-active' to nil or
4797 run `deactivate-mark-hook'."
4798 (when (or (region-active-p) force
)
4799 (when (and (if (eq select-active-regions
'only
)
4800 (eq (car-safe transient-mark-mode
) 'only
)
4801 select-active-regions
)
4803 (display-selections-p))
4804 ;; The var `saved-region-selection', if non-nil, is the text in
4805 ;; the region prior to the last command modifying the buffer.
4806 ;; Set the selection to that, or to the current region.
4807 (cond (saved-region-selection
4808 (if (gui-backend-selection-owner-p 'PRIMARY
)
4809 (gui-set-selection 'PRIMARY saved-region-selection
))
4810 (setq saved-region-selection nil
))
4811 ;; If another program has acquired the selection, region
4812 ;; deactivation should not clobber it (Bug#11772).
4813 ((and (/= (region-beginning) (region-end))
4814 (or (gui-backend-selection-owner-p 'PRIMARY
)
4815 (null (gui-backend-selection-exists-p 'PRIMARY
))))
4816 (gui-set-selection 'PRIMARY
4817 (funcall region-extract-function nil
)))))
4818 (when mark-active
(force-mode-line-update)) ;Refresh toolbar (bug#16382).
4820 ((eq (car-safe transient-mark-mode
) 'only
)
4821 (setq transient-mark-mode
(cdr transient-mark-mode
))
4822 (if (eq transient-mark-mode
(default-value 'transient-mark-mode
))
4823 (kill-local-variable 'transient-mark-mode
)))
4824 ((eq transient-mark-mode
'lambda
)
4825 (kill-local-variable 'transient-mark-mode
)))
4826 (setq mark-active nil
)
4827 (run-hooks 'deactivate-mark-hook
)
4828 (redisplay--update-region-highlight (selected-window))))
4830 (defun activate-mark (&optional no-tmm
)
4832 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
4834 (unless (region-active-p)
4835 (force-mode-line-update) ;Refresh toolbar (bug#16382).
4836 (setq mark-active t
)
4837 (unless (or transient-mark-mode no-tmm
)
4838 (setq-local transient-mark-mode
'lambda
))
4839 (run-hooks 'activate-mark-hook
))))
4841 (defun set-mark (pos)
4842 "Set this buffer's mark to POS. Don't use this function!
4843 That is to say, don't use this function unless you want
4844 the user to see that the mark has moved, and you want the previous
4845 mark position to be lost.
4847 Normally, when a new mark is set, the old one should go on the stack.
4848 This is why most applications should use `push-mark', not `set-mark'.
4850 Novice Emacs Lisp programmers often try to use the mark for the wrong
4851 purposes. The mark saves a location for the user's convenience.
4852 Most editing commands should not alter the mark.
4853 To remember a location for internal use in the Lisp program,
4854 store it in a Lisp variable. Example:
4856 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
4859 (set-marker (mark-marker) pos
(current-buffer))
4860 (activate-mark 'no-tmm
))
4861 ;; Normally we never clear mark-active except in Transient Mark mode.
4862 ;; But when we actually clear out the mark value too, we must
4863 ;; clear mark-active in any mode.
4865 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
4866 ;; it should never be nil if the mark is nil.
4867 (setq mark-active nil
)
4868 (set-marker (mark-marker) nil
)))
4870 (defun save-mark-and-excursion--save ()
4872 (let ((mark (mark-marker)))
4873 (and (marker-position mark
) (copy-marker mark
)))
4876 (defun save-mark-and-excursion--restore (saved-mark-info)
4877 (let ((saved-mark (car saved-mark-info
))
4878 (omark (marker-position (mark-marker)))
4880 (saved-mark-active (cdr saved-mark-info
)))
4882 (if (null saved-mark
)
4883 (set-marker (mark-marker) nil
)
4884 (setf nmark
(marker-position saved-mark
))
4885 (set-marker (mark-marker) nmark
)
4886 (set-marker saved-mark nil
))
4888 (let ((cur-mark-active mark-active
))
4889 (setq mark-active saved-mark-active
)
4890 ;; If mark is active now, and either was not active or was at a
4891 ;; different place, run the activate hook.
4892 (if saved-mark-active
4893 (when (or (not cur-mark-active
)
4894 (not (eq omark nmark
)))
4895 (run-hooks 'activate-mark-hook
))
4896 ;; If mark has ceased to be active, run deactivate hook.
4897 (when cur-mark-active
4898 (run-hooks 'deactivate-mark-hook
))))))
4900 (defmacro save-mark-and-excursion
(&rest body
)
4901 "Like `save-excursion', but also save and restore the mark state.
4902 This macro does what `save-excursion' did before Emacs 25.1."
4903 (let ((saved-marker-sym (make-symbol "saved-marker")))
4904 `(let ((,saved-marker-sym
(save-mark-and-excursion--save)))
4906 (save-excursion ,@body
)
4907 (save-mark-and-excursion--restore ,saved-marker-sym
)))))
4909 (defcustom use-empty-active-region nil
4910 "Whether \"region-aware\" commands should act on empty regions.
4911 If nil, region-aware commands treat empty regions as inactive.
4912 If non-nil, region-aware commands treat the region as active as
4913 long as the mark is active, even if the region is empty.
4915 Region-aware commands are those that act on the region if it is
4916 active and Transient Mark mode is enabled, and on the text near
4920 :group
'editing-basics
)
4922 (defun use-region-p ()
4923 "Return t if the region is active and it is appropriate to act on it.
4924 This is used by commands that act specially on the region under
4925 Transient Mark mode.
4927 The return value is t if Transient Mark mode is enabled and the
4928 mark is active; furthermore, if `use-empty-active-region' is nil,
4929 the region must not be empty. Otherwise, the return value is nil.
4931 For some commands, it may be appropriate to ignore the value of
4932 `use-empty-active-region'; in that case, use `region-active-p'."
4933 (and (region-active-p)
4934 (or use-empty-active-region
(> (region-end) (region-beginning)))))
4936 (defun region-active-p ()
4937 "Return non-nil if Transient Mark mode is enabled and the mark is active.
4939 Some commands act specially on the region when Transient Mark
4940 mode is enabled. Usually, such commands should use
4941 `use-region-p' instead of this function, because `use-region-p'
4942 also checks the value of `use-empty-active-region'."
4943 (and transient-mark-mode mark-active
4944 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
4945 ;; without the mark being set (e.g. bug#17324). We really should fix
4946 ;; that problem, but in the mean time, let's make sure we don't say the
4947 ;; region is active when there's no mark.
4948 (progn (cl-assert (mark)) t
)))
4951 (defvar redisplay-unhighlight-region-function
4952 (lambda (rol) (when (overlayp rol
) (delete-overlay rol
))))
4954 (defvar redisplay-highlight-region-function
4955 (lambda (start end window rol
)
4956 (if (not (overlayp rol
))
4957 (let ((nrol (make-overlay start end
)))
4958 (funcall redisplay-unhighlight-region-function rol
)
4959 (overlay-put nrol
'window window
)
4960 (overlay-put nrol
'face
'region
)
4961 ;; Normal priority so that a large region doesn't hide all the
4962 ;; overlays within it, but high secondary priority so that if it
4963 ;; ends/starts in the middle of a small overlay, that small overlay
4964 ;; won't hide the region's boundaries.
4965 (overlay-put nrol
'priority
'(nil .
100))
4967 (unless (and (eq (overlay-buffer rol
) (current-buffer))
4968 (eq (overlay-start rol
) start
)
4969 (eq (overlay-end rol
) end
))
4970 (move-overlay rol start end
(current-buffer)))
4973 (defun redisplay--update-region-highlight (window)
4974 (let ((rol (window-parameter window
'internal-region-overlay
)))
4975 (if (not (and (region-active-p)
4976 (or highlight-nonselected-windows
4977 (eq window
(selected-window))
4978 (and (window-minibuffer-p)
4979 (eq window
(minibuffer-selected-window))))))
4980 (funcall redisplay-unhighlight-region-function rol
)
4981 (let* ((pt (window-point window
))
4983 (start (min pt mark
))
4986 (funcall redisplay-highlight-region-function
4987 start end window rol
)))
4988 (unless (equal new rol
)
4989 (set-window-parameter window
'internal-region-overlay
4992 (defvar pre-redisplay-functions
(list #'redisplay--update-region-highlight
)
4993 "Hook run just before redisplay.
4994 It is called in each window that is to be redisplayed. It takes one argument,
4995 which is the window that will be redisplayed. When run, the `current-buffer'
4996 is set to the buffer displayed in that window.")
4998 (defun redisplay--pre-redisplay-functions (windows)
4999 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5001 (with-current-buffer (window-buffer (selected-window))
5002 (run-hook-with-args 'pre-redisplay-functions
(selected-window)))
5003 (dolist (win (if (listp windows
) windows
(window-list-1 nil nil t
)))
5004 (with-current-buffer (window-buffer win
)
5005 (run-hook-with-args 'pre-redisplay-functions win
))))))
5007 (add-function :before pre-redisplay-function
5008 #'redisplay--pre-redisplay-functions
)
5011 (defvar-local mark-ring nil
5012 "The list of former marks of the current buffer, most recent first.")
5013 (put 'mark-ring
'permanent-local t
)
5015 (defcustom mark-ring-max
16
5016 "Maximum size of mark ring. Start discarding off end if gets this big."
5018 :group
'editing-basics
)
5020 (defvar global-mark-ring nil
5021 "The list of saved global marks, most recent first.")
5023 (defcustom global-mark-ring-max
16
5024 "Maximum size of global mark ring. \
5025 Start discarding off end if gets this big."
5027 :group
'editing-basics
)
5029 (defun pop-to-mark-command ()
5030 "Jump to mark, and pop a new position for mark off the ring.
5031 \(Does not affect global mark ring)."
5034 (user-error "No mark set in this buffer")
5035 (if (= (point) (mark t
))
5036 (message "Mark popped"))
5037 (goto-char (mark t
))
5040 (defun push-mark-command (arg &optional nomsg
)
5041 "Set mark at where point is.
5042 If no prefix ARG and mark is already set there, just activate it.
5043 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5045 (let ((mark (mark t
)))
5046 (if (or arg
(null mark
) (/= mark
(point)))
5047 (push-mark nil nomsg t
)
5048 (activate-mark 'no-tmm
)
5050 (message "Mark activated")))))
5052 (defcustom set-mark-command-repeat-pop nil
5053 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5054 That means that C-u \\[set-mark-command] \\[set-mark-command]
5055 will pop the mark twice, and
5056 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5057 will pop the mark three times.
5059 A value of nil means \\[set-mark-command]'s behavior does not change
5060 after C-u \\[set-mark-command]."
5062 :group
'editing-basics
)
5064 (defun set-mark-command (arg)
5065 "Set the mark where point is, or jump to the mark.
5066 Setting the mark also alters the region, which is the text
5067 between point and mark; this is the closest equivalent in
5068 Emacs to what some editors call the \"selection\".
5070 With no prefix argument, set the mark at point, and push the
5071 old mark position on local mark ring. Also push the old mark on
5072 global mark ring, if the previous mark was set in another buffer.
5074 When Transient Mark Mode is off, immediately repeating this
5075 command activates `transient-mark-mode' temporarily.
5077 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5078 jump to the mark, and set the mark from
5079 position popped off the local mark ring (this does not affect the global
5080 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5081 mark ring (see `pop-global-mark').
5083 If `set-mark-command-repeat-pop' is non-nil, repeating
5084 the \\[set-mark-command] command with no prefix argument pops the next position
5085 off the local (or global) mark ring and jumps there.
5087 With \\[universal-argument] \\[universal-argument] as prefix
5088 argument, unconditionally set mark where point is, even if
5089 `set-mark-command-repeat-pop' is non-nil.
5091 Novice Emacs Lisp programmers often try to use the mark for the wrong
5092 purposes. See the documentation of `set-mark' for more information."
5094 (cond ((eq transient-mark-mode
'lambda
)
5095 (kill-local-variable 'transient-mark-mode
))
5096 ((eq (car-safe transient-mark-mode
) 'only
)
5099 ((and (consp arg
) (> (prefix-numeric-value arg
) 4))
5100 (push-mark-command nil
))
5101 ((not (eq this-command
'set-mark-command
))
5103 (pop-to-mark-command)
5104 (push-mark-command t
)))
5105 ((and set-mark-command-repeat-pop
5106 (eq last-command
'pop-global-mark
)
5108 (setq this-command
'pop-global-mark
)
5110 ((or (and set-mark-command-repeat-pop
5111 (eq last-command
'pop-to-mark-command
))
5113 (setq this-command
'pop-to-mark-command
)
5114 (pop-to-mark-command))
5115 ((eq last-command
'set-mark-command
)
5116 (if (region-active-p)
5119 (message "Mark deactivated"))
5121 (message "Mark activated")))
5123 (push-mark-command nil
))))
5125 (defun push-mark (&optional location nomsg activate
)
5126 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5127 If the last global mark pushed was not in the current buffer,
5128 also push LOCATION on the global mark ring.
5129 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5131 Novice Emacs Lisp programmers often try to use the mark for the wrong
5132 purposes. See the documentation of `set-mark' for more information.
5134 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5135 (unless (null (mark t
))
5136 (setq mark-ring
(cons (copy-marker (mark-marker)) mark-ring
))
5137 (when (> (length mark-ring
) mark-ring-max
)
5138 (move-marker (car (nthcdr mark-ring-max mark-ring
)) nil
)
5139 (setcdr (nthcdr (1- mark-ring-max
) mark-ring
) nil
)))
5140 (set-marker (mark-marker) (or location
(point)) (current-buffer))
5141 ;; Now push the mark on the global mark ring.
5142 (if (and global-mark-ring
5143 (eq (marker-buffer (car global-mark-ring
)) (current-buffer)))
5144 ;; The last global mark pushed was in this same buffer.
5145 ;; Don't push another one.
5147 (setq global-mark-ring
(cons (copy-marker (mark-marker)) global-mark-ring
))
5148 (when (> (length global-mark-ring
) global-mark-ring-max
)
5149 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring
)) nil
)
5150 (setcdr (nthcdr (1- global-mark-ring-max
) global-mark-ring
) nil
)))
5151 (or nomsg executing-kbd-macro
(> (minibuffer-depth) 0)
5152 (message "Mark set"))
5153 (if (or activate
(not transient-mark-mode
))
5154 (set-mark (mark t
)))
5158 "Pop off mark ring into the buffer's actual mark.
5159 Does not set point. Does nothing if mark ring is empty."
5161 (setq mark-ring
(nconc mark-ring
(list (copy-marker (mark-marker)))))
5162 (set-marker (mark-marker) (+ 0 (car mark-ring
)) (current-buffer))
5163 (move-marker (car mark-ring
) nil
)
5164 (if (null (mark t
)) (ding))
5165 (setq mark-ring
(cdr mark-ring
)))
5168 (define-obsolete-function-alias
5169 'exchange-dot-and-mark
'exchange-point-and-mark
"23.3")
5170 (defun exchange-point-and-mark (&optional arg
)
5171 "Put the mark where point is now, and point where the mark is now.
5172 This command works even when the mark is not active,
5173 and it reactivates the mark.
5175 If Transient Mark mode is on, a prefix ARG deactivates the mark
5176 if it is active, and otherwise avoids reactivating it. If
5177 Transient Mark mode is off, a prefix ARG enables Transient Mark
5180 (let ((omark (mark t
))
5181 (temp-highlight (eq (car-safe transient-mark-mode
) 'only
)))
5183 (user-error "No mark set in this buffer"))
5186 (cond (temp-highlight
5187 (setq-local transient-mark-mode
(cons 'only transient-mark-mode
)))
5188 ((or (and arg
(region-active-p)) ; (xor arg (not (region-active-p)))
5189 (not (or arg
(region-active-p))))
5191 (t (activate-mark)))
5194 (defcustom shift-select-mode t
5195 "When non-nil, shifted motion keys activate the mark momentarily.
5197 While the mark is activated in this way, any shift-translated point
5198 motion key extends the region, and if Transient Mark mode was off, it
5199 is temporarily turned on. Furthermore, the mark will be deactivated
5200 by any subsequent point motion key that was not shift-translated, or
5201 by any action that normally deactivates the mark in Transient Mark mode.
5203 See `this-command-keys-shift-translated' for the meaning of
5206 :group
'editing-basics
)
5208 (defun handle-shift-selection ()
5209 "Activate/deactivate mark depending on invocation thru shift translation.
5210 This function is called by `call-interactively' when a command
5211 with a `^' character in its `interactive' spec is invoked, before
5212 running the command itself.
5214 If `shift-select-mode' is enabled and the command was invoked
5215 through shift translation, set the mark and activate the region
5216 temporarily, unless it was already set in this way. See
5217 `this-command-keys-shift-translated' for the meaning of shift
5220 Otherwise, if the region has been activated temporarily,
5221 deactivate it, and restore the variable `transient-mark-mode' to
5223 (cond ((and shift-select-mode this-command-keys-shift-translated
)
5224 (unless (and mark-active
5225 (eq (car-safe transient-mark-mode
) 'only
))
5226 (setq-local transient-mark-mode
5228 (unless (eq transient-mark-mode
'lambda
)
5229 transient-mark-mode
)))
5230 (push-mark nil nil t
)))
5231 ((eq (car-safe transient-mark-mode
) 'only
)
5232 (setq transient-mark-mode
(cdr transient-mark-mode
))
5233 (if (eq transient-mark-mode
(default-value 'transient-mark-mode
))
5234 (kill-local-variable 'transient-mark-mode
))
5235 (deactivate-mark))))
5237 (define-minor-mode transient-mark-mode
5238 "Toggle Transient Mark mode.
5239 With a prefix argument ARG, enable Transient Mark mode if ARG is
5240 positive, and disable it otherwise. If called from Lisp, enable
5241 Transient Mark mode if ARG is omitted or nil.
5243 Transient Mark mode is a global minor mode. When enabled, the
5244 region is highlighted with the `region' face whenever the mark
5245 is active. The mark is \"deactivated\" by changing the buffer,
5246 and after certain other operations that set the mark but whose
5247 main purpose is something else--for example, incremental search,
5248 \\[beginning-of-buffer], and \\[end-of-buffer].
5250 You can also deactivate the mark by typing \\[keyboard-quit] or
5251 \\[keyboard-escape-quit].
5253 Many commands change their behavior when Transient Mark mode is
5254 in effect and the mark is active, by acting on the region instead
5255 of their usual default part of the buffer's text. Examples of
5256 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5257 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5258 To see the documentation of commands which are sensitive to the
5259 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5260 or \"mark.*active\" at the prompt."
5262 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5263 :variable
(default-value 'transient-mark-mode
))
5265 (defvar widen-automatically t
5266 "Non-nil means it is ok for commands to call `widen' when they want to.
5267 Some commands will do this in order to go to positions outside
5268 the current accessible part of the buffer.
5270 If `widen-automatically' is nil, these commands will do something else
5271 as a fallback, and won't change the buffer bounds.")
5273 (defvar non-essential nil
5274 "Whether the currently executing code is performing an essential task.
5275 This variable should be non-nil only when running code which should not
5276 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5277 user for a password when we are simply scanning a set of files in the
5278 background or displaying possible completions before the user even asked
5281 (defun pop-global-mark ()
5282 "Pop off global mark ring and jump to the top location."
5284 ;; Pop entries which refer to non-existent buffers.
5285 (while (and global-mark-ring
(not (marker-buffer (car global-mark-ring
))))
5286 (setq global-mark-ring
(cdr global-mark-ring
)))
5287 (or global-mark-ring
5288 (error "No global mark set"))
5289 (let* ((marker (car global-mark-ring
))
5290 (buffer (marker-buffer marker
))
5291 (position (marker-position marker
)))
5292 (setq global-mark-ring
(nconc (cdr global-mark-ring
)
5293 (list (car global-mark-ring
))))
5295 (or (and (>= position
(point-min))
5296 (<= position
(point-max)))
5297 (if widen-automatically
5299 (error "Global mark position is outside accessible part of buffer")))
5300 (goto-char position
)
5301 (switch-to-buffer buffer
)))
5303 (defcustom next-line-add-newlines nil
5304 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5307 :group
'editing-basics
)
5309 (defun next-line (&optional arg try-vscroll
)
5310 "Move cursor vertically down ARG lines.
5311 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5312 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5313 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5314 function will not vscroll.
5318 If there is no character in the target line exactly under the current column,
5319 the cursor is positioned after the character in that line which spans this
5320 column, or at the end of the line if it is not long enough.
5321 If there is no line in the buffer after this one, behavior depends on the
5322 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5323 to create a line, and moves the cursor to that line. Otherwise it moves the
5324 cursor to the end of the buffer.
5326 If the variable `line-move-visual' is non-nil, this command moves
5327 by display lines. Otherwise, it moves by buffer lines, without
5328 taking variable-width characters or continued lines into account.
5330 The command \\[set-goal-column] can be used to create
5331 a semipermanent goal column for this command.
5332 Then instead of trying to move exactly vertically (or as close as possible),
5333 this command moves to the specified goal column (or as close as possible).
5334 The goal column is stored in the variable `goal-column', which is nil
5335 when there is no goal column. Note that setting `goal-column'
5336 overrides `line-move-visual' and causes this command to move by buffer
5337 lines rather than by display lines."
5338 (declare (interactive-only forward-line
))
5339 (interactive "^p\np")
5340 (or arg
(setq arg
1))
5341 (if (and next-line-add-newlines
(= arg
1))
5342 (if (save-excursion (end-of-line) (eobp))
5343 ;; When adding a newline, don't expand an abbrev.
5344 (let ((abbrev-mode nil
))
5346 (insert (if use-hard-newlines hard-newline
"\n")))
5347 (line-move arg nil nil try-vscroll
))
5348 (if (called-interactively-p 'interactive
)
5350 (line-move arg nil nil try-vscroll
)
5351 ((beginning-of-buffer end-of-buffer
)
5352 (signal (car err
) (cdr err
))))
5353 (line-move arg nil nil try-vscroll
)))
5356 (defun previous-line (&optional arg try-vscroll
)
5357 "Move cursor vertically up ARG lines.
5358 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5359 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5360 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5361 function will not vscroll.
5365 If there is no character in the target line exactly over the current column,
5366 the cursor is positioned after the character in that line which spans this
5367 column, or at the end of the line if it is not long enough.
5369 If the variable `line-move-visual' is non-nil, this command moves
5370 by display lines. Otherwise, it moves by buffer lines, without
5371 taking variable-width characters or continued lines into account.
5373 The command \\[set-goal-column] can be used to create
5374 a semipermanent goal column for this command.
5375 Then instead of trying to move exactly vertically (or as close as possible),
5376 this command moves to the specified goal column (or as close as possible).
5377 The goal column is stored in the variable `goal-column', which is nil
5378 when there is no goal column. Note that setting `goal-column'
5379 overrides `line-move-visual' and causes this command to move by buffer
5380 lines rather than by display lines."
5381 (declare (interactive-only
5382 "use `forward-line' with negative argument instead."))
5383 (interactive "^p\np")
5384 (or arg
(setq arg
1))
5385 (if (called-interactively-p 'interactive
)
5387 (line-move (- arg
) nil nil try-vscroll
)
5388 ((beginning-of-buffer end-of-buffer
)
5389 (signal (car err
) (cdr err
))))
5390 (line-move (- arg
) nil nil try-vscroll
))
5393 (defcustom track-eol nil
5394 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5395 This means moving to the end of each line moved onto.
5396 The beginning of a blank line does not count as the end of a line.
5397 This has no effect when the variable `line-move-visual' is non-nil."
5399 :group
'editing-basics
)
5401 (defcustom goal-column nil
5402 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5403 A non-nil setting overrides the variable `line-move-visual', which see."
5404 :type
'(choice integer
5405 (const :tag
"None" nil
))
5406 :group
'editing-basics
)
5407 (make-variable-buffer-local 'goal-column
)
5409 (defvar temporary-goal-column
0
5410 "Current goal column for vertical motion.
5411 It is the column where point was at the start of the current run
5412 of vertical motion commands.
5414 When moving by visual lines via the function `line-move-visual', it is a cons
5415 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5416 divided by the default column width, and HSCROLL is the number of
5417 columns by which window is scrolled from left margin.
5419 When the `track-eol' feature is doing its job, the value is
5420 `most-positive-fixnum'.")
5422 (defcustom line-move-ignore-invisible t
5423 "Non-nil means commands that move by lines ignore invisible newlines.
5424 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5425 as if newlines that are invisible didn't exist, and count
5426 only visible newlines. Thus, moving across across 2 newlines
5427 one of which is invisible will be counted as a one-line move.
5428 Also, a non-nil value causes invisible text to be ignored when
5429 counting columns for the purposes of keeping point in the same
5430 column by \\[next-line] and \\[previous-line].
5432 Outline mode sets this."
5434 :group
'editing-basics
)
5436 (defcustom line-move-visual t
5437 "When non-nil, `line-move' moves point by visual lines.
5438 This movement is based on where the cursor is displayed on the
5439 screen, instead of relying on buffer contents alone. It takes
5440 into account variable-width characters and line continuation.
5441 If nil, `line-move' moves point by logical lines.
5442 A non-nil setting of `goal-column' overrides the value of this variable
5443 and forces movement by logical lines.
5444 A window that is horizontally scrolled also forces movement by logical
5447 :group
'editing-basics
5450 ;; Only used if display-graphic-p.
5451 (declare-function font-info
"font.c" (name &optional frame
))
5453 (defun default-font-height ()
5454 "Return the height in pixels of the current buffer's default face font.
5456 If the default font is remapped (see `face-remapping-alist'), the
5457 function returns the height of the remapped face."
5458 (let ((default-font (face-font 'default
)))
5460 ((and (display-multi-font-p)
5461 ;; Avoid calling font-info if the frame's default font was
5462 ;; not changed since the frame was created. That's because
5463 ;; font-info is expensive for some fonts, see bug #14838.
5464 (not (string= (frame-parameter nil
'font
) default-font
)))
5465 (aref (font-info default-font
) 3))
5466 (t (frame-char-height)))))
5468 (defun default-font-width ()
5469 "Return the width in pixels of the current buffer's default face font.
5471 If the default font is remapped (see `face-remapping-alist'), the
5472 function returns the width of the remapped face."
5473 (let ((default-font (face-font 'default
)))
5475 ((and (display-multi-font-p)
5476 ;; Avoid calling font-info if the frame's default font was
5477 ;; not changed since the frame was created. That's because
5478 ;; font-info is expensive for some fonts, see bug #14838.
5479 (not (string= (frame-parameter nil
'font
) default-font
)))
5480 (let* ((info (font-info (face-font 'default
)))
5481 (width (aref info
11)))
5485 (t (frame-char-width)))))
5487 (defun default-line-height ()
5488 "Return the pixel height of current buffer's default-face text line.
5490 The value includes `line-spacing', if any, defined for the buffer
5492 (let ((dfh (default-font-height))
5493 (lsp (if (display-graphic-p)
5495 (default-value 'line-spacing
)
5496 (frame-parameter nil
'line-spacing
)
5500 (setq lsp
(truncate (* (frame-char-height) lsp
))))
5503 (defun window-screen-lines ()
5504 "Return the number of screen lines in the text area of the selected window.
5506 This is different from `window-text-height' in that this function counts
5507 lines in units of the height of the font used by the default face displayed
5508 in the window, not in units of the frame's default font, and also accounts
5509 for `line-spacing', if any, defined for the window's buffer or frame.
5511 The value is a floating-point number."
5512 (let ((edges (window-inside-pixel-edges))
5513 (dlh (default-line-height)))
5514 (/ (float (- (nth 3 edges
) (nth 1 edges
))) dlh
)))
5516 ;; Returns non-nil if partial move was done.
5517 (defun line-move-partial (arg noerror to-end
)
5519 ;; Move backward (up).
5520 ;; If already vscrolled, reduce vscroll
5521 (let ((vs (window-vscroll nil t
))
5522 (dlh (default-line-height)))
5524 (set-window-vscroll nil
(- vs dlh
) t
)))
5526 ;; Move forward (down).
5527 (let* ((lh (window-line-height -
1))
5532 (this-lh (window-line-height))
5533 (this-height (car this-lh
))
5534 (this-ypos (nth 2 this-lh
))
5535 (dlh (default-line-height))
5536 (wslines (window-screen-lines))
5537 (edges (window-inside-pixel-edges))
5538 (winh (- (nth 3 edges
) (nth 1 edges
) 1))
5540 (if (> (mod wslines
1.0) 0.0)
5541 (setq wslines
(round (+ wslines
0.5))))
5546 (<= this-ypos
(- dlh
)))
5548 (let ((wend (pos-visible-in-window-p t nil t
)))
5549 (setq rbot
(nth 3 wend
)
5551 vpos
(nth 5 wend
))))
5553 (let ((wstart (pos-visible-in-window-p nil nil t
)))
5554 (setq this-ypos
(nth 2 wstart
)
5555 this-height
(nth 4 wstart
))))
5558 (let ((ppos (posn-at-point))
5560 (setq col-row
(posn-actual-col-row ppos
))
5562 (- (cdr col-row
) (window-vscroll))
5563 (cdr (posn-col-row ppos
))))))
5564 ;; VPOS > 0 means the last line is only partially visible.
5565 ;; But if the part that is visible is at least as tall as the
5566 ;; default font, that means the line is actually fully
5567 ;; readable, and something like line-spacing is hidden. So in
5568 ;; that case we accept the last line in the window as still
5569 ;; visible, and consider the margin as starting one line
5571 (if (and vpos
(> vpos
0))
5573 (>= rowh
(default-font-height))
5575 (setq last-line
(min (- wslines scroll-margin
) vpos
))
5576 (setq last-line
(min (- wslines scroll-margin
1) (1- vpos
)))))
5578 ;; If last line of window is fully visible, and vscrolling
5579 ;; more would make this line invisible, move forward.
5580 ((and (or (< (setq vs
(window-vscroll nil t
)) dlh
)
5582 (<= this-height dlh
))
5583 (or (null rbot
) (= rbot
0)))
5585 ;; If cursor is not in the bottom scroll margin, and the
5586 ;; current line is is not too tall, move forward.
5587 ((and (or (null this-height
) (<= this-height winh
))
5592 ;; When already vscrolled, we vscroll some more if we can,
5593 ;; or clear vscroll and move forward at end of tall image.
5595 (when (or (and rbot
(> rbot
0))
5596 (and this-height
(> this-height dlh
)))
5597 (set-window-vscroll nil
(+ vs dlh
) t
)))
5598 ;; If cursor just entered the bottom scroll margin, move forward,
5599 ;; but also optionally vscroll one line so redisplay won't recenter.
5603 ;; Don't vscroll if the partially-visible line at window
5604 ;; bottom is not too tall (a.k.a. "just one more text
5605 ;; line"): in that case, we do want redisplay to behave
5606 ;; normally, i.e. recenter or whatever.
5608 ;; Note: ROWH + RBOT from the value returned by
5609 ;; pos-visible-in-window-p give the total height of the
5610 ;; partially-visible glyph row at the end of the window. As
5611 ;; we are dealing with floats, we disregard sub-pixel
5612 ;; discrepancies between that and DLH.
5613 (if (and rowh rbot
(>= (- (+ rowh rbot
) winh
) 1))
5614 (set-window-vscroll nil dlh t
))
5615 (line-move-1 arg noerror to-end
)
5617 ;; If there are lines above the last line, scroll-up one line.
5618 ((and vpos
(> vpos
0))
5621 ;; Finally, start vscroll.
5623 (set-window-vscroll nil dlh t
)))))))
5626 ;; This is like line-move-1 except that it also performs
5627 ;; vertical scrolling of tall images if appropriate.
5628 ;; That is not really a clean thing to do, since it mixes
5629 ;; scrolling with cursor motion. But so far we don't have
5630 ;; a cleaner solution to the problem of making C-n do something
5631 ;; useful given a tall image.
5632 (defun line-move (arg &optional noerror to-end try-vscroll
)
5633 "Move forward ARG lines.
5634 If NOERROR, don't signal an error if we can't move ARG lines.
5636 TRY-VSCROLL controls whether to vscroll tall lines: if either
5637 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5640 (line-move-1 arg noerror to-end
)
5641 (unless (and auto-window-vscroll try-vscroll
5642 ;; Only vscroll for single line moves
5644 ;; Under scroll-conservatively, the display engine
5645 ;; does this better.
5646 (zerop scroll-conservatively
)
5647 ;; But don't vscroll in a keyboard macro.
5648 (not defining-kbd-macro
)
5649 (not executing-kbd-macro
)
5650 (line-move-partial arg noerror to-end
))
5651 (set-window-vscroll nil
0 t
)
5652 (if (and line-move-visual
5653 ;; Display-based column are incompatible with goal-column.
5655 ;; When the text in the window is scrolled to the left,
5656 ;; display-based motion doesn't make sense (because each
5657 ;; logical line occupies exactly one screen line).
5658 (not (> (window-hscroll) 0))
5659 ;; Likewise when the text _was_ scrolled to the left
5660 ;; when the current run of vertical motion commands
5662 (not (and (memq last-command
5663 `(next-line previous-line
,this-command
))
5665 (numberp temporary-goal-column
)
5666 (>= temporary-goal-column
5667 (- (window-width) hscroll-margin
)))))
5668 (prog1 (line-move-visual arg noerror
)
5669 ;; If we moved into a tall line, set vscroll to make
5670 ;; scrolling through tall images more smooth.
5671 (let ((lh (line-pixel-height))
5672 (edges (window-inside-pixel-edges))
5673 (dlh (default-line-height))
5675 (setq winh
(- (nth 3 edges
) (nth 1 edges
) 1))
5677 (< (point) (window-start))
5682 (line-move-1 arg noerror to-end
)))))
5684 ;; Display-based alternative to line-move-1.
5685 ;; Arg says how many lines to move. The value is t if we can move the
5686 ;; specified number of lines.
5687 (defun line-move-visual (arg &optional noerror
)
5688 "Move ARG lines forward.
5689 If NOERROR, don't signal an error if we can't move that many lines."
5690 (let ((opoint (point))
5691 (hscroll (window-hscroll))
5693 ;; Check if the previous command was a line-motion command, or if
5694 ;; we were called from some other command.
5695 (if (and (consp temporary-goal-column
)
5696 (memq last-command
`(next-line previous-line
,this-command
)))
5697 ;; If so, there's no need to reset `temporary-goal-column',
5698 ;; but we may need to hscroll.
5699 (if (or (/= (cdr temporary-goal-column
) hscroll
)
5700 (> (cdr temporary-goal-column
) 0))
5701 (setq target-hscroll
(cdr temporary-goal-column
)))
5702 ;; Otherwise, we should reset `temporary-goal-column'.
5703 (let ((posn (posn-at-point))
5706 ;; Handle the `overflow-newline-into-fringe' case:
5707 ((eq (nth 1 posn
) 'right-fringe
)
5708 (setq temporary-goal-column
(cons (- (window-width) 1) hscroll
)))
5709 ((car (posn-x-y posn
))
5710 (setq x-pos
(car (posn-x-y posn
)))
5711 ;; In R2L lines, the X pixel coordinate is measured from the
5712 ;; left edge of the window, but columns are still counted
5713 ;; from the logical-order beginning of the line, i.e. from
5714 ;; the right edge in this case. We need to adjust for that.
5715 (if (eq (current-bidi-paragraph-direction) 'right-to-left
)
5716 (setq x-pos
(- (window-body-width nil t
) 1 x-pos
)))
5717 (setq temporary-goal-column
5718 (cons (/ (float x-pos
)
5722 (set-window-hscroll (selected-window) target-hscroll
))
5723 ;; vertical-motion can move more than it was asked to if it moves
5724 ;; across display strings with newlines. We don't want to ring
5725 ;; the bell and announce beginning/end of buffer in that case.
5726 (or (and (or (and (>= arg
0)
5727 (>= (vertical-motion
5728 (cons (or goal-column
5729 (if (consp temporary-goal-column
)
5730 (car temporary-goal-column
)
5731 temporary-goal-column
))
5735 (<= (vertical-motion
5736 (cons (or goal-column
5737 (if (consp temporary-goal-column
)
5738 (car temporary-goal-column
)
5739 temporary-goal-column
))
5744 ;; If the goal column lies on a display string,
5745 ;; `vertical-motion' advances the cursor to the end
5746 ;; of the string. For arg < 0, this can cause the
5747 ;; cursor to get stuck. (Bug#3020).
5748 (= (vertical-motion arg
) arg
)))
5750 (signal (if (< arg
0) 'beginning-of-buffer
'end-of-buffer
)
5753 ;; This is the guts of next-line and previous-line.
5754 ;; Arg says how many lines to move.
5755 ;; The value is t if we can move the specified number of lines.
5756 (defun line-move-1 (arg &optional noerror _to-end
)
5757 ;; Don't run any point-motion hooks, and disregard intangibility,
5758 ;; for intermediate positions.
5759 (let ((inhibit-point-motion-hooks t
)
5762 (if (consp temporary-goal-column
)
5763 (setq temporary-goal-column
(+ (car temporary-goal-column
)
5764 (cdr temporary-goal-column
))))
5767 (if (not (memq last-command
'(next-line previous-line
)))
5768 (setq temporary-goal-column
5769 (if (and track-eol
(eolp)
5770 ;; Don't count beg of empty line as end of line
5771 ;; unless we just did explicit end-of-line.
5772 (or (not (bolp)) (eq last-command
'move-end-of-line
)))
5773 most-positive-fixnum
5776 (if (not (or (integerp selective-display
)
5777 line-move-ignore-invisible
))
5778 ;; Use just newline characters.
5779 ;; Set ARG to 0 if we move as many lines as requested.
5781 (progn (if (> arg
1) (forward-line (1- arg
)))
5782 ;; This way of moving forward ARG lines
5783 ;; verifies that we have a newline after the last one.
5784 ;; It doesn't get confused by intangible text.
5786 (if (zerop (forward-line 1))
5788 (and (zerop (forward-line arg
))
5792 (signal (if (< arg
0)
5793 'beginning-of-buffer
5796 ;; Move by arg lines, but ignore invisible ones.
5798 (while (and (> arg
0) (not done
))
5799 ;; If the following character is currently invisible,
5800 ;; skip all characters with that same `invisible' property value.
5801 (while (and (not (eobp)) (invisible-p (point)))
5802 (goto-char (next-char-property-change (point))))
5804 ;; We don't use `end-of-line', since we want to escape
5805 ;; from field boundaries occurring exactly at point.
5806 (goto-char (constrain-to-field
5807 (let ((inhibit-field-text-motion t
))
5808 (line-end-position))
5810 'inhibit-line-move-field-capture
))
5811 ;; If there's no invisibility here, move over the newline.
5815 (signal 'end-of-buffer nil
)
5817 ((and (> arg
1) ;; Use vertical-motion for last move
5818 (not (integerp selective-display
))
5819 (not (invisible-p (point))))
5820 ;; We avoid vertical-motion when possible
5821 ;; because that has to fontify.
5823 ;; Otherwise move a more sophisticated way.
5824 ((zerop (vertical-motion 1))
5826 (signal 'end-of-buffer nil
)
5829 (setq arg
(1- arg
))))
5830 ;; The logic of this is the same as the loop above,
5831 ;; it just goes in the other direction.
5832 (while (and (< arg
0) (not done
))
5833 ;; For completely consistency with the forward-motion
5834 ;; case, we should call beginning-of-line here.
5835 ;; However, if point is inside a field and on a
5836 ;; continued line, the call to (vertical-motion -1)
5837 ;; below won't move us back far enough; then we return
5838 ;; to the same column in line-move-finish, and point
5839 ;; gets stuck -- cyd
5844 (signal 'beginning-of-buffer nil
)
5846 ((and (< arg -
1) ;; Use vertical-motion for last move
5847 (not (integerp selective-display
))
5848 (not (invisible-p (1- (point)))))
5850 ((zerop (vertical-motion -
1))
5852 (signal 'beginning-of-buffer nil
)
5856 (while (and ;; Don't move over previous invis lines
5857 ;; if our target is the middle of this line.
5858 (or (zerop (or goal-column temporary-goal-column
))
5860 (not (bobp)) (invisible-p (1- (point))))
5861 (goto-char (previous-char-property-change (point))))))))
5862 ;; This is the value the function returns.
5866 ;; If we did not move down as far as desired, at least go
5867 ;; to end of line. Be sure to call point-entered and
5868 ;; point-left-hooks.
5869 (let* ((npoint (prog1 (line-end-position)
5870 (goto-char opoint
)))
5871 (inhibit-point-motion-hooks nil
))
5872 (goto-char npoint
)))
5874 ;; If we did not move up as far as desired,
5875 ;; at least go to beginning of line.
5876 (let* ((npoint (prog1 (line-beginning-position)
5877 (goto-char opoint
)))
5878 (inhibit-point-motion-hooks nil
))
5879 (goto-char npoint
)))
5881 (line-move-finish (or goal-column temporary-goal-column
)
5882 opoint
(> orig-arg
0)))))))
5884 (defun line-move-finish (column opoint forward
)
5887 ;; Set REPEAT to t to repeat the whole thing.
5892 (line-beg (line-beginning-position))
5894 ;; Compute the end of the line
5895 ;; ignoring effectively invisible newlines.
5897 ;; Like end-of-line but ignores fields.
5898 (skip-chars-forward "^\n")
5899 (while (and (not (eobp)) (invisible-p (point)))
5900 (goto-char (next-char-property-change (point)))
5901 (skip-chars-forward "^\n"))
5904 ;; Move to the desired column.
5905 (line-move-to-column (truncate column
))
5907 ;; Corner case: suppose we start out in a field boundary in
5908 ;; the middle of a continued line. When we get to
5909 ;; line-move-finish, point is at the start of a new *screen*
5910 ;; line but the same text line; then line-move-to-column would
5911 ;; move us backwards. Test using C-n with point on the "x" in
5912 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
5919 ;; Process intangibility within a line.
5920 ;; With inhibit-point-motion-hooks bound to nil, a call to
5921 ;; goto-char moves point past intangible text.
5923 ;; However, inhibit-point-motion-hooks controls both the
5924 ;; intangibility and the point-entered/point-left hooks. The
5925 ;; following hack avoids calling the point-* hooks
5926 ;; unnecessarily. Note that we move *forward* past intangible
5927 ;; text when the initial and final points are the same.
5929 (let ((inhibit-point-motion-hooks nil
))
5932 ;; If intangibility moves us to a different (later) place
5933 ;; in the same line, use that as the destination.
5934 (if (<= (point) line-end
)
5936 ;; If that position is "too late",
5937 ;; try the previous allowable position.
5941 ;; If going forward, don't accept the previous
5942 ;; allowable position if it is before the target line.
5943 (< line-beg
(point))
5944 ;; If going backward, don't accept the previous
5945 ;; allowable position if it is still after the target line.
5946 (<= (point) line-end
))
5948 ;; As a last resort, use the end of the line.
5949 (setq new line-end
))))
5951 ;; Now move to the updated destination, processing fields
5952 ;; as well as intangibility.
5954 (let ((inhibit-point-motion-hooks nil
))
5956 ;; Ignore field boundaries if the initial and final
5957 ;; positions have the same `field' property, even if the
5958 ;; fields are non-contiguous. This seems to be "nicer"
5959 ;; behavior in many situations.
5960 (if (eq (get-char-property new
'field
)
5961 (get-char-property opoint
'field
))
5963 (constrain-to-field new opoint t t
5964 'inhibit-line-move-field-capture
))))
5966 ;; If all this moved us to a different line,
5967 ;; retry everything within that new line.
5968 (when (or (< (point) line-beg
) (> (point) line-end
))
5969 ;; Repeat the intangibility and field processing.
5970 (setq repeat t
))))))
5972 (defun line-move-to-column (col)
5973 "Try to find column COL, considering invisibility.
5974 This function works only in certain cases,
5975 because what we really need is for `move-to-column'
5976 and `current-column' to be able to ignore invisible text."
5979 (move-to-column col
))
5981 (when (and line-move-ignore-invisible
5982 (not (bolp)) (invisible-p (1- (point))))
5983 (let ((normal-location (point))
5984 (normal-column (current-column)))
5985 ;; If the following character is currently invisible,
5986 ;; skip all characters with that same `invisible' property value.
5987 (while (and (not (eobp))
5988 (invisible-p (point)))
5989 (goto-char (next-char-property-change (point))))
5990 ;; Have we advanced to a larger column position?
5991 (if (> (current-column) normal-column
)
5992 ;; We have made some progress towards the desired column.
5993 ;; See if we can make any further progress.
5994 (line-move-to-column (+ (current-column) (- col normal-column
)))
5995 ;; Otherwise, go to the place we originally found
5996 ;; and move back over invisible text.
5997 ;; that will get us to the same place on the screen
5998 ;; but with a more reasonable buffer position.
5999 (goto-char normal-location
)
6001 ;; We want the real line beginning, so it's consistent
6002 ;; with bolp below, otherwise we might infloop.
6003 (let ((inhibit-field-text-motion t
))
6004 (line-beginning-position))))
6005 (while (and (not (bolp)) (invisible-p (1- (point))))
6006 (goto-char (previous-char-property-change (point) line-beg
))))))))
6008 (defun move-end-of-line (arg)
6009 "Move point to end of current line as displayed.
6010 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6011 If point reaches the beginning or end of buffer, it stops there.
6013 To ignore the effects of the `intangible' text or overlay
6014 property, bind `inhibit-point-motion-hooks' to t.
6015 If there is an image in the current line, this function
6016 disregards newlines that are part of the text on which the image
6019 (or arg
(setq arg
1))
6024 (let ((goal-column 0)
6025 (line-move-visual nil
))
6026 (and (line-move arg t
)
6027 ;; With bidi reordering, we may not be at bol,
6028 ;; so make sure we are.
6029 (skip-chars-backward "^\n")
6032 (while (and (not (bobp)) (invisible-p (1- (point))))
6033 (goto-char (previous-single-char-property-change
6034 (point) 'invisible
)))
6038 (if (and (> (point) newpos
)
6039 (eq (preceding-char) ?
\n))
6041 (if (and (> (point) newpos
) (not (eobp))
6042 (not (eq (following-char) ?
\n)))
6043 ;; If we skipped something intangible and now we're not
6044 ;; really at eol, keep going.
6048 (defun move-beginning-of-line (arg)
6049 "Move point to beginning of current line as displayed.
6050 \(If there's an image in the line, this disregards newlines
6051 which are part of the text that the image rests on.)
6053 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6054 If point reaches the beginning or end of buffer, it stops there.
6055 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6057 (or arg
(setq arg
1))
6059 (let ((orig (point))
6060 first-vis first-vis-field-value
)
6062 ;; Move by lines, if ARG is not 1 (the default).
6064 (let ((line-move-visual nil
))
6065 (line-move (1- arg
) t
)))
6067 ;; Move to beginning-of-line, ignoring fields and invisible text.
6068 (skip-chars-backward "^\n")
6069 (while (and (not (bobp)) (invisible-p (1- (point))))
6070 (goto-char (previous-char-property-change (point)))
6071 (skip-chars-backward "^\n"))
6073 ;; Now find first visible char in the line.
6074 (while (and (< (point) orig
) (invisible-p (point)))
6075 (goto-char (next-char-property-change (point) orig
)))
6076 (setq first-vis
(point))
6078 ;; See if fields would stop us from reaching FIRST-VIS.
6079 (setq first-vis-field-value
6080 (constrain-to-field first-vis orig
(/= arg
1) t nil
))
6082 (goto-char (if (/= first-vis-field-value first-vis
)
6083 ;; If yes, obey them.
6084 first-vis-field-value
6085 ;; Otherwise, move to START with attention to fields.
6086 ;; (It is possible that fields never matter in this case.)
6087 (constrain-to-field (point) orig
6088 (/= arg
1) t nil
)))))
6091 ;; Many people have said they rarely use this feature, and often type
6092 ;; it by accident. Maybe it shouldn't even be on a key.
6093 (put 'set-goal-column
'disabled t
)
6095 (defun set-goal-column (arg)
6096 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6097 Those commands will move to this position in the line moved to
6098 rather than trying to keep the same horizontal position.
6099 With a non-nil argument ARG, clears out the goal column
6100 so that \\[next-line] and \\[previous-line] resume vertical motion.
6101 The goal column is stored in the variable `goal-column'."
6105 (setq goal-column nil
)
6106 (message "No goal column"))
6107 (setq goal-column
(current-column))
6108 ;; The older method below can be erroneous if `set-goal-column' is bound
6109 ;; to a sequence containing %
6110 ;;(message (substitute-command-keys
6111 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6115 (format "Goal column %d " goal-column
)
6116 (substitute-command-keys
6117 "(use \\[set-goal-column] with an arg to unset it)")))
6122 ;;; Editing based on visual lines, as opposed to logical lines.
6124 (defun end-of-visual-line (&optional n
)
6125 "Move point to end of current visual line.
6126 With argument N not nil or 1, move forward N - 1 visual lines first.
6127 If point reaches the beginning or end of buffer, it stops there.
6128 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6132 (let ((line-move-visual t
))
6133 (line-move (1- n
) t
)))
6134 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6135 ;; constrain to field boundaries, so we don't either.
6136 (vertical-motion (cons (window-width) 0)))
6138 (defun beginning-of-visual-line (&optional n
)
6139 "Move point to beginning of current visual line.
6140 With argument N not nil or 1, move forward N - 1 visual lines first.
6141 If point reaches the beginning or end of buffer, it stops there.
6142 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6145 (let ((opoint (point)))
6147 (let ((line-move-visual t
))
6148 (line-move (1- n
) t
)))
6150 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6151 (goto-char (constrain-to-field (point) opoint
(/= n
1)))))
6153 (defun kill-visual-line (&optional arg
)
6154 "Kill the rest of the visual line.
6155 With prefix argument ARG, kill that many visual lines from point.
6156 If ARG is negative, kill visual lines backward.
6157 If ARG is zero, kill the text before point on the current visual
6160 If you want to append the killed line to the last killed text,
6161 use \\[append-next-kill] before \\[kill-line].
6163 If the buffer is read-only, Emacs will beep and refrain from deleting
6164 the line, but put the line in the kill ring anyway. This means that
6165 you can use this command to copy text from a read-only buffer.
6166 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6169 ;; Like in `kill-line', it's better to move point to the other end
6170 ;; of the kill before killing.
6171 (let ((opoint (point))
6172 (kill-whole-line (and kill-whole-line
(bolp))))
6174 (vertical-motion (prefix-numeric-value arg
))
6175 (end-of-visual-line 1)
6176 (if (= (point) opoint
)
6178 ;; Skip any trailing whitespace at the end of the visual line.
6179 ;; We used to do this only if `show-trailing-whitespace' is
6180 ;; nil, but that's wrong; the correct thing would be to check
6181 ;; whether the trailing whitespace is highlighted. But, it's
6182 ;; OK to just do this unconditionally.
6183 (skip-chars-forward " \t")))
6184 (kill-region opoint
(if (and kill-whole-line
(looking-at "\n"))
6188 (defun next-logical-line (&optional arg try-vscroll
)
6189 "Move cursor vertically down ARG lines.
6190 This is identical to `next-line', except that it always moves
6191 by logical lines instead of visual lines, ignoring the value of
6192 the variable `line-move-visual'."
6193 (interactive "^p\np")
6194 (let ((line-move-visual nil
))
6196 (next-line arg try-vscroll
))))
6198 (defun previous-logical-line (&optional arg try-vscroll
)
6199 "Move cursor vertically up ARG lines.
6200 This is identical to `previous-line', except that it always moves
6201 by logical lines instead of visual lines, ignoring the value of
6202 the variable `line-move-visual'."
6203 (interactive "^p\np")
6204 (let ((line-move-visual nil
))
6206 (previous-line arg try-vscroll
))))
6208 (defgroup visual-line nil
6209 "Editing based on visual lines."
6213 (defvar visual-line-mode-map
6214 (let ((map (make-sparse-keymap)))
6215 (define-key map
[remap kill-line
] 'kill-visual-line
)
6216 (define-key map
[remap move-beginning-of-line
] 'beginning-of-visual-line
)
6217 (define-key map
[remap move-end-of-line
] 'end-of-visual-line
)
6218 ;; These keybindings interfere with xterm function keys. Are
6219 ;; there any other suitable bindings?
6220 ;; (define-key map "\M-[" 'previous-logical-line)
6221 ;; (define-key map "\M-]" 'next-logical-line)
6224 (defcustom visual-line-fringe-indicators
'(nil nil
)
6225 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6226 The value should be a list of the form (LEFT RIGHT), where LEFT
6227 and RIGHT are symbols representing the bitmaps to display, to
6228 indicate wrapped lines, in the left and right fringes respectively.
6229 See also `fringe-indicator-alist'.
6230 The default is not to display fringe indicators for wrapped lines.
6231 This variable does not affect fringe indicators displayed for
6233 :type
'(list (choice (const :tag
"Hide left indicator" nil
)
6234 (const :tag
"Left curly arrow" left-curly-arrow
)
6235 (symbol :tag
"Other bitmap"))
6236 (choice (const :tag
"Hide right indicator" nil
)
6237 (const :tag
"Right curly arrow" right-curly-arrow
)
6238 (symbol :tag
"Other bitmap")))
6239 :set
(lambda (symbol value
)
6240 (dolist (buf (buffer-list))
6241 (with-current-buffer buf
6242 (when (and (boundp 'visual-line-mode
)
6243 (symbol-value 'visual-line-mode
))
6244 (setq fringe-indicator-alist
6245 (cons (cons 'continuation value
)
6248 (copy-tree fringe-indicator-alist
)))))))
6249 (set-default symbol value
)))
6251 (defvar visual-line--saved-state nil
)
6253 (define-minor-mode visual-line-mode
6254 "Toggle visual line based editing (Visual Line mode).
6255 With a prefix argument ARG, enable Visual Line mode if ARG is
6256 positive, and disable it otherwise. If called from Lisp, enable
6257 the mode if ARG is omitted or nil.
6259 When Visual Line mode is enabled, `word-wrap' is turned on in
6260 this buffer, and simple editing commands are redefined to act on
6261 visual lines, not logical lines. See Info node `Visual Line
6263 :keymap visual-line-mode-map
6266 (if visual-line-mode
6268 (set (make-local-variable 'visual-line--saved-state
) nil
)
6269 ;; Save the local values of some variables, to be restored if
6270 ;; visual-line-mode is turned off.
6271 (dolist (var '(line-move-visual truncate-lines
6272 truncate-partial-width-windows
6273 word-wrap fringe-indicator-alist
))
6274 (if (local-variable-p var
)
6275 (push (cons var
(symbol-value var
))
6276 visual-line--saved-state
)))
6277 (set (make-local-variable 'line-move-visual
) t
)
6278 (set (make-local-variable 'truncate-partial-width-windows
) nil
)
6279 (setq truncate-lines nil
6281 fringe-indicator-alist
6282 (cons (cons 'continuation visual-line-fringe-indicators
)
6283 fringe-indicator-alist
)))
6284 (kill-local-variable 'line-move-visual
)
6285 (kill-local-variable 'word-wrap
)
6286 (kill-local-variable 'truncate-lines
)
6287 (kill-local-variable 'truncate-partial-width-windows
)
6288 (kill-local-variable 'fringe-indicator-alist
)
6289 (dolist (saved visual-line--saved-state
)
6290 (set (make-local-variable (car saved
)) (cdr saved
)))
6291 (kill-local-variable 'visual-line--saved-state
)))
6293 (defun turn-on-visual-line-mode ()
6294 (visual-line-mode 1))
6296 (define-globalized-minor-mode global-visual-line-mode
6297 visual-line-mode turn-on-visual-line-mode
)
6300 (defun transpose-chars (arg)
6301 "Interchange characters around point, moving forward one character.
6302 With prefix arg ARG, effect is to take character before point
6303 and drag it forward past ARG other characters (backward if ARG negative).
6304 If no argument and at end of line, the previous two chars are exchanged."
6306 (when (and (null arg
) (eolp) (not (bobp))
6307 (not (get-text-property (1- (point)) 'read-only
)))
6309 (transpose-subr 'forward-char
(prefix-numeric-value arg
)))
6311 (defun transpose-words (arg)
6312 "Interchange words around point, leaving point at end of them.
6313 With prefix arg ARG, effect is to take word before or around point
6314 and drag it forward past ARG other words (backward if ARG negative).
6315 If ARG is zero, the words around or after point and around or after mark
6317 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6319 (transpose-subr 'forward-word arg
))
6321 (defun transpose-sexps (arg)
6322 "Like \\[transpose-words] but applies to sexps.
6323 Does not work on a sexp that point is in the middle of
6324 if it is a list or string."
6328 ;; Here we should try to simulate the behavior of
6329 ;; (cons (progn (forward-sexp x) (point))
6330 ;; (progn (forward-sexp (- x)) (point)))
6331 ;; Except that we don't want to rely on the second forward-sexp
6332 ;; putting us back to where we want to be, since forward-sexp-function
6333 ;; might do funny things like infix-precedence.
6335 (looking-at "\\sw\\|\\s_")
6337 (save-excursion (forward-char -
1) (looking-at "\\sw\\|\\s_"))))
6338 ;; Jumping over a symbol. We might be inside it, mind you.
6339 (progn (funcall (if (> arg
0)
6340 'skip-syntax-backward
'skip-syntax-forward
)
6342 (cons (save-excursion (forward-sexp arg
) (point)) (point)))
6343 ;; Otherwise, we're between sexps. Take a step back before jumping
6344 ;; to make sure we'll obey the same precedence no matter which direction
6346 (funcall (if (> arg
0) 'skip-syntax-backward
'skip-syntax-forward
) " .")
6347 (cons (save-excursion (forward-sexp arg
) (point))
6348 (progn (while (or (forward-comment (if (> arg
0) 1 -
1))
6349 (not (zerop (funcall (if (> arg
0)
6350 'skip-syntax-forward
6351 'skip-syntax-backward
)
6356 (defun transpose-lines (arg)
6357 "Exchange current line and previous line, leaving point after both.
6358 With argument ARG, takes previous line and moves it past ARG lines.
6359 With argument 0, interchanges line point is in with line mark is in."
6361 (transpose-subr (function
6365 ;; Move forward over ARG lines,
6366 ;; but create newlines if necessary.
6367 (setq arg
(forward-line arg
))
6368 (if (/= (preceding-char) ?
\n)
6369 (setq arg
(1+ arg
)))
6372 (forward-line arg
))))
6375 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6376 ;; which seems inconsistent with the ARG /= 0 case.
6377 ;; FIXME document SPECIAL.
6378 (defun transpose-subr (mover arg
&optional special
)
6379 "Subroutine to do the work of transposing objects.
6380 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6381 moves forward by units of the given object (e.g. forward-sentence,
6382 forward-paragraph). If ARG is zero, exchanges the current object
6383 with the one containing mark. If ARG is an integer, moves the
6384 current object past ARG following (if ARG is positive) or
6385 preceding (if ARG is negative) objects, leaving point after the
6387 (let ((aux (if special mover
6389 (cons (progn (funcall mover x
) (point))
6390 (progn (funcall mover
(- x
)) (point))))))
6395 (setq pos1
(funcall aux
1))
6396 (goto-char (or (mark) (error "No mark set in this buffer")))
6397 (setq pos2
(funcall aux
1))
6398 (transpose-subr-1 pos1 pos2
))
6399 (exchange-point-and-mark))
6401 (setq pos1
(funcall aux -
1))
6402 (setq pos2
(funcall aux arg
))
6403 (transpose-subr-1 pos1 pos2
)
6404 (goto-char (car pos2
)))
6406 (setq pos1
(funcall aux -
1))
6407 (goto-char (car pos1
))
6408 (setq pos2
(funcall aux arg
))
6409 (transpose-subr-1 pos1 pos2
)))))
6411 (defun transpose-subr-1 (pos1 pos2
)
6412 (when (> (car pos1
) (cdr pos1
)) (setq pos1
(cons (cdr pos1
) (car pos1
))))
6413 (when (> (car pos2
) (cdr pos2
)) (setq pos2
(cons (cdr pos2
) (car pos2
))))
6414 (when (> (car pos1
) (car pos2
))
6416 (setq pos1 pos2 pos2 swap
)))
6417 (if (> (cdr pos1
) (car pos2
)) (error "Don't have two things to transpose"))
6418 (atomic-change-group
6419 ;; This sequence of insertions attempts to preserve marker
6420 ;; positions at the start and end of the transposed objects.
6421 (let* ((word (buffer-substring (car pos2
) (cdr pos2
)))
6422 (len1 (- (cdr pos1
) (car pos1
)))
6423 (len2 (length word
))
6424 (boundary (make-marker)))
6425 (set-marker boundary
(car pos2
))
6426 (goto-char (cdr pos1
))
6427 (insert-before-markers word
)
6428 (setq word
(delete-and-extract-region (car pos1
) (+ (car pos1
) len1
)))
6429 (goto-char boundary
)
6431 (goto-char (+ boundary len1
))
6432 (delete-region (point) (+ (point) len2
))
6433 (set-marker boundary nil
))))
6435 (defun backward-word (&optional arg
)
6436 "Move backward until encountering the beginning of a word.
6437 With argument ARG, do this that many times.
6438 If ARG is omitted or nil, move point backward one word."
6440 (forward-word (- (or arg
1))))
6442 (defun mark-word (&optional arg allow-extend
)
6443 "Set mark ARG words away from point.
6444 The place mark goes is the same place \\[forward-word] would
6445 move to with the same argument.
6446 Interactively, if this command is repeated
6447 or (in Transient Mark mode) if the mark is active,
6448 it marks the next ARG words after the ones already marked."
6449 (interactive "P\np")
6450 (cond ((and allow-extend
6451 (or (and (eq last-command this-command
) (mark t
))
6453 (setq arg
(if arg
(prefix-numeric-value arg
)
6454 (if (< (mark) (point)) -
1 1)))
6463 (forward-word (prefix-numeric-value arg
))
6467 (defun kill-word (arg)
6468 "Kill characters forward until encountering the end of a word.
6469 With argument ARG, do this that many times."
6471 (kill-region (point) (progn (forward-word arg
) (point))))
6473 (defun backward-kill-word (arg)
6474 "Kill characters backward until encountering the beginning of a word.
6475 With argument ARG, do this that many times."
6477 (kill-word (- arg
)))
6479 (defun current-word (&optional strict really-word
)
6480 "Return the symbol or word that point is on (or a nearby one) as a string.
6481 The return value includes no text properties.
6482 If optional arg STRICT is non-nil, return nil unless point is within
6483 or adjacent to a symbol or word. In all cases the value can be nil
6484 if there is no word nearby.
6485 The function, belying its name, normally finds a symbol.
6486 If optional arg REALLY-WORD is non-nil, it finds just a word."
6488 (let* ((oldpoint (point)) (start (point)) (end (point))
6489 (syntaxes (if really-word
"w" "w_"))
6490 (not-syntaxes (concat "^" syntaxes
)))
6491 (skip-syntax-backward syntaxes
) (setq start
(point))
6492 (goto-char oldpoint
)
6493 (skip-syntax-forward syntaxes
) (setq end
(point))
6494 (when (and (eq start oldpoint
) (eq end oldpoint
)
6495 ;; Point is neither within nor adjacent to a word.
6497 ;; Look for preceding word in same line.
6498 (skip-syntax-backward not-syntaxes
(line-beginning-position))
6500 ;; No preceding word in same line.
6501 ;; Look for following word in same line.
6503 (skip-syntax-forward not-syntaxes
(line-end-position))
6504 (setq start
(point))
6505 (skip-syntax-forward syntaxes
)
6508 (skip-syntax-backward syntaxes
)
6509 (setq start
(point))))
6510 ;; If we found something nonempty, return it as a string.
6511 (unless (= start end
)
6512 (buffer-substring-no-properties start end
)))))
6514 (defcustom fill-prefix nil
6515 "String for filling to insert at front of new line, or nil for none."
6516 :type
'(choice (const :tag
"None" nil
)
6519 (make-variable-buffer-local 'fill-prefix
)
6520 (put 'fill-prefix
'safe-local-variable
'string-or-null-p
)
6522 (defcustom auto-fill-inhibit-regexp nil
6523 "Regexp to match lines which should not be auto-filled."
6524 :type
'(choice (const :tag
"None" nil
)
6528 (defun do-auto-fill ()
6529 "The default value for `normal-auto-fill-function'.
6530 This is the default auto-fill function, some major modes use a different one.
6531 Returns t if it really did any work."
6532 (let (fc justify give-up
6533 (fill-prefix fill-prefix
))
6534 (if (or (not (setq justify
(current-justification)))
6535 (null (setq fc
(current-fill-column)))
6536 (and (eq justify
'left
)
6537 (<= (current-column) fc
))
6538 (and auto-fill-inhibit-regexp
6539 (save-excursion (beginning-of-line)
6540 (looking-at auto-fill-inhibit-regexp
))))
6541 nil
;; Auto-filling not required
6542 (if (memq justify
'(full center right
))
6543 (save-excursion (unjustify-current-line)))
6545 ;; Choose a fill-prefix automatically.
6546 (when (and adaptive-fill-mode
6547 (or (null fill-prefix
) (string= fill-prefix
"")))
6549 (fill-context-prefix
6550 (save-excursion (fill-forward-paragraph -
1) (point))
6551 (save-excursion (fill-forward-paragraph 1) (point)))))
6552 (and prefix
(not (equal prefix
""))
6553 ;; Use auto-indentation rather than a guessed empty prefix.
6554 (not (and fill-indent-according-to-mode
6555 (string-match "\\`[ \t]*\\'" prefix
)))
6556 (setq fill-prefix prefix
))))
6558 (while (and (not give-up
) (> (current-column) fc
))
6559 ;; Determine where to split the line.
6564 (setq after-prefix
(point))
6566 (looking-at (regexp-quote fill-prefix
))
6567 (setq after-prefix
(match-end 0)))
6568 (move-to-column (1+ fc
))
6569 (fill-move-to-break-point after-prefix
)
6572 ;; See whether the place we found is any good.
6574 (goto-char fill-point
)
6576 ;; There is no use breaking at end of line.
6577 (save-excursion (skip-chars-forward " ") (eolp))
6578 ;; It is futile to split at the end of the prefix
6579 ;; since we would just insert the prefix again.
6580 (and after-prefix
(<= (point) after-prefix
))
6581 ;; Don't split right after a comment starter
6582 ;; since we would just make another comment starter.
6583 (and comment-start-skip
6584 (let ((limit (point)))
6586 (and (re-search-forward comment-start-skip
6588 (eq (point) limit
))))))
6589 ;; No good place to break => stop trying.
6591 ;; Ok, we have a useful place to break the line. Do it.
6592 (let ((prev-column (current-column)))
6593 ;; If point is at the fill-point, do not `save-excursion'.
6594 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6595 ;; point will end up before it rather than after it.
6597 (skip-chars-backward " \t")
6598 (= (point) fill-point
))
6599 (default-indent-new-line t
)
6601 (goto-char fill-point
)
6602 (default-indent-new-line t
)))
6603 ;; Now do justification, if required
6604 (if (not (eq justify
'left
))
6607 (justify-current-line justify nil t
)))
6608 ;; If making the new line didn't reduce the hpos of
6609 ;; the end of the line, then give up now;
6610 ;; trying again will not help.
6611 (if (>= (current-column) prev-column
)
6612 (setq give-up t
))))))
6613 ;; Justify last line.
6614 (justify-current-line justify t t
)
6617 (defvar comment-line-break-function
'comment-indent-new-line
6618 "Mode-specific function which line breaks and continues a comment.
6619 This function is called during auto-filling when a comment syntax
6621 The function should take a single optional argument, which is a flag
6622 indicating whether it should use soft newlines.")
6624 (defun default-indent-new-line (&optional soft
)
6625 "Break line at point and indent.
6626 If a comment syntax is defined, call `comment-indent-new-line'.
6628 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6629 unless optional argument SOFT is non-nil."
6632 (funcall comment-line-break-function soft
)
6633 ;; Insert the newline before removing empty space so that markers
6634 ;; get preserved better.
6635 (if soft
(insert-and-inherit ?
\n) (newline 1))
6636 (save-excursion (forward-char -
1) (delete-horizontal-space))
6637 (delete-horizontal-space)
6639 (if (and fill-prefix
(not adaptive-fill-mode
))
6640 ;; Blindly trust a non-adaptive fill-prefix.
6642 (indent-to-left-margin)
6643 (insert-before-markers-and-inherit fill-prefix
))
6646 ;; If there's an adaptive prefix, use it unless we're inside
6647 ;; a comment and the prefix is not a comment starter.
6649 (indent-to-left-margin)
6650 (insert-and-inherit fill-prefix
))
6651 ;; If we're not inside a comment, just try to indent.
6652 (t (indent-according-to-mode))))))
6654 (defvar normal-auto-fill-function
'do-auto-fill
6655 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6656 Some major modes set this.")
6658 (put 'auto-fill-function
:minor-mode-function
'auto-fill-mode
)
6659 ;; `functions' and `hooks' are usually unsafe to set, but setting
6660 ;; auto-fill-function to nil in a file-local setting is safe and
6661 ;; can be useful to prevent auto-filling.
6662 (put 'auto-fill-function
'safe-local-variable
'null
)
6664 (define-minor-mode auto-fill-mode
6665 "Toggle automatic line breaking (Auto Fill mode).
6666 With a prefix argument ARG, enable Auto Fill mode if ARG is
6667 positive, and disable it otherwise. If called from Lisp, enable
6668 the mode if ARG is omitted or nil.
6670 When Auto Fill mode is enabled, inserting a space at a column
6671 beyond `current-fill-column' automatically breaks the line at a
6674 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6677 The value of `normal-auto-fill-function' specifies the function to use
6678 for `auto-fill-function' when turning Auto Fill mode on."
6679 :variable
(auto-fill-function
6680 .
(lambda (v) (setq auto-fill-function
6681 (if v normal-auto-fill-function
)))))
6683 ;; This holds a document string used to document auto-fill-mode.
6684 (defun auto-fill-function ()
6685 "Automatically break line at a previous space, in insertion of text."
6688 (defun turn-on-auto-fill ()
6689 "Unconditionally turn on Auto Fill mode."
6692 (defun turn-off-auto-fill ()
6693 "Unconditionally turn off Auto Fill mode."
6694 (auto-fill-mode -
1))
6696 (custom-add-option 'text-mode-hook
'turn-on-auto-fill
)
6698 (defun set-fill-column (arg)
6699 "Set `fill-column' to specified argument.
6700 Use \\[universal-argument] followed by a number to specify a column.
6701 Just \\[universal-argument] as argument means to use the current column."
6703 (list (or current-prefix-arg
6704 ;; We used to use current-column silently, but C-x f is too easily
6705 ;; typed as a typo for C-x C-f, so we turned it into an error and
6706 ;; now an interactive prompt.
6707 (read-number "Set fill-column to: " (current-column)))))
6709 (setq arg
(current-column)))
6710 (if (not (integerp arg
))
6711 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6712 (error "set-fill-column requires an explicit argument")
6713 (message "Fill column set to %d (was %d)" arg fill-column
)
6714 (setq fill-column arg
)))
6716 (defun set-selective-display (arg)
6717 "Set `selective-display' to ARG; clear it if no arg.
6718 When the value of `selective-display' is a number > 0,
6719 lines whose indentation is >= that value are not displayed.
6720 The variable `selective-display' has a separate value for each buffer."
6722 (if (eq selective-display t
)
6723 (error "selective-display already in use for marked lines"))
6726 (narrow-to-region (point-min) (point))
6727 (goto-char (window-start))
6728 (vertical-motion (window-height)))))
6729 (setq selective-display
6730 (and arg
(prefix-numeric-value arg
)))
6731 (recenter current-vpos
))
6732 (set-window-start (selected-window) (window-start))
6733 (princ "selective-display set to " t
)
6734 (prin1 selective-display t
)
6737 (defvaralias 'indicate-unused-lines
'indicate-empty-lines
)
6739 (defun toggle-truncate-lines (&optional arg
)
6740 "Toggle truncating of long lines for the current buffer.
6741 When truncating is off, long lines are folded.
6742 With prefix argument ARG, truncate long lines if ARG is positive,
6743 otherwise fold them. Note that in side-by-side windows, this
6744 command has no effect if `truncate-partial-width-windows' is
6747 (setq truncate-lines
6749 (not truncate-lines
)
6750 (> (prefix-numeric-value arg
) 0)))
6751 (force-mode-line-update)
6752 (unless truncate-lines
6753 (let ((buffer (current-buffer)))
6754 (walk-windows (lambda (window)
6755 (if (eq buffer
(window-buffer window
))
6756 (set-window-hscroll window
0)))
6758 (message "Truncate long lines %s"
6759 (if truncate-lines
"enabled" "disabled")))
6761 (defun toggle-word-wrap (&optional arg
)
6762 "Toggle whether to use word-wrapping for continuation lines.
6763 With prefix argument ARG, wrap continuation lines at word boundaries
6764 if ARG is positive, otherwise wrap them at the right screen edge.
6765 This command toggles the value of `word-wrap'. It has no effect
6766 if long lines are truncated."
6771 (> (prefix-numeric-value arg
) 0)))
6772 (force-mode-line-update)
6773 (message "Word wrapping %s"
6774 (if word-wrap
"enabled" "disabled")))
6776 (defvar overwrite-mode-textual
(purecopy " Ovwrt")
6777 "The string displayed in the mode line when in overwrite mode.")
6778 (defvar overwrite-mode-binary
(purecopy " Bin Ovwrt")
6779 "The string displayed in the mode line when in binary overwrite mode.")
6781 (define-minor-mode overwrite-mode
6782 "Toggle Overwrite mode.
6783 With a prefix argument ARG, enable Overwrite mode if ARG is
6784 positive, and disable it otherwise. If called from Lisp, enable
6785 the mode if ARG is omitted or nil.
6787 When Overwrite mode is enabled, printing characters typed in
6788 replace existing text on a one-for-one basis, rather than pushing
6789 it to the right. At the end of a line, such characters extend
6790 the line. Before a tab, such characters insert until the tab is
6791 filled in. \\[quoted-insert] still inserts characters in
6792 overwrite mode; this is supposed to make it easier to insert
6793 characters when necessary."
6794 :variable
(overwrite-mode
6795 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-textual
)))))
6797 (define-minor-mode binary-overwrite-mode
6798 "Toggle Binary Overwrite mode.
6799 With a prefix argument ARG, enable Binary Overwrite mode if ARG
6800 is positive, and disable it otherwise. If called from Lisp,
6801 enable the mode if ARG is omitted or nil.
6803 When Binary Overwrite mode is enabled, printing characters typed
6804 in replace existing text. Newlines are not treated specially, so
6805 typing at the end of a line joins the line to the next, with the
6806 typed character between them. Typing before a tab character
6807 simply replaces the tab with the character typed.
6808 \\[quoted-insert] replaces the text at the cursor, just as
6809 ordinary typing characters do.
6811 Note that Binary Overwrite mode is not its own minor mode; it is
6812 a specialization of overwrite mode, entered by setting the
6813 `overwrite-mode' variable to `overwrite-mode-binary'."
6814 :variable
(overwrite-mode
6815 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-binary
)))))
6817 (define-minor-mode line-number-mode
6818 "Toggle line number display in the mode line (Line Number mode).
6819 With a prefix argument ARG, enable Line Number mode if ARG is
6820 positive, and disable it otherwise. If called from Lisp, enable
6821 the mode if ARG is omitted or nil.
6823 Line numbers do not appear for very large buffers and buffers
6824 with very long lines; see variables `line-number-display-limit'
6825 and `line-number-display-limit-width'."
6826 :init-value t
:global t
:group
'mode-line
)
6828 (define-minor-mode column-number-mode
6829 "Toggle column number display in the mode line (Column Number mode).
6830 With a prefix argument ARG, enable Column Number mode if ARG is
6831 positive, and disable it otherwise.
6833 If called from Lisp, enable the mode if ARG is omitted or nil."
6834 :global t
:group
'mode-line
)
6836 (define-minor-mode size-indication-mode
6837 "Toggle buffer size display in the mode line (Size Indication mode).
6838 With a prefix argument ARG, enable Size Indication mode if ARG is
6839 positive, and disable it otherwise.
6841 If called from Lisp, enable the mode if ARG is omitted or nil."
6842 :global t
:group
'mode-line
)
6844 (define-minor-mode auto-save-mode
6845 "Toggle auto-saving in the current buffer (Auto Save mode).
6846 With a prefix argument ARG, enable Auto Save mode if ARG is
6847 positive, and disable it otherwise.
6849 If called from Lisp, enable the mode if ARG is omitted or nil."
6850 :variable
((and buffer-auto-save-file-name
6851 ;; If auto-save is off because buffer has shrunk,
6852 ;; then toggling should turn it on.
6853 (>= buffer-saved-size
0))
6855 (setq buffer-auto-save-file-name
6858 ((and buffer-file-name auto-save-visited-file-name
6859 (not buffer-read-only
))
6861 (t (make-auto-save-file-name))))))
6862 ;; If -1 was stored here, to temporarily turn off saving,
6864 (and (< buffer-saved-size
0)
6865 (setq buffer-saved-size
0)))
6867 (defgroup paren-blinking nil
6868 "Blinking matching of parens and expressions."
6869 :prefix
"blink-matching-"
6870 :group
'paren-matching
)
6872 (defcustom blink-matching-paren t
6873 "Non-nil means show matching open-paren when close-paren is inserted.
6874 If t, highlight the paren. If `jump', move cursor to its position."
6876 (const :tag
"Disable" nil
)
6877 (const :tag
"Highlight" t
)
6878 (const :tag
"Move cursor" jump
))
6879 :group
'paren-blinking
)
6881 (defcustom blink-matching-paren-on-screen t
6882 "Non-nil means show matching open-paren when it is on screen.
6883 If nil, don't show it (but the open-paren can still be shown
6884 when it is off screen).
6886 This variable has no effect if `blink-matching-paren' is nil.
6887 \(In that case, the open-paren is never shown.)
6888 It is also ignored if `show-paren-mode' is enabled."
6890 :group
'paren-blinking
)
6892 (defcustom blink-matching-paren-distance
(* 100 1024)
6893 "If non-nil, maximum distance to search backwards for matching open-paren.
6894 If nil, search stops at the beginning of the accessible portion of the buffer."
6895 :version
"23.2" ; 25->100k
6896 :type
'(choice (const nil
) integer
)
6897 :group
'paren-blinking
)
6899 (defcustom blink-matching-delay
1
6900 "Time in seconds to delay after showing a matching paren."
6902 :group
'paren-blinking
)
6904 (defcustom blink-matching-paren-dont-ignore-comments nil
6905 "If nil, `blink-matching-paren' ignores comments.
6906 More precisely, when looking for the matching parenthesis,
6907 it skips the contents of comments that end before point."
6909 :group
'paren-blinking
)
6911 (defun blink-matching-check-mismatch (start end
)
6912 "Return whether or not START...END are matching parens.
6913 END is the current point and START is the blink position.
6914 START might be nil if no matching starter was found.
6915 Returns non-nil if we find there is a mismatch."
6916 (let* ((end-syntax (syntax-after (1- end
)))
6917 (matching-paren (and (consp end-syntax
)
6918 (eq (syntax-class end-syntax
) 5)
6920 ;; For self-matched chars like " and $, we can't know when they're
6921 ;; mismatched or unmatched, so we can only do it for parens.
6922 (when matching-paren
6925 (eq (char-after start
) matching-paren
)
6926 ;; The cdr might hold a new paren-class info rather than
6927 ;; a matching-char info, in which case the two CDRs
6929 (eq matching-paren
(cdr-safe (syntax-after start
)))))))))
6931 (defvar blink-matching-check-function
#'blink-matching-check-mismatch
6932 "Function to check parentheses mismatches.
6933 The function takes two arguments (START and END) where START is the
6934 position just before the opening token and END is the position right after.
6935 START can be nil, if it was not found.
6936 The function should return non-nil if the two tokens do not match.")
6938 (defvar blink-matching--overlay
6939 (let ((ol (make-overlay (point) (point) nil t
)))
6940 (overlay-put ol
'face
'show-paren-match
)
6943 "Overlay used to highlight the matching paren.")
6945 (defun blink-matching-open ()
6946 "Momentarily highlight the beginning of the sexp before point."
6948 (when (and (not (bobp))
6949 blink-matching-paren
)
6950 (let* ((oldpos (point))
6951 (message-log-max nil
) ; Don't log messages about paren matching.
6955 (if blink-matching-paren-distance
6957 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
6958 (- (point) blink-matching-paren-distance
))
6960 (let ((parse-sexp-ignore-comments
6961 (and parse-sexp-ignore-comments
6962 (not blink-matching-paren-dont-ignore-comments
))))
6965 (syntax-propertize (point))
6967 ;; backward-sexp skips backward over prefix chars,
6968 ;; so move back to the matching paren.
6969 (while (and (< (point) (1- oldpos
))
6970 (let ((code (syntax-after (point))))
6971 (or (eq (syntax-class code
) 6)
6972 (eq (logand 1048576 (car code
))
6977 (mismatch (funcall blink-matching-check-function blinkpos oldpos
)))
6982 (minibuffer-message "Mismatched parentheses")
6983 (message "Mismatched parentheses"))
6985 (minibuffer-message "No matching parenthesis found")
6986 (message "No matching parenthesis found"))))
6987 ((not blinkpos
) nil
)
6988 ((pos-visible-in-window-p blinkpos
)
6989 ;; Matching open within window, temporarily move to or highlight
6990 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
6992 (and blink-matching-paren-on-screen
6993 (not show-paren-mode
)
6994 (if (eq blink-matching-paren
'jump
)
6996 (goto-char blinkpos
)
6997 (sit-for blink-matching-delay
))
7000 (move-overlay blink-matching--overlay blinkpos
(1+ blinkpos
)
7002 (sit-for blink-matching-delay
))
7003 (delete-overlay blink-matching--overlay
)))))
7006 (goto-char blinkpos
)
7007 (let ((open-paren-line-string
7008 ;; Show what precedes the open in its line, if anything.
7010 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7011 (buffer-substring (line-beginning-position)
7013 ;; Show what follows the open in its line, if anything.
7016 (skip-chars-forward " \t")
7018 (buffer-substring blinkpos
7019 (line-end-position)))
7020 ;; Otherwise show the previous nonblank line,
7022 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7024 (buffer-substring (progn
7025 (skip-chars-backward "\n \t")
7026 (line-beginning-position))
7027 (progn (end-of-line)
7028 (skip-chars-backward " \t")
7030 ;; Replace the newline and other whitespace with `...'.
7032 (buffer-substring blinkpos
(1+ blinkpos
))))
7033 ;; There is nothing to show except the char itself.
7034 (t (buffer-substring blinkpos
(1+ blinkpos
))))))
7037 (substring-no-properties open-paren-line-string
)))))))))
7039 (defvar blink-paren-function
'blink-matching-open
7040 "Function called, if non-nil, whenever a close parenthesis is inserted.
7041 More precisely, a char with closeparen syntax is self-inserted.")
7043 (defun blink-paren-post-self-insert-function ()
7044 (when (and (eq (char-before) last-command-event
) ; Sanity check.
7045 (memq (char-syntax last-command-event
) '(?\
) ?\$
))
7046 blink-paren-function
7047 (not executing-kbd-macro
)
7048 (not noninteractive
)
7049 ;; Verify an even number of quoting characters precede the close.
7050 ;; FIXME: Also check if this parenthesis closes a comment as
7051 ;; can happen in Pascal and SML.
7052 (= 1 (logand 1 (- (point)
7055 (skip-syntax-backward "/\\")
7057 (funcall blink-paren-function
)))
7059 (put 'blink-paren-post-self-insert-function
'priority
100)
7061 (add-hook 'post-self-insert-hook
#'blink-paren-post-self-insert-function
7062 ;; Most likely, this hook is nil, so this arg doesn't matter,
7063 ;; but I use it as a reminder that this function usually
7064 ;; likes to be run after others since it does
7065 ;; `sit-for'. That's also the reason it get a `priority' prop
7069 ;; This executes C-g typed while Emacs is waiting for a command.
7070 ;; Quitting out of a program does not go through here;
7071 ;; that happens in the QUIT macro at the C code level.
7072 (defun keyboard-quit ()
7073 "Signal a `quit' condition.
7074 During execution of Lisp code, this character causes a quit directly.
7075 At top-level, as an editor command, this simply beeps."
7077 ;; Avoid adding the region to the window selection.
7078 (setq saved-region-selection nil
)
7079 (let (select-active-regions)
7081 (if (fboundp 'kmacro-keyboard-quit
)
7082 (kmacro-keyboard-quit))
7083 (when completion-in-region-mode
7084 (completion-in-region-mode -
1))
7085 ;; Force the next redisplay cycle to remove the "Def" indicator from
7086 ;; all the mode lines.
7087 (if defining-kbd-macro
7088 (force-mode-line-update t
))
7089 (setq defining-kbd-macro nil
)
7090 (let ((debug-on-quit nil
))
7091 (signal 'quit nil
)))
7093 (defvar buffer-quit-function nil
7094 "Function to call to \"quit\" the current buffer, or nil if none.
7095 \\[keyboard-escape-quit] calls this function when its more local actions
7096 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7098 (defun keyboard-escape-quit ()
7099 "Exit the current \"mode\" (in a generalized sense of the word).
7100 This command can exit an interactive command such as `query-replace',
7101 can clear out a prefix argument or a region,
7102 can get out of the minibuffer or other recursive edit,
7103 cancel the use of the current buffer (for special-purpose buffers),
7104 or go back to just one window (by deleting all but the selected window)."
7106 (cond ((eq last-command
'mode-exited
) nil
)
7109 ((> (minibuffer-depth) 0)
7110 (abort-recursive-edit))
7113 ((> (recursion-depth) 0)
7114 (exit-recursive-edit))
7115 (buffer-quit-function
7116 (funcall buffer-quit-function
))
7117 ((not (one-window-p t
))
7118 (delete-other-windows))
7119 ((string-match "^ \\*" (buffer-name (current-buffer)))
7122 (defun play-sound-file (file &optional volume device
)
7123 "Play sound stored in FILE.
7124 VOLUME and DEVICE correspond to the keywords of the sound
7125 specification for `play-sound'."
7126 (interactive "fPlay sound file: ")
7127 (let ((sound (list :file file
)))
7129 (plist-put sound
:volume volume
))
7131 (plist-put sound
:device device
))
7133 (play-sound sound
)))
7136 (defcustom read-mail-command
'rmail
7137 "Your preference for a mail reading package.
7138 This is used by some keybindings which support reading mail.
7139 See also `mail-user-agent' concerning sending mail."
7140 :type
'(radio (function-item :tag
"Rmail" :format
"%t\n" rmail
)
7141 (function-item :tag
"Gnus" :format
"%t\n" gnus
)
7142 (function-item :tag
"Emacs interface to MH"
7143 :format
"%t\n" mh-rmail
)
7144 (function :tag
"Other"))
7148 (defcustom mail-user-agent
'message-user-agent
7149 "Your preference for a mail composition package.
7150 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7151 outgoing email message. This variable lets you specify which
7152 mail-sending package you prefer.
7154 Valid values include:
7156 `message-user-agent' -- use the Message package.
7157 See Info node `(message)'.
7158 `sendmail-user-agent' -- use the Mail package.
7159 See Info node `(emacs)Sending Mail'.
7160 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7161 See Info node `(mh-e)'.
7162 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7163 paraphernalia if Gnus is running, particularly
7164 the Gcc: header for archiving.
7166 Additional valid symbols may be available; check with the author of
7167 your package for details. The function should return non-nil if it
7170 See also `read-mail-command' concerning reading mail."
7171 :type
'(radio (function-item :tag
"Message package"
7174 (function-item :tag
"Mail package"
7176 sendmail-user-agent
)
7177 (function-item :tag
"Emacs interface to MH"
7180 (function-item :tag
"Message with full Gnus features"
7183 (function :tag
"Other"))
7184 :version
"23.2" ; sendmail->message
7187 (defcustom compose-mail-user-agent-warnings t
7188 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7189 If the value of `mail-user-agent' is the default, and the user
7190 appears to have customizations applying to the old default,
7191 `compose-mail' issues a warning."
7196 (defun rfc822-goto-eoh ()
7197 "If the buffer starts with a mail header, move point to the header's end.
7198 Otherwise, moves to `point-min'.
7199 The end of the header is the start of the next line, if there is one,
7200 else the end of the last line. This function obeys RFC822."
7201 (goto-char (point-min))
7202 (when (re-search-forward
7203 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil
'move
)
7204 (goto-char (match-beginning 0))))
7206 ;; Used by Rmail (e.g., rmail-forward).
7207 (defvar mail-encode-mml nil
7208 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7209 the outgoing message before sending it.")
7211 (defun compose-mail (&optional to subject other-headers continue
7212 switch-function yank-action send-actions
7214 "Start composing a mail message to send.
7215 This uses the user's chosen mail composition package
7216 as selected with the variable `mail-user-agent'.
7217 The optional arguments TO and SUBJECT specify recipients
7218 and the initial Subject field, respectively.
7220 OTHER-HEADERS is an alist specifying additional
7221 header fields. Elements look like (HEADER . VALUE) where both
7222 HEADER and VALUE are strings.
7224 CONTINUE, if non-nil, says to continue editing a message already
7225 being composed. Interactively, CONTINUE is the prefix argument.
7227 SWITCH-FUNCTION, if non-nil, is a function to use to
7228 switch to and display the buffer used for mail composition.
7230 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7231 to insert the raw text of the message being replied to.
7232 It has the form (FUNCTION . ARGS). The user agent will apply
7233 FUNCTION to ARGS, to insert the raw text of the original message.
7234 \(The user agent will also run `mail-citation-hook', *after* the
7235 original text has been inserted in this way.)
7237 SEND-ACTIONS is a list of actions to call when the message is sent.
7238 Each action has the form (FUNCTION . ARGS).
7240 RETURN-ACTION, if non-nil, is an action for returning to the
7241 caller. It has the form (FUNCTION . ARGS). The function is
7242 called after the mail has been sent or put aside, and the mail
7245 (list nil nil nil current-prefix-arg
))
7247 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7248 ;; from sendmail-user-agent to message-user-agent. Some users may
7249 ;; encounter incompatibilities. This hack tries to detect problems
7250 ;; and warn about them.
7251 (and compose-mail-user-agent-warnings
7252 (eq mail-user-agent
'message-user-agent
)
7254 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7255 mail-yank-hooks mail-archive-file-name
7256 mail-default-reply-to mail-mailing-lists
7260 (push var warn-vars
)))
7262 (display-warning 'mail
7264 The default mail mode is now Message mode.
7265 You have the following Mail mode variable%s customized:
7266 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7267 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7268 (if (> (length warn-vars
) 1) "s" "")
7269 (mapconcat 'symbol-name
7272 (let ((function (get mail-user-agent
'composefunc
)))
7273 (funcall function to subject other-headers continue switch-function
7274 yank-action send-actions return-action
)))
7276 (defun compose-mail-other-window (&optional to subject other-headers continue
7277 yank-action send-actions
7279 "Like \\[compose-mail], but edit the outgoing message in another window."
7280 (interactive (list nil nil nil current-prefix-arg
))
7281 (compose-mail to subject other-headers continue
7282 'switch-to-buffer-other-window yank-action send-actions
7285 (defun compose-mail-other-frame (&optional to subject other-headers continue
7286 yank-action send-actions
7288 "Like \\[compose-mail], but edit the outgoing message in another frame."
7289 (interactive (list nil nil nil current-prefix-arg
))
7290 (compose-mail to subject other-headers continue
7291 'switch-to-buffer-other-frame yank-action send-actions
7295 (defvar set-variable-value-history nil
7296 "History of values entered with `set-variable'.
7298 Maximum length of the history list is determined by the value
7299 of `history-length', which see.")
7301 (defun set-variable (variable value
&optional make-local
)
7302 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7303 VARIABLE should be a user option variable name, a Lisp variable
7304 meant to be customized by users. You should enter VALUE in Lisp syntax,
7305 so if you want VALUE to be a string, you must surround it with doublequotes.
7306 VALUE is used literally, not evaluated.
7308 If VARIABLE has a `variable-interactive' property, that is used as if
7309 it were the arg to `interactive' (which see) to interactively read VALUE.
7311 If VARIABLE has been defined with `defcustom', then the type information
7312 in the definition is used to check that VALUE is valid.
7314 Note that this function is at heart equivalent to the basic `set' function.
7315 For a variable defined with `defcustom', it does not pay attention to
7316 any :set property that the variable might have (if you want that, use
7317 \\[customize-set-variable] instead).
7319 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7321 (let* ((default-var (variable-at-point))
7322 (var (if (custom-variable-p default-var
)
7323 (read-variable (format "Set variable (default %s): " default-var
)
7325 (read-variable "Set variable: ")))
7326 (minibuffer-help-form '(describe-variable var
))
7327 (prop (get var
'variable-interactive
))
7328 (obsolete (car (get var
'byte-obsolete-variable
)))
7329 (prompt (format "Set %s %s to value: " var
7330 (cond ((local-variable-p var
)
7332 ((or current-prefix-arg
7333 (local-variable-if-set-p var
))
7338 (message (concat "`%S' is obsolete; "
7339 (if (symbolp obsolete
) "use `%S' instead" "%s"))
7343 ;; Use VAR's `variable-interactive' property
7344 ;; as an interactive spec for prompting.
7345 (call-interactively `(lambda (arg)
7348 (read-from-minibuffer prompt nil
7349 read-expression-map t
7350 'set-variable-value-history
7351 (format "%S" (symbol-value var
)))))))
7352 (list var val current-prefix-arg
)))
7354 (and (custom-variable-p variable
)
7355 (not (get variable
'custom-type
))
7356 (custom-load-symbol variable
))
7357 (let ((type (get variable
'custom-type
)))
7359 ;; Match with custom type.
7361 (setq type
(widget-convert type
))
7362 (unless (widget-apply type
:match value
)
7363 (user-error "Value `%S' does not match type %S of %S"
7364 value
(car type
) variable
))))
7367 (make-local-variable variable
))
7369 (set variable value
)
7371 ;; Force a thorough redisplay for the case that the variable
7372 ;; has an effect on the display, like `tab-width' has.
7373 (force-mode-line-update))
7375 ;; Define the major mode for lists of completions.
7377 (defvar completion-list-mode-map
7378 (let ((map (make-sparse-keymap)))
7379 (define-key map
[mouse-2
] 'choose-completion
)
7380 (define-key map
[follow-link
] 'mouse-face
)
7381 (define-key map
[down-mouse-2
] nil
)
7382 (define-key map
"\C-m" 'choose-completion
)
7383 (define-key map
"\e\e\e" 'delete-completion-window
)
7384 (define-key map
[left] 'previous-completion)
7385 (define-key map [right] 'next-completion)
7386 (define-key map [?\t] 'next-completion)
7387 (define-key map [backtab] 'previous-completion)
7388 (define-key map "q" 'quit-window)
7389 (define-key map "z" 'kill-this-buffer)
7391 "Local map for completion list buffers.")
7393 ;; Completion mode is suitable only for specially formatted data.
7394 (put 'completion-list-mode 'mode-class 'special)
7396 (defvar completion-reference-buffer nil
7397 "Record the buffer that was current when the completion list was requested.
7398 This is a local variable in the completion list buffer.
7399 Initial value is nil to avoid some compiler warnings.")
7401 (defvar completion-no-auto-exit nil
7402 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7403 This also applies to other functions such as `choose-completion'.")
7405 (defvar completion-base-position nil
7406 "Position of the base of the text corresponding to the shown completions.
7407 This variable is used in the *Completions* buffers.
7408 Its value is a list of the form (START END) where START is the place
7409 where the completion should be inserted and END (if non-nil) is the end
7410 of the text to replace. If END is nil, point is used instead.")
7412 (defvar completion-list-insert-choice-function #'completion--replace
7413 "Function to use to insert the text chosen in *Completions*.
7414 Called with three arguments (BEG END TEXT), it should replace the text
7415 between BEG and END with TEXT. Expected to be set buffer-locally
7416 in the *Completions* buffer.")
7418 (defvar completion-base-size nil
7419 "Number of chars before point not involved in completion.
7420 This is a local variable in the completion list buffer.
7421 It refers to the chars in the minibuffer if completing in the
7422 minibuffer, or in `completion-reference-buffer' otherwise.
7423 Only characters in the field at point are included.
7425 If nil, Emacs determines which part of the tail end of the
7426 buffer's text is involved in completion by comparing the text
7428 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7430 (defun delete-completion-window ()
7431 "Delete the completion list window.
7432 Go to the window from which completion was requested."
7434 (let ((buf completion-reference-buffer))
7435 (if (one-window-p t)
7436 (if (window-dedicated-p) (delete-frame))
7437 (delete-window (selected-window))
7438 (if (get-buffer-window buf)
7439 (select-window (get-buffer-window buf))))))
7441 (defun previous-completion (n)
7442 "Move to the previous item in the completion list."
7444 (next-completion (- n)))
7446 (defun next-completion (n)
7447 "Move to the next item in the completion list.
7448 With prefix argument N, move N items (negative N means move backward)."
7450 (let ((beg (point-min)) (end (point-max)))
7451 (while (and (> n 0) (not (eobp)))
7452 ;; If in a completion, move to the end of it.
7453 (when (get-text-property (point) 'mouse-face)
7454 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7455 ;; Move to start of next one.
7456 (unless (get-text-property (point) 'mouse-face)
7457 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7459 (while (and (< n 0) (not (bobp)))
7460 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7461 ;; If in a completion, move to the start of it.
7462 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7463 (goto-char (previous-single-property-change
7464 (point) 'mouse-face nil beg)))
7465 ;; Move to end of the previous completion.
7466 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7467 (goto-char (previous-single-property-change
7468 (point) 'mouse-face nil beg)))
7469 ;; Move to the start of that one.
7470 (goto-char (previous-single-property-change
7471 (point) 'mouse-face nil beg))
7474 (defun choose-completion (&optional event)
7475 "Choose the completion at point.
7476 If EVENT, use EVENT's position to determine the starting position."
7477 (interactive (list last-nonmenu-event))
7478 ;; In case this is run via the mouse, give temporary modes such as
7479 ;; isearch a chance to turn off.
7480 (run-hooks 'mouse-leave-buffer-hook)
7481 (with-current-buffer (window-buffer (posn-window (event-start event)))
7482 (let ((buffer completion-reference-buffer)
7483 (base-size completion-base-size)
7484 (base-position completion-base-position)
7485 (insert-function completion-list-insert-choice-function)
7488 (goto-char (posn-point (event-start event)))
7491 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7492 (setq end (point) beg (1+ (point))))
7494 (get-text-property (1- (point)) 'mouse-face))
7495 (setq end (1- (point)) beg (point)))
7496 (t (error "No completion here")))
7497 (setq beg (previous-single-property-change beg 'mouse-face))
7498 (setq end (or (next-single-property-change end 'mouse-face)
7500 (buffer-substring-no-properties beg end)))))
7502 (unless (buffer-live-p buffer)
7503 (error "Destination buffer is dead"))
7504 (quit-window nil (posn-window (event-start event)))
7506 (with-current-buffer buffer
7507 (choose-completion-string
7511 ;; Someone's using old completion code that doesn't know
7512 ;; about base-position yet.
7513 (list (+ base-size (field-beginning))))
7514 ;; If all else fails, just guess.
7515 (list (choose-completion-guess-base-position choice)))
7516 insert-function)))))
7518 ;; Delete the longest partial match for STRING
7519 ;; that can be found before POINT.
7520 (defun choose-completion-guess-base-position (string)
7522 (let ((opoint (point))
7524 ;; Try moving back by the length of the string.
7525 (goto-char (max (- (point) (length string))
7526 (minibuffer-prompt-end)))
7527 ;; See how far back we were actually able to move. That is the
7528 ;; upper bound on how much we can match and delete.
7529 (setq len (- opoint (point)))
7530 (if completion-ignore-case
7531 (setq string (downcase string)))
7532 (while (and (> len 0)
7533 (let ((tail (buffer-substring (point) opoint)))
7534 (if completion-ignore-case
7535 (setq tail (downcase tail)))
7536 (not (string= tail (substring string 0 len)))))
7541 (defun choose-completion-delete-max-match (string)
7542 (declare (obsolete choose-completion-guess-base-position "23.2"))
7543 (delete-region (choose-completion-guess-base-position string) (point)))
7545 (defvar choose-completion-string-functions nil
7546 "Functions that may override the normal insertion of a completion choice.
7547 These functions are called in order with three arguments:
7548 CHOICE - the string to insert in the buffer,
7549 BUFFER - the buffer in which the choice should be inserted,
7550 BASE-POSITION - where to insert the completion.
7552 If a function in the list returns non-nil, that function is supposed
7553 to have inserted the CHOICE in the BUFFER, and possibly exited
7554 the minibuffer; no further functions will be called.
7556 If all functions in the list return nil, that means to use
7557 the default method of inserting the completion in BUFFER.")
7559 (defun choose-completion-string (choice &optional
7560 buffer base-position insert-function)
7561 "Switch to BUFFER and insert the completion choice CHOICE.
7562 BASE-POSITION says where to insert the completion.
7563 INSERT-FUNCTION says how to insert the completion and falls
7564 back on `completion-list-insert-choice-function' when nil."
7566 ;; If BUFFER is the minibuffer, exit the minibuffer
7567 ;; unless it is reading a file name and CHOICE is a directory,
7568 ;; or completion-no-auto-exit is non-nil.
7570 ;; Some older code may call us passing `base-size' instead of
7571 ;; `base-position'. It's difficult to make any use of `base-size',
7572 ;; so we just ignore it.
7573 (unless (consp base-position)
7574 (message "Obsolete `base-size' passed to choose-completion-string")
7575 (setq base-position nil))
7577 (let* ((buffer (or buffer completion-reference-buffer))
7578 (mini-p (minibufferp buffer)))
7579 ;; If BUFFER is a minibuffer, barf unless it's the currently
7580 ;; active minibuffer.
7582 (not (and (active-minibuffer-window)
7584 (window-buffer (active-minibuffer-window))))))
7585 (error "Minibuffer is not active for completion")
7586 ;; Set buffer so buffer-local choose-completion-string-functions works.
7588 (unless (run-hook-with-args-until-success
7589 'choose-completion-string-functions
7590 ;; The fourth arg used to be `mini-p' but was useless
7591 ;; (since minibufferp can be used on the `buffer' arg)
7592 ;; and indeed unused. The last used to be `base-size', so we
7593 ;; keep it to try and avoid breaking old code.
7594 choice buffer base-position nil)
7595 ;; This remove-text-properties should be unnecessary since `choice'
7596 ;; comes from buffer-substring-no-properties.
7597 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7598 ;; Insert the completion into the buffer where it was requested.
7599 (funcall (or insert-function completion-list-insert-choice-function)
7600 (or (car base-position) (point))
7601 (or (cadr base-position) (point))
7603 ;; Update point in the window that BUFFER is showing in.
7604 (let ((window (get-buffer-window buffer t)))
7605 (set-window-point window (point)))
7606 ;; If completing for the minibuffer, exit it with this choice.
7607 (and (not completion-no-auto-exit)
7608 (minibufferp buffer)
7609 minibuffer-completion-table
7610 ;; If this is reading a file name, and the file name chosen
7611 ;; is a directory, don't exit the minibuffer.
7612 (let* ((result (buffer-substring (field-beginning) (point)))
7614 (completion-boundaries result minibuffer-completion-table
7615 minibuffer-completion-predicate
7617 (if (eq (car bounds) (length result))
7618 ;; The completion chosen leads to a new set of completions
7619 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7620 (let ((mini (active-minibuffer-window)))
7621 (select-window mini)
7622 (when minibuffer-auto-raise
7623 (raise-frame (window-frame mini))))
7624 (exit-minibuffer))))))))
7626 (define-derived-mode completion-list-mode nil "Completion List"
7627 "Major mode for buffers showing lists of possible completions.
7628 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7629 to select the completion near point.
7630 Or click to select one with the mouse.
7632 \\{completion-list-mode-map}"
7633 (set (make-local-variable 'completion-base-size) nil))
7635 (defun completion-list-mode-finish ()
7636 "Finish setup of the completions buffer.
7637 Called from `temp-buffer-show-hook'."
7638 (when (eq major-mode 'completion-list-mode)
7639 (setq buffer-read-only t)))
7641 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7644 ;; Variables and faces used in `completion-setup-function'.
7646 (defcustom completion-show-help t
7647 "Non-nil means show help message in *Completions* buffer."
7652 ;; This function goes in completion-setup-hook, so that it is called
7653 ;; after the text of the completion list buffer is written.
7654 (defun completion-setup-function ()
7655 (let* ((mainbuf (current-buffer))
7657 ;; FIXME: This is a bad hack. We try to set the default-directory
7658 ;; in the *Completions* buffer so that the relative file names
7659 ;; displayed there can be treated as valid file names, independently
7660 ;; from the completion context. But this suffers from many problems:
7661 ;; - It's not clear when the completions are file names. With some
7662 ;; completion tables (e.g. bzr revision specs), the listed
7663 ;; completions can mix file names and other things.
7664 ;; - It doesn't pay attention to possible quoting.
7665 ;; - With fancy completion styles, the code below will not always
7666 ;; find the right base directory.
7667 (if minibuffer-completing-file-name
7668 (file-name-as-directory
7670 (buffer-substring (minibuffer-prompt-end)
7671 (- (point) (or completion-base-size 0))))))))
7672 (with-current-buffer standard-output
7673 (let ((base-size completion-base-size) ;Read before killing localvars.
7674 (base-position completion-base-position)
7675 (insert-fun completion-list-insert-choice-function))
7676 (completion-list-mode)
7677 (set (make-local-variable 'completion-base-size) base-size)
7678 (set (make-local-variable 'completion-base-position) base-position)
7679 (set (make-local-variable 'completion-list-insert-choice-function)
7681 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7682 (if base-dir (setq default-directory base-dir))
7683 ;; Maybe insert help string.
7684 (when completion-show-help
7685 (goto-char (point-min))
7686 (if (display-mouse-p)
7687 (insert (substitute-command-keys
7688 "Click on a completion to select it.\n")))
7689 (insert (substitute-command-keys
7690 "In this buffer, type \\[choose-completion] to \
7691 select the completion near point.\n\n"))))))
7693 (add-hook 'completion-setup-hook 'completion-setup-function)
7695 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7696 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7698 (defun switch-to-completions ()
7699 "Select the completion list window."
7701 (let ((window (or (get-buffer-window "*Completions*" 0)
7702 ;; Make sure we have a completions window.
7703 (progn (minibuffer-completion-help)
7704 (get-buffer-window "*Completions*" 0)))))
7706 (select-window window)
7707 ;; In the new buffer, go to the first completion.
7708 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
7710 (next-completion 1)))))
7712 ;;; Support keyboard commands to turn on various modifiers.
7714 ;; These functions -- which are not commands -- each add one modifier
7715 ;; to the following event.
7717 (defun event-apply-alt-modifier (_ignore-prompt)
7718 "\\<function-key-map>Add the Alt modifier to the following event.
7719 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
7720 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
7721 (defun event-apply-super-modifier (_ignore-prompt)
7722 "\\<function-key-map>Add the Super modifier to the following event.
7723 For example, type \\[event-apply-super-modifier] & to enter Super-&."
7724 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
7725 (defun event-apply-hyper-modifier (_ignore-prompt)
7726 "\\<function-key-map>Add the Hyper modifier to the following event.
7727 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
7728 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
7729 (defun event-apply-shift-modifier (_ignore-prompt)
7730 "\\<function-key-map>Add the Shift modifier to the following event.
7731 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
7732 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
7733 (defun event-apply-control-modifier (_ignore-prompt)
7734 "\\<function-key-map>Add the Ctrl modifier to the following event.
7735 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
7736 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
7737 (defun event-apply-meta-modifier (_ignore-prompt)
7738 "\\<function-key-map>Add the Meta modifier to the following event.
7739 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
7740 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
7742 (defun event-apply-modifier (event symbol lshiftby prefix)
7743 "Apply a modifier flag to event EVENT.
7744 SYMBOL is the name of this modifier, as a symbol.
7745 LSHIFTBY is the numeric value of this modifier, in keyboard events.
7746 PREFIX is the string that represents this modifier in an event type symbol."
7748 (cond ((eq symbol 'control)
7749 (if (and (<= (downcase event) ?z)
7750 (>= (downcase event) ?a))
7751 (- (downcase event) ?a -1)
7752 (if (and (<= (downcase event) ?Z)
7753 (>= (downcase event) ?A))
7754 (- (downcase event) ?A -1)
7755 (logior (lsh 1 lshiftby) event))))
7757 (if (and (<= (downcase event) ?z)
7758 (>= (downcase event) ?a))
7760 (logior (lsh 1 lshiftby) event)))
7762 (logior (lsh 1 lshiftby) event)))
7763 (if (memq symbol (event-modifiers event))
7765 (let ((event-type (if (symbolp event) event (car event))))
7766 (setq event-type (intern (concat prefix (symbol-name event-type))))
7769 (cons event-type (cdr event)))))))
7771 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
7772 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
7773 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
7774 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
7775 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
7776 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
7778 ;;;; Keypad support.
7780 ;; Make the keypad keys act like ordinary typing keys. If people add
7781 ;; bindings for the function key symbols, then those bindings will
7782 ;; override these, so this shouldn't interfere with any existing
7785 ;; Also tell read-char how to handle these keys.
7787 (lambda (keypad-normal)
7788 (let ((keypad (nth 0 keypad-normal))
7789 (normal (nth 1 keypad-normal)))
7790 (put keypad 'ascii-character normal)
7791 (define-key function-key-map (vector keypad) (vector normal))))
7792 ;; See also kp-keys bound in bindings.el.
7798 ;; Do the same for various keys that are represented as symbols under
7799 ;; GUIs but naturally correspond to characters.
7810 ;;;; forking a twin copy of a buffer.
7813 (defvar clone-buffer-hook nil
7814 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
7816 (defvar clone-indirect-buffer-hook nil
7817 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
7819 (defun clone-process (process &optional newname)
7820 "Create a twin copy of PROCESS.
7821 If NEWNAME is nil, it defaults to PROCESS' name;
7822 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
7823 If PROCESS is associated with a buffer, the new process will be associated
7824 with the current buffer instead.
7825 Returns nil if PROCESS has already terminated."
7826 (setq newname (or newname (process-name process)))
7827 (if (string-match "<[0-9]+>\\'" newname)
7828 (setq newname (substring newname 0 (match-beginning 0))))
7829 (when (memq (process-status process) '(run stop open))
7830 (let* ((process-connection-type (process-tty-name process))
7832 (if (memq (process-status process) '(open))
7833 (let ((args (process-contact process t)))
7834 (setq args (plist-put args :name newname))
7835 (setq args (plist-put args :buffer
7836 (if (process-buffer process)
7838 (apply 'make-network-process args))
7839 (apply 'start-process newname
7840 (if (process-buffer process) (current-buffer))
7841 (process-command process)))))
7842 (set-process-query-on-exit-flag
7843 new-process (process-query-on-exit-flag process))
7844 (set-process-inherit-coding-system-flag
7845 new-process (process-inherit-coding-system-flag process))
7846 (set-process-filter new-process (process-filter process))
7847 (set-process-sentinel new-process (process-sentinel process))
7848 (set-process-plist new-process (copy-sequence (process-plist process)))
7851 ;; things to maybe add (currently partly covered by `funcall mode'):
7854 (defun clone-buffer (&optional newname display-flag)
7855 "Create and return a twin copy of the current buffer.
7856 Unlike an indirect buffer, the new buffer can be edited
7857 independently of the old one (if it is not read-only).
7858 NEWNAME is the name of the new buffer. It may be modified by
7859 adding or incrementing <N> at the end as necessary to create a
7860 unique buffer name. If nil, it defaults to the name of the
7861 current buffer, with the proper suffix. If DISPLAY-FLAG is
7862 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
7863 clone a file-visiting buffer, or a buffer whose major mode symbol
7864 has a non-nil `no-clone' property, results in an error.
7866 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
7867 current buffer with appropriate suffix. However, if a prefix
7868 argument is given, then the command prompts for NEWNAME in the
7871 This runs the normal hook `clone-buffer-hook' in the new buffer
7872 after it has been set up properly in other respects."
7875 (if buffer-file-name
7876 (error "Cannot clone a file-visiting buffer"))
7877 (if (get major-mode 'no-clone)
7878 (error "Cannot clone a buffer in %s mode" mode-name))
7879 (list (if current-prefix-arg
7880 (read-buffer "Name of new cloned buffer: " (current-buffer)))
7882 (if buffer-file-name
7883 (error "Cannot clone a file-visiting buffer"))
7884 (if (get major-mode 'no-clone)
7885 (error "Cannot clone a buffer in %s mode" mode-name))
7886 (setq newname (or newname (buffer-name)))
7887 (if (string-match "<[0-9]+>\\'" newname)
7888 (setq newname (substring newname 0 (match-beginning 0))))
7889 (let ((buf (current-buffer))
7893 (mk (if mark-active (mark t)))
7894 (modified (buffer-modified-p))
7896 (lvars (buffer-local-variables))
7897 (process (get-buffer-process (current-buffer)))
7898 (new (generate-new-buffer (or newname (buffer-name)))))
7901 (with-current-buffer new
7902 (insert-buffer-substring buf)))
7903 (with-current-buffer new
7904 (narrow-to-region ptmin ptmax)
7906 (if mk (set-mark mk))
7907 (set-buffer-modified-p modified)
7909 ;; Clone the old buffer's process, if any.
7910 (when process (clone-process process))
7912 ;; Now set up the major mode.
7915 ;; Set up other local variables.
7917 (condition-case () ;in case var is read-only
7920 (set (make-local-variable (car v)) (cdr v)))
7924 ;; Run any hooks (typically set up by the major mode
7925 ;; for cloning to work properly).
7926 (run-hooks 'clone-buffer-hook))
7928 ;; Presumably the current buffer is shown in the selected frame, so
7929 ;; we want to display the clone elsewhere.
7930 (let ((same-window-regexps nil)
7931 (same-window-buffer-names))
7932 (pop-to-buffer new)))
7936 (defun clone-indirect-buffer (newname display-flag &optional norecord)
7937 "Create an indirect buffer that is a twin copy of the current buffer.
7939 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
7940 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
7941 or if not called with a prefix arg, NEWNAME defaults to the current
7942 buffer's name. The name is modified by adding a `<N>' suffix to it
7943 or by incrementing the N in an existing suffix. Trying to clone a
7944 buffer whose major mode symbol has a non-nil `no-clone-indirect'
7945 property results in an error.
7947 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7948 This is always done when called interactively.
7950 Optional third arg NORECORD non-nil means do not put this buffer at the
7951 front of the list of recently selected ones.
7953 Returns the newly created indirect buffer."
7956 (if (get major-mode 'no-clone-indirect)
7957 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7958 (list (if current-prefix-arg
7959 (read-buffer "Name of indirect buffer: " (current-buffer)))
7961 (if (get major-mode 'no-clone-indirect)
7962 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7963 (setq newname (or newname (buffer-name)))
7964 (if (string-match "<[0-9]+>\\'" newname)
7965 (setq newname (substring newname 0 (match-beginning 0))))
7966 (let* ((name (generate-new-buffer-name newname))
7967 (buffer (make-indirect-buffer (current-buffer) name t)))
7968 (with-current-buffer buffer
7969 (run-hooks 'clone-indirect-buffer-hook))
7971 (pop-to-buffer buffer norecord))
7975 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
7976 "Like `clone-indirect-buffer' but display in another window."
7979 (if (get major-mode 'no-clone-indirect)
7980 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7981 (list (if current-prefix-arg
7982 (read-buffer "Name of indirect buffer: " (current-buffer)))
7984 (let ((pop-up-windows t))
7985 (clone-indirect-buffer newname display-flag norecord)))
7988 ;;; Handling of Backspace and Delete keys.
7990 (defcustom normal-erase-is-backspace 'maybe
7991 "Set the default behavior of the Delete and Backspace keys.
7993 If set to t, Delete key deletes forward and Backspace key deletes
7996 If set to nil, both Delete and Backspace keys delete backward.
7998 If set to 'maybe (which is the default), Emacs automatically
7999 selects a behavior. On window systems, the behavior depends on
8000 the keyboard used. If the keyboard has both a Backspace key and
8001 a Delete key, and both are mapped to their usual meanings, the
8002 option's default value is set to t, so that Backspace can be used
8003 to delete backward, and Delete can be used to delete forward.
8005 If not running under a window system, customizing this option
8006 accomplishes a similar effect by mapping C-h, which is usually
8007 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8008 via `keyboard-translate'. The former functionality of C-h is
8009 available on the F1 key. You should probably not use this
8010 setting if you don't have both Backspace, Delete and F1 keys.
8012 Setting this variable with setq doesn't take effect. Programmatically,
8013 call `normal-erase-is-backspace-mode' (which see) instead."
8014 :type '(choice (const :tag "Off" nil)
8015 (const :tag "Maybe" maybe)
8016 (other :tag "On" t))
8017 :group 'editing-basics
8019 :set (lambda (symbol value)
8020 ;; The fboundp is because of a problem with :set when
8021 ;; dumping Emacs. It doesn't really matter.
8022 (if (fboundp 'normal-erase-is-backspace-mode)
8023 (normal-erase-is-backspace-mode (or value 0))
8024 (set-default symbol value))))
8026 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8027 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8028 (unless frame (setq frame (selected-frame)))
8029 (with-selected-frame frame
8030 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8031 (normal-erase-is-backspace-mode
8032 (if (if (eq normal-erase-is-backspace 'maybe)
8033 (and (not noninteractive)
8034 (or (memq system-type '(ms-dos windows-nt))
8035 (memq window-system '(w32 ns))
8036 (and (memq window-system '(x))
8037 (fboundp 'x-backspace-delete-keys-p)
8038 (x-backspace-delete-keys-p))
8039 ;; If the terminal Emacs is running on has erase char
8040 ;; set to ^H, use the Backspace key for deleting
8041 ;; backward, and the Delete key for deleting forward.
8042 (and (null window-system)
8043 (eq tty-erase-char ?\^H))))
8044 normal-erase-is-backspace)
8047 (define-minor-mode normal-erase-is-backspace-mode
8048 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8049 With a prefix argument ARG, enable this feature if ARG is
8050 positive, and disable it otherwise. If called from Lisp, enable
8051 the mode if ARG is omitted or nil.
8053 On window systems, when this mode is on, Delete is mapped to C-d
8054 and Backspace is mapped to DEL; when this mode is off, both
8055 Delete and Backspace are mapped to DEL. (The remapping goes via
8056 `local-function-key-map', so binding Delete or Backspace in the
8057 global or local keymap will override that.)
8059 In addition, on window systems, the bindings of C-Delete, M-Delete,
8060 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8061 the global keymap in accordance with the functionality of Delete and
8062 Backspace. For example, if Delete is remapped to C-d, which deletes
8063 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8064 to DEL, which deletes backward, C-Delete is bound to
8065 `backward-kill-word'.
8067 If not running on a window system, a similar effect is accomplished by
8068 remapping C-h (normally produced by the Backspace key) and DEL via
8069 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8070 to C-d; if it's off, the keys are not remapped.
8072 When not running on a window system, and this mode is turned on, the
8073 former functionality of C-h is available on the F1 key. You should
8074 probably not turn on this mode on a text-only terminal if you don't
8075 have both Backspace, Delete and F1 keys.
8077 See also `normal-erase-is-backspace'."
8078 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8080 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8082 (let ((enabled (eq 1 (terminal-parameter
8083 nil 'normal-erase-is-backspace))))
8085 (cond ((or (memq window-system '(x w32 ns pc))
8086 (memq system-type '(ms-dos windows-nt)))
8088 `(([M-delete] [M-backspace])
8089 ([C-M-delete] [C-M-backspace])
8090 ([?\e C-delete] [?\e C-backspace]))))
8094 (define-key local-function-key-map [delete] [deletechar])
8095 (define-key local-function-key-map [kp-delete] [deletechar])
8096 (define-key local-function-key-map [backspace] [?\C-?])
8097 (dolist (b bindings)
8098 ;; Not sure if input-decode-map is really right, but
8099 ;; keyboard-translate-table (used below) only works
8100 ;; for integer events, and key-translation-table is
8101 ;; global (like the global-map, used earlier).
8102 (define-key input-decode-map (car b) nil)
8103 (define-key input-decode-map (cadr b) nil)))
8104 (define-key local-function-key-map [delete] [?\C-?])
8105 (define-key local-function-key-map [kp-delete] [?\C-?])
8106 (define-key local-function-key-map [backspace] [?\C-?])
8107 (dolist (b bindings)
8108 (define-key input-decode-map (car b) (cadr b))
8109 (define-key input-decode-map (cadr b) (car b))))))
8113 (keyboard-translate ?\C-h ?\C-?)
8114 (keyboard-translate ?\C-? ?\C-d))
8115 (keyboard-translate ?\C-h ?\C-h)
8116 (keyboard-translate ?\C-? ?\C-?))))
8118 (if (called-interactively-p 'interactive)
8119 (message "Delete key deletes %s"
8120 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8121 "forward" "backward")))))
8123 (defvar vis-mode-saved-buffer-invisibility-spec nil
8124 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8126 (define-minor-mode read-only-mode
8127 "Change whether the current buffer is read-only.
8128 With prefix argument ARG, make the buffer read-only if ARG is
8129 positive, otherwise make it writable. If buffer is read-only
8130 and `view-read-only' is non-nil, enter view mode.
8132 Do not call this from a Lisp program unless you really intend to
8133 do the same thing as the \\[read-only-mode] command, including
8134 possibly enabling or disabling View mode. Also, note that this
8135 command works by setting the variable `buffer-read-only', which
8136 does not affect read-only regions caused by text properties. To
8137 ignore read-only status in a Lisp program (whether due to text
8138 properties or buffer state), bind `inhibit-read-only' temporarily
8139 to a non-nil value."
8140 :variable buffer-read-only
8142 ((and (not buffer-read-only) view-mode)
8143 (View-exit-and-edit)
8144 (make-local-variable 'view-read-only)
8145 (setq view-read-only t)) ; Must leave view mode.
8146 ((and buffer-read-only view-read-only
8147 ;; If view-mode is already active, `view-mode-enter' is a nop.
8149 (not (eq (get major-mode 'mode-class) 'special)))
8150 (view-mode-enter))))
8152 (define-minor-mode visible-mode
8153 "Toggle making all invisible text temporarily visible (Visible mode).
8154 With a prefix argument ARG, enable Visible mode if ARG is
8155 positive, and disable it otherwise. If called from Lisp, enable
8156 the mode if ARG is omitted or nil.
8158 This mode works by saving the value of `buffer-invisibility-spec'
8159 and setting it to nil."
8161 :group 'editing-basics
8162 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8163 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8164 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8166 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8167 buffer-invisibility-spec)
8168 (setq buffer-invisibility-spec nil)))
8170 (defvar messages-buffer-mode-map
8171 (let ((map (make-sparse-keymap)))
8172 (set-keymap-parent map special-mode-map)
8173 (define-key map "g" nil) ; nothing to revert
8176 (define-derived-mode messages-buffer-mode special-mode "Messages"
8177 "Major mode used in the \"*Messages*\" buffer.")
8179 (defun messages-buffer ()
8180 "Return the \"*Messages*\" buffer.
8181 If it does not exist, create and it switch it to `messages-buffer-mode'."
8182 (or (get-buffer "*Messages*")
8183 (with-current-buffer (get-buffer-create "*Messages*")
8184 (messages-buffer-mode)
8188 ;; Minibuffer prompt stuff.
8190 ;;(defun minibuffer-prompt-modification (start end)
8191 ;; (error "You cannot modify the prompt"))
8194 ;;(defun minibuffer-prompt-insertion (start end)
8195 ;; (let ((inhibit-modification-hooks t))
8196 ;; (delete-region start end)
8197 ;; ;; Discard undo information for the text insertion itself
8198 ;; ;; and for the text deletion.above.
8199 ;; (when (consp buffer-undo-list)
8200 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8201 ;; (message "You cannot modify the prompt")))
8204 ;;(setq minibuffer-prompt-properties
8205 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8206 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8209 ;;;; Problematic external packages.
8211 ;; rms says this should be done by specifying symbols that define
8212 ;; versions together with bad values. This is therefore not as
8213 ;; flexible as it could be. See the thread:
8214 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8215 (defconst bad-packages-alist
8216 ;; Not sure exactly which semantic versions have problems.
8217 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8218 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8219 "The version of `semantic' loaded does not work in Emacs 22.
8220 It can cause constant high CPU load.
8221 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8222 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8223 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8224 ;; provided the `CUA-mode' feature. Since this is no longer true,
8225 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8227 "CUA-mode is now part of the standard GNU Emacs distribution,
8228 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8230 You have loaded an older version of CUA-mode which does not work
8231 correctly with this version of Emacs. You should remove the old
8232 version and use the one distributed with Emacs."))
8233 "Alist of packages known to cause problems in this version of Emacs.
8234 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8235 PACKAGE is either a regular expression to match file names, or a
8236 symbol (a feature name), like for `with-eval-after-load'.
8237 SYMBOL is either the name of a string variable, or t. Upon
8238 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8239 warning using STRING as the message.")
8241 (defun bad-package-check (package)
8242 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8244 (let* ((list (assoc package bad-packages-alist))
8245 (symbol (nth 1 list)))
8249 (and (stringp (setq symbol (eval symbol)))
8250 (string-match-p (nth 2 list) symbol)))
8251 (display-warning package (nth 3 list) :warning)))
8254 (dolist (elem bad-packages-alist)
8255 (let ((pkg (car elem)))
8256 (with-eval-after-load pkg
8257 (bad-package-check pkg))))
8260 ;;; Generic dispatcher commands
8262 ;; Macro `define-alternatives' is used to create generic commands.
8263 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8264 ;; that can have different alternative implementations where choosing
8265 ;; among them is exclusively a matter of user preference.
8267 ;; (define-alternatives COMMAND) creates a new interactive command
8268 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8269 ;; Typically, the user will not need to customize this variable; packages
8270 ;; wanting to add alternative implementations should use
8272 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8274 (defmacro define-alternatives (command &rest customizations)
8275 "Define the new command `COMMAND'.
8277 The argument `COMMAND' should be a symbol.
8279 Running `M-x COMMAND RET' for the first time prompts for which
8280 alternative to use and records the selected command as a custom
8283 Running `C-u M-x COMMAND RET' prompts again for an alternative
8284 and overwrites the previous choice.
8286 The variable `COMMAND-alternatives' contains an alist with
8287 alternative implementations of COMMAND. `define-alternatives'
8288 does not have any effect until this variable is set.
8290 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8291 `defcustom' keywords and values to add to the declaration of
8292 `COMMAND-alternatives' (typically :group and :version)."
8293 (let* ((command-name (symbol-name command))
8294 (varalt-name (concat command-name "-alternatives"))
8295 (varalt-sym (intern varalt-name))
8296 (varimp-sym (intern (concat command-name "--implementation"))))
8299 (defcustom ,varalt-sym nil
8300 ,(format "Alist of alternative implementations for the `%s' command.
8302 Each entry must be a pair (ALTNAME . ALTFUN), where:
8303 ALTNAME - The name shown at user to describe the alternative implementation.
8304 ALTFUN - The function called to implement this alternative."
8306 :type '(alist :key-type string :value-type function)
8309 (put ',varalt-sym 'definition-name ',command)
8310 (defvar ,varimp-sym nil "Internal use only.")
8312 (defun ,command (&optional arg)
8313 ,(format "Run generic command `%s'.
8314 If used for the first time, or with interactive ARG, ask the user which
8315 implementation to use for `%s'. The variable `%s'
8316 contains the list of implementations currently supported for this command."
8317 command-name command-name varalt-name)
8319 (when (or arg (null ,varimp-sym))
8320 (let ((val (completing-read
8321 ,(format "Select implementation for command `%s': "
8323 ,varalt-sym nil t)))
8324 (unless (string-equal val "")
8325 (when (null ,varimp-sym)
8327 "Use `C-u M-x %s RET' to select another implementation"
8330 (customize-save-variable ',varimp-sym
8331 (cdr (assoc-string val ,varalt-sym))))))
8333 (call-interactively ,varimp-sym)
8334 (message ,(format "No implementation selected for command `%s'"
8341 ;;; simple.el ends here