1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2018 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 <https://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 shell-command-dont-erase-buffer nil
41 "If non-nil, output buffer is not erased between shell commands.
42 Also, a non-nil value sets the point in the output buffer
43 once the command completes.
44 The value `beg-last-out' sets point at the beginning of the output,
45 `end-last-out' sets point at the end of the buffer, `save-point'
46 restores the buffer position before the command."
48 (const :tag
"Erase buffer" nil
)
49 (const :tag
"Set point to beginning of last output" beg-last-out
)
50 (const :tag
"Set point to end of last output" end-last-out
)
51 (const :tag
"Save point" save-point
))
55 (defvar shell-command-saved-pos nil
56 "Record of point positions in output buffers after command completion.
57 The value is an alist whose elements are of the form (BUFFER . POS),
58 where BUFFER is the output buffer, and POS is the point position
59 in BUFFER once the command finishes.
60 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
62 (defcustom idle-update-delay
0.5
63 "Idle time delay before updating various things on the screen.
64 Various Emacs features that update auxiliary information when point moves
65 wait this many seconds after Emacs becomes idle before doing an update."
71 "Killing and yanking commands."
74 (defgroup paren-matching nil
75 "Highlight (un)matching of parens and expressions."
78 ;;; next-error support framework
80 (defgroup next-error nil
81 "`next-error' support framework."
86 '((t (:inherit region
)))
87 "Face used to highlight next error locus."
91 (defcustom next-error-highlight
0.5
92 "Highlighting of locations in selected source buffers.
93 If a number, highlight the locus in `next-error' face for the given time
94 in seconds, or until the next command is executed.
95 If t, highlight the locus until the next command is executed, or until
96 some other locus replaces it.
97 If nil, don't highlight the locus in the source buffer.
98 If `fringe-arrow', indicate the locus by the fringe arrow
99 indefinitely until some other locus replaces it."
100 :type
'(choice (number :tag
"Highlight for specified time")
101 (const :tag
"Semipermanent highlighting" t
)
102 (const :tag
"No highlighting" nil
)
103 (const :tag
"Fringe arrow" fringe-arrow
))
107 (defcustom next-error-highlight-no-select
0.5
108 "Highlighting of locations in `next-error-no-select'.
109 If number, highlight the locus in `next-error' face for given time in seconds.
110 If t, highlight the locus indefinitely until some other locus replaces it.
111 If nil, don't highlight the locus in the source buffer.
112 If `fringe-arrow', indicate the locus by the fringe arrow
113 indefinitely until some other locus replaces it."
114 :type
'(choice (number :tag
"Highlight for specified time")
115 (const :tag
"Semipermanent highlighting" t
)
116 (const :tag
"No highlighting" nil
)
117 (const :tag
"Fringe arrow" fringe-arrow
))
121 (defcustom next-error-recenter nil
122 "Display the line in the visited source file recentered as specified.
123 If non-nil, the value is passed directly to `recenter'."
124 :type
'(choice (integer :tag
"Line to recenter to")
125 (const :tag
"Center of window" (4))
126 (const :tag
"No recentering" nil
))
130 (defcustom next-error-hook nil
131 "List of hook functions run by `next-error' after visiting source file."
135 (defvar next-error-highlight-timer nil
)
137 (defvar next-error-overlay-arrow-position nil
)
138 (put 'next-error-overlay-arrow-position
'overlay-arrow-string
(purecopy "=>"))
139 (add-to-list 'overlay-arrow-variable-list
'next-error-overlay-arrow-position
)
141 (defvar next-error-last-buffer nil
142 "The most recent `next-error' buffer.
143 A buffer becomes most recent when its compilation, grep, or
144 similar mode is started, or when it is used with \\[next-error]
145 or \\[compile-goto-error].")
147 (defvar next-error-function nil
148 "Function to use to find the next error in the current buffer.
149 The function is called with 2 parameters:
150 ARG is an integer specifying by how many errors to move.
151 RESET is a boolean which, if non-nil, says to go back to the beginning
152 of the errors before moving.
153 Major modes providing compile-like functionality should set this variable
154 to indicate to `next-error' that this is a candidate buffer and how
156 (make-variable-buffer-local 'next-error-function
)
158 (defvar next-error-move-function nil
159 "Function to use to move to an error locus.
160 It takes two arguments, a buffer position in the error buffer
161 and a buffer position in the error locus buffer.
162 The buffer for the error locus should already be current.
163 nil means use goto-char using the second argument position.")
164 (make-variable-buffer-local 'next-error-move-function
)
166 (defsubst next-error-buffer-p
(buffer
167 &optional avoid-current
169 extra-test-exclusive
)
170 "Return non-nil if BUFFER is a `next-error' capable buffer.
171 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
174 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
175 BUFFER would not normally qualify. If it returns non-nil, BUFFER
176 is considered `next-error' capable, anyway, and the function
179 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
180 buffer would normally qualify. If it returns nil, BUFFER is
181 rejected, and the function returns nil."
182 (and (buffer-name buffer
) ;First make sure it's live.
183 (not (and avoid-current
(eq buffer
(current-buffer))))
184 (with-current-buffer buffer
185 (if next-error-function
; This is the normal test.
186 ;; Optionally reject some buffers.
187 (if extra-test-exclusive
188 (funcall extra-test-exclusive
)
190 ;; Optionally accept some other buffers.
191 (and extra-test-inclusive
192 (funcall extra-test-inclusive
))))))
194 (defun next-error-find-buffer (&optional avoid-current
196 extra-test-exclusive
)
197 "Return a `next-error' capable buffer.
199 If AVOID-CURRENT is non-nil, treat the current buffer
200 as an absolute last resort only.
202 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
203 that normally would not qualify. If it returns t, the buffer
204 in question is treated as usable.
206 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
207 that would normally be considered usable. If it returns nil,
208 that buffer is rejected."
210 ;; 1. If one window on the selected frame displays such buffer, return it.
211 (let ((window-buffers
213 (delq nil
(mapcar (lambda (w)
214 (if (next-error-buffer-p
217 extra-test-inclusive extra-test-exclusive
)
220 (if (eq (length window-buffers
) 1)
221 (car window-buffers
)))
222 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
223 (if (and next-error-last-buffer
224 (next-error-buffer-p next-error-last-buffer avoid-current
225 extra-test-inclusive extra-test-exclusive
))
226 next-error-last-buffer
)
227 ;; 3. If the current buffer is acceptable, choose it.
228 (if (next-error-buffer-p (current-buffer) avoid-current
229 extra-test-inclusive extra-test-exclusive
)
231 ;; 4. Look for any acceptable buffer.
232 (let ((buffers (buffer-list)))
234 (not (next-error-buffer-p
235 (car buffers
) avoid-current
236 extra-test-inclusive extra-test-exclusive
)))
237 (setq buffers
(cdr buffers
)))
239 ;; 5. Use the current buffer as a last resort if it qualifies,
240 ;; even despite AVOID-CURRENT.
242 (next-error-buffer-p (current-buffer) nil
243 extra-test-inclusive extra-test-exclusive
)
245 (message "This is the only buffer with error message locations")
248 (error "No buffers contain error message locations")))
250 (defun next-error (&optional arg reset
)
251 "Visit next `next-error' message and corresponding source code.
253 If all the error messages parsed so far have been processed already,
254 the message buffer is checked for new ones.
256 A prefix ARG specifies how many error messages to move;
257 negative means move back to previous error messages.
258 Just \\[universal-argument] as a prefix means reparse the error message buffer
259 and start at the first error.
261 The RESET argument specifies that we should restart from the beginning.
263 \\[next-error] normally uses the most recently started
264 compilation, grep, or occur buffer. It can also operate on any
265 buffer with output from the \\[compile], \\[grep] commands, or,
266 more generally, on any buffer in Compilation mode or with
267 Compilation Minor mode enabled, or any buffer in which
268 `next-error-function' is bound to an appropriate function.
269 To specify use of a particular buffer for error messages, type
270 \\[next-error] in that buffer when it is the only one displayed
271 in the current frame.
273 Once \\[next-error] has chosen the buffer for error messages, it
274 runs `next-error-hook' with `run-hooks', and stays with that buffer
275 until you use it in some other buffer which uses Compilation mode
276 or Compilation Minor mode.
278 To control which errors are matched, customize the variable
279 `compilation-error-regexp-alist'."
281 (if (consp arg
) (setq reset t arg nil
))
282 (when (setq next-error-last-buffer
(next-error-find-buffer))
283 ;; we know here that next-error-function is a valid symbol we can funcall
284 (with-current-buffer next-error-last-buffer
285 (funcall next-error-function
(prefix-numeric-value arg
) reset
)
286 (when next-error-recenter
287 (recenter next-error-recenter
))
288 (run-hooks 'next-error-hook
))))
290 (defun next-error-internal ()
291 "Visit the source code corresponding to the `next-error' message at point."
292 (setq next-error-last-buffer
(current-buffer))
293 ;; we know here that next-error-function is a valid symbol we can funcall
294 (with-current-buffer next-error-last-buffer
295 (funcall next-error-function
0 nil
)
296 (when next-error-recenter
297 (recenter next-error-recenter
))
298 (run-hooks 'next-error-hook
)))
300 (defalias 'goto-next-locus
'next-error
)
301 (defalias 'next-match
'next-error
)
303 (defun previous-error (&optional n
)
304 "Visit previous `next-error' message and corresponding source code.
306 Prefix arg N says how many error messages to move backwards (or
307 forwards, if negative).
309 This operates on the output from the \\[compile] and \\[grep] commands."
311 (next-error (- (or n
1))))
313 (defun first-error (&optional n
)
314 "Restart at the first error.
315 Visit corresponding source code.
316 With prefix arg N, visit the source code of the Nth error.
317 This operates on the output from the \\[compile] command, for instance."
321 (defun next-error-no-select (&optional n
)
322 "Move point to the next error in the `next-error' buffer and highlight match.
323 Prefix arg N says how many error messages to move forwards (or
324 backwards, if negative).
325 Finds and highlights the source line like \\[next-error], but does not
326 select the source buffer."
328 (let ((next-error-highlight next-error-highlight-no-select
))
330 (pop-to-buffer next-error-last-buffer
))
332 (defun previous-error-no-select (&optional n
)
333 "Move point to the previous error in the `next-error' buffer and highlight match.
334 Prefix arg N says how many error messages to move backwards (or
335 forwards, if negative).
336 Finds and highlights the source line like \\[previous-error], but does not
337 select the source buffer."
339 (next-error-no-select (- (or n
1))))
341 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
342 (defvar next-error-follow-last-line nil
)
344 (define-minor-mode next-error-follow-minor-mode
345 "Minor mode for compilation, occur and diff modes.
346 With a prefix argument ARG, enable mode if ARG is positive, and
347 disable it otherwise. If called from Lisp, enable mode if ARG is
349 When turned on, cursor motion in the compilation, grep, occur or diff
350 buffer causes automatic display of the corresponding source code location."
351 :group
'next-error
:init-value nil
:lighter
" Fol"
352 (if (not next-error-follow-minor-mode
)
353 (remove-hook 'post-command-hook
'next-error-follow-mode-post-command-hook t
)
354 (add-hook 'post-command-hook
'next-error-follow-mode-post-command-hook nil t
)
355 (make-local-variable 'next-error-follow-last-line
)))
357 ;; Used as a `post-command-hook' by `next-error-follow-mode'
358 ;; for the *Compilation* *grep* and *Occur* buffers.
359 (defun next-error-follow-mode-post-command-hook ()
360 (unless (equal next-error-follow-last-line
(line-number-at-pos))
361 (setq next-error-follow-last-line
(line-number-at-pos))
363 (let ((compilation-context-lines nil
))
364 (setq compilation-current-error
(point))
365 (next-error-no-select 0))
371 (defun fundamental-mode ()
372 "Major mode not specialized for anything in particular.
373 Other major modes are defined by comparison with this one."
375 (kill-all-local-variables)
378 ;; Special major modes to view specially formatted data rather than files.
380 (defvar special-mode-map
381 (let ((map (make-sparse-keymap)))
382 (suppress-keymap map
)
383 (define-key map
"q" 'quit-window
)
384 (define-key map
" " 'scroll-up-command
)
385 (define-key map
[?\S-\
] 'scroll-down-command
)
386 (define-key map
"\C-?" 'scroll-down-command
)
387 (define-key map
"?" 'describe-mode
)
388 (define-key map
"h" 'describe-mode
)
389 (define-key map
">" 'end-of-buffer
)
390 (define-key map
"<" 'beginning-of-buffer
)
391 (define-key map
"g" 'revert-buffer
)
394 (put 'special-mode
'mode-class
'special
)
395 (define-derived-mode special-mode nil
"Special"
396 "Parent major mode from which special major modes should inherit."
397 (setq buffer-read-only t
))
399 ;; Making and deleting lines.
401 (defvar self-insert-uses-region-functions nil
402 "Special hook to tell if `self-insert-command' will use the region.
403 It must be called via `run-hook-with-args-until-success' with no arguments.
405 If any function on this hook returns a non-nil value, `delete-selection-mode'
406 will act on that value (see `delete-selection-helper'), and will
407 usually delete the region. If all the functions on this hook return
408 nil, it is an indiction that `self-insert-command' needs the region
409 untouched by `delete-selection-mode', and will itself do whatever is
410 appropriate with the region.
411 Any function on `post-self-insert-hook' which act on the region should
412 add a function to this hook so that `delete-selection-mode' could
413 refrain from deleting the region before `post-self-insert-hook'
414 functions are called.
415 This hook is run by `delete-selection-uses-region-p', which see.")
417 (defvar hard-newline
(propertize "\n" 'hard t
'rear-nonsticky
'(hard))
418 "Propertized string representing a hard newline character.")
420 (defun newline (&optional arg interactive
)
421 "Insert a newline, and move to left margin of the new line if it's blank.
422 If option `use-hard-newlines' is non-nil, the newline is marked with the
423 text-property `hard'.
424 With ARG, insert that many newlines.
426 If `electric-indent-mode' is enabled, this indents the final new line
427 that it adds, and reindents the preceding line. To just insert
428 a newline, use \\[electric-indent-just-newline].
430 Calls `auto-fill-function' if the current column number is greater
431 than the value of `fill-column' and ARG is nil.
432 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
433 (interactive "*P\np")
434 (barf-if-buffer-read-only)
435 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
436 ;; Set last-command-event to tell self-insert what to insert.
437 (let* ((was-page-start (and (bolp) (looking-at page-delimiter
)))
439 (last-command-event ?
\n)
440 ;; Don't auto-fill if we have a numeric argument.
441 (auto-fill-function (if arg nil auto-fill-function
))
442 (arg (prefix-numeric-value arg
))
444 ;; Do the rest in post-self-insert-hook, because we want to do it
445 ;; *before* other functions on that hook.
447 ;; Mark the newline(s) `hard'.
448 (if use-hard-newlines
449 (set-hard-newline-properties
450 (- (point) arg
) (point)))
451 ;; If the newline leaves the previous line blank, and we
452 ;; have a left margin, delete that from the blank line.
454 (goto-char beforepos
)
456 (and (looking-at "[ \t]$")
457 (> (current-left-margin) 0)
458 (delete-region (point)
459 (line-end-position))))
460 ;; Indent the line after the newline, except in one case:
461 ;; when we added the newline at the beginning of a line which
464 (move-to-left-margin nil t
)))))
465 (if (not interactive
)
466 ;; FIXME: For non-interactive uses, many calls actually
467 ;; just want (insert "\n"), so maybe we should do just
468 ;; that, so as to avoid the risk of filling or running
469 ;; abbrevs unexpectedly.
470 (let ((post-self-insert-hook (list postproc
)))
471 (self-insert-command arg
))
474 (add-hook 'post-self-insert-hook postproc nil t
)
475 (self-insert-command arg
))
476 ;; We first used let-binding to protect the hook, but that
477 ;; was naive since add-hook affects the symbol-default
478 ;; value of the variable, whereas the let-binding might
479 ;; only protect the buffer-local value.
480 (remove-hook 'post-self-insert-hook postproc t
))))
483 (defun set-hard-newline-properties (from to
)
484 (let ((sticky (get-text-property from
'rear-nonsticky
)))
485 (put-text-property from to
'hard
't
)
486 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
487 (if (and (listp sticky
) (not (memq 'hard sticky
)))
488 (put-text-property from
(point) 'rear-nonsticky
489 (cons 'hard sticky
)))))
492 "Insert a newline and leave point before it.
493 If there is a fill prefix and/or a `left-margin', insert them on
494 the new line if the line would have been blank.
495 With arg N, insert N newlines."
497 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
498 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
500 ;; Don't expand an abbrev before point.
506 (if do-left-margin
(indent-to (current-left-margin)))
507 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
511 ;; Necessary in case a margin or prefix was inserted.
514 (defun split-line (&optional arg
)
515 "Split current line, moving portion beyond point vertically down.
516 If the current line starts with `fill-prefix', insert it on the new
517 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
519 When called from Lisp code, ARG may be a prefix string to copy."
521 (skip-chars-forward " \t")
522 (let* ((col (current-column))
524 ;; What prefix should we check for (nil means don't).
525 (prefix (cond ((stringp arg
) arg
)
528 ;; Does this line start with it?
529 (have-prfx (and prefix
532 (looking-at (regexp-quote prefix
))))))
534 (if have-prfx
(insert-and-inherit prefix
))
538 (defun delete-indentation (&optional arg
)
539 "Join this line to previous and fix up whitespace at join.
540 If there is a fill prefix, delete it from the beginning of this line.
541 With argument, join this line to following line."
544 (if arg
(forward-line 1))
545 (if (eq (preceding-char) ?
\n)
547 (delete-region (point) (1- (point)))
548 ;; If the second line started with the fill prefix,
549 ;; delete the prefix.
551 (<= (+ (point) (length fill-prefix
)) (point-max))
553 (buffer-substring (point)
554 (+ (point) (length fill-prefix
)))))
555 (delete-region (point) (+ (point) (length fill-prefix
))))
556 (fixup-whitespace))))
558 (defalias 'join-line
#'delete-indentation
) ; easier to find
560 (defun delete-blank-lines ()
561 "On blank line, delete all surrounding blank lines, leaving just one.
562 On isolated blank line, delete that one.
563 On nonblank line, delete any immediately following blank lines."
565 (let (thisblank singleblank
)
568 (setq thisblank
(looking-at "[ \t]*$"))
569 ;; Set singleblank if there is just one blank line here.
572 (not (looking-at "[ \t]*\n[ \t]*$"))
574 (progn (forward-line -
1)
575 (not (looking-at "[ \t]*$")))))))
576 ;; Delete preceding blank lines, and this one too if it's the only one.
580 (if singleblank
(forward-line 1))
581 (delete-region (point)
582 (if (re-search-backward "[^ \t\n]" nil t
)
583 (progn (forward-line 1) (point))
585 ;; Delete following blank lines, unless the current line is blank
586 ;; and there are no following blank lines.
587 (if (not (and thisblank singleblank
))
591 (delete-region (point)
592 (if (re-search-forward "[^ \t\n]" nil t
)
593 (progn (beginning-of-line) (point))
595 ;; Handle the special case where point is followed by newline and eob.
596 ;; Delete the line, leaving point at eob.
597 (if (looking-at "^[ \t]*\n\\'")
598 (delete-region (point) (point-max)))))
600 (defcustom delete-trailing-lines t
601 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
602 Trailing lines are deleted only if `delete-trailing-whitespace'
603 is called on the entire buffer (rather than an active region)."
608 (defun region-modifiable-p (start end
)
609 "Return non-nil if the region contains no read-only text."
610 (and (not (get-text-property start
'read-only
))
611 (eq end
(next-single-property-change start
'read-only nil end
))))
613 (defun delete-trailing-whitespace (&optional start end
)
614 "Delete trailing whitespace between START and END.
615 If called interactively, START and END are the start/end of the
616 region if the mark is active, or of the buffer's accessible
617 portion if the mark is inactive.
619 This command deletes whitespace characters after the last
620 non-whitespace character in each line between START and END. It
621 does not consider formfeed characters to be whitespace.
623 If this command acts on the entire buffer (i.e. if called
624 interactively with the mark inactive, or called from Lisp with
625 END nil), it also deletes all trailing lines at the end of the
626 buffer if the variable `delete-trailing-lines' is non-nil."
628 (barf-if-buffer-read-only)
630 (list (region-beginning) (region-end))
634 (let ((end-marker (and end
(copy-marker end
))))
635 (goto-char (or start
(point-min)))
636 (with-syntax-table (make-syntax-table (syntax-table))
637 ;; Don't delete formfeeds, even if they are considered whitespace.
638 (modify-syntax-entry ?
\f "_")
639 (while (re-search-forward "\\s-$" end-marker t
)
640 (skip-syntax-backward "-" (line-beginning-position))
641 (let ((b (point)) (e (match-end 0)))
642 (if (region-modifiable-p b e
)
646 (set-marker end-marker nil
)
647 ;; Delete trailing empty lines.
648 (and delete-trailing-lines
649 ;; Really the end of buffer.
650 (= (goto-char (point-max)) (1+ (buffer-size)))
651 (<= (skip-chars-backward "\n") -
2)
652 (region-modifiable-p (1+ (point)) (point-max))
653 (delete-region (1+ (point)) (point-max)))))))
654 ;; Return nil for the benefit of `write-file-functions'.
657 (defun newline-and-indent ()
658 "Insert a newline, then indent according to major mode.
659 Indentation is done using the value of `indent-line-function'.
660 In programming language modes, this is the same as TAB.
661 In some text modes, where TAB inserts a tab, this command indents to the
662 column specified by the function `current-left-margin'."
664 (delete-horizontal-space t
)
666 (indent-according-to-mode))
668 (defun reindent-then-newline-and-indent ()
669 "Reindent current line, insert newline, then indent the new line.
670 Indentation of both lines is done according to the current major mode,
671 which means calling the current value of `indent-line-function'.
672 In programming language modes, this is the same as TAB.
673 In some text modes, where TAB inserts a tab, this indents to the
674 column specified by the function `current-left-margin'."
677 ;; Be careful to insert the newline before indenting the line.
678 ;; Otherwise, the indentation might be wrong.
682 ;; We are at EOL before the call to indent-according-to-mode, and
683 ;; after it we usually are as well, but not always. We tried to
684 ;; address it with `save-excursion' but that uses a normal marker
685 ;; whereas we need `move after insertion', so we do the save/restore
687 (setq pos
(copy-marker pos t
))
688 (indent-according-to-mode)
690 ;; Remove the trailing white-space after indentation because
691 ;; indentation may introduce the whitespace.
692 (delete-horizontal-space t
))
693 (indent-according-to-mode)))
695 (defcustom read-quoted-char-radix
8
696 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
697 Legitimate radix values are 8, 10 and 16."
698 :type
'(choice (const 8) (const 10) (const 16))
699 :group
'editing-basics
)
701 (defun read-quoted-char (&optional prompt
)
702 "Like `read-char', but do not allow quitting.
703 Also, if the first character read is an octal digit,
704 we read any number of octal digits and return the
705 specified character code. Any nondigit terminates the sequence.
706 If the terminator is RET, it is discarded;
707 any other terminator is used itself as input.
709 The optional argument PROMPT specifies a string to use to prompt the user.
710 The variable `read-quoted-char-radix' controls which radix to use
712 (let ((message-log-max nil
)
713 (help-events (delq nil
(mapcar (lambda (c) (unless (characterp c
) c
))
715 done
(first t
) (code 0) char translated
)
717 (let ((inhibit-quit first
)
718 ;; Don't let C-h or other help chars get the help
719 ;; message--only help function keys. See bug#16617.
721 (help-event-list help-events
)
723 "Type the special character you want to use,
724 or the octal character code.
725 RET terminates the character code and is discarded;
726 any other non-digit terminates the character code and is then used as input."))
727 (setq char
(read-event (and prompt
(format "%s-" prompt
)) t
))
728 (if inhibit-quit
(setq quit-flag nil
)))
729 ;; Translate TAB key into control-I ASCII character, and so on.
730 ;; Note: `read-char' does it using the `ascii-character' property.
731 ;; We tried using read-key instead, but that disables the keystroke
732 ;; echo produced by 'C-q', see bug#24635.
733 (let ((translation (lookup-key local-function-key-map
(vector char
))))
734 (setq translated
(if (arrayp translation
)
737 (if (integerp translated
)
738 (setq translated
(char-resolve-modifiers translated
)))
739 (cond ((null translated
))
740 ((not (integerp translated
))
741 (setq unread-command-events
(list char
)
743 ((/= (logand translated ?\M-\^
@) 0)
744 ;; Turn a meta-character into a character with the 0200 bit set.
745 (setq code
(logior (logand translated
(lognot ?\M-\^
@)) 128)
747 ((and (<= ?
0 translated
)
748 (< translated
(+ ?
0 (min 10 read-quoted-char-radix
))))
749 (setq code
(+ (* code read-quoted-char-radix
) (- translated ?
0)))
750 (and prompt
(setq prompt
(message "%s %c" prompt translated
))))
751 ((and (<= ?a
(downcase translated
))
752 (< (downcase translated
)
753 (+ ?a -
10 (min 36 read-quoted-char-radix
))))
754 (setq code
(+ (* code read-quoted-char-radix
)
755 (+ 10 (- (downcase translated
) ?a
))))
756 (and prompt
(setq prompt
(message "%s %c" prompt translated
))))
757 ((and (not first
) (eq translated ?\C-m
))
760 (setq unread-command-events
(list char
)
762 (t (setq code translated
767 (defun quoted-insert (arg)
768 "Read next input character and insert it.
769 This is useful for inserting control characters.
770 With argument, insert ARG copies of the character.
772 If the first character you type after this command is an octal digit,
773 you should type a sequence of octal digits which specify a character code.
774 Any nondigit terminates the sequence. If the terminator is a RET,
775 it is discarded; any other terminator is used itself as input.
776 The variable `read-quoted-char-radix' specifies the radix for this feature;
777 set it to 10 or 16 to use decimal or hex instead of octal.
779 In overwrite mode, this function inserts the character anyway, and
780 does not handle octal digits specially. This means that if you use
781 overwrite as your normal editing mode, you can use this function to
782 insert characters when necessary.
784 In binary overwrite mode, this function does overwrite, and octal
785 digits are interpreted as a character code. This is intended to be
786 useful for editing binary files."
789 ;; Avoid "obsolete" warnings for translation-table-for-input.
791 (let (translation-table-for-input input-method-function
)
792 (if (or (not overwrite-mode
)
793 (eq overwrite-mode
'overwrite-mode-binary
))
796 ;; This used to assume character codes 0240 - 0377 stand for
797 ;; characters in some single-byte character set, and converted them
798 ;; to Emacs characters. But in 23.1 this feature is deprecated
799 ;; in favor of inserting the corresponding Unicode characters.
800 ;; (if (and enable-multibyte-characters
803 ;; (setq char (unibyte-char-to-multibyte char)))
804 (unless (characterp char
)
805 (user-error "%s is not a valid character"
806 (key-description (vector char
))))
808 (if (eq overwrite-mode
'overwrite-mode-binary
)
811 (insert-and-inherit char
)
812 (setq arg
(1- arg
)))))
814 (defun forward-to-indentation (&optional arg
)
815 "Move forward ARG lines and position at first nonblank character."
817 (forward-line (or arg
1))
818 (skip-chars-forward " \t"))
820 (defun backward-to-indentation (&optional arg
)
821 "Move backward ARG lines and position at first nonblank character."
823 (forward-line (- (or arg
1)))
824 (skip-chars-forward " \t"))
826 (defun back-to-indentation ()
827 "Move point to the first non-whitespace character on this line."
829 (beginning-of-line 1)
830 (skip-syntax-forward " " (line-end-position))
831 ;; Move back over chars that have whitespace syntax but have the p flag.
832 (backward-prefix-chars))
834 (defun fixup-whitespace ()
835 "Fixup white space between objects around point.
836 Leave one space or none, according to the context."
839 (delete-horizontal-space)
840 (if (or (looking-at "^\\|$\\|\\s)")
841 (save-excursion (forward-char -
1)
842 (looking-at "$\\|\\s(\\|\\s'")))
846 (defun delete-horizontal-space (&optional backward-only
)
847 "Delete all spaces and tabs around point.
848 If BACKWARD-ONLY is non-nil, only delete them before point."
850 (let ((orig-pos (point)))
855 (skip-chars-forward " \t")
856 (constrain-to-field nil orig-pos t
)))
858 (skip-chars-backward " \t")
859 (constrain-to-field nil orig-pos
)))))
861 (defun just-one-space (&optional n
)
862 "Delete all spaces and tabs around point, leaving one space (or N spaces).
863 If N is negative, delete newlines as well, leaving -N spaces.
864 See also `cycle-spacing'."
866 (cycle-spacing n nil
'single-shot
))
868 (defvar cycle-spacing--context nil
869 "Store context used in consecutive calls to `cycle-spacing' command.
870 The first time `cycle-spacing' runs, it saves in this variable:
871 its N argument, the original point position, and the original spacing
874 (defun cycle-spacing (&optional n preserve-nl-back mode
)
875 "Manipulate whitespace around point in a smart way.
876 In interactive use, this function behaves differently in successive
879 The first call in a sequence acts like `just-one-space'.
880 It deletes all spaces and tabs around point, leaving one space
881 \(or N spaces). N is the prefix argument. If N is negative,
882 it deletes newlines as well, leaving -N spaces.
883 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
885 The second call in a sequence deletes all spaces.
887 The third call in a sequence restores the original whitespace (and point).
889 If MODE is `single-shot', it only performs the first step in the sequence.
890 If MODE is `fast' and the first step would not result in any change
891 \(i.e., there are exactly (abs N) spaces around point),
892 the function goes straight to the second step.
894 Repeatedly calling the function with different values of N starts a
895 new sequence each time."
897 (let ((orig-pos (point))
898 (skip-characters (if (and n
(< n
0)) " \t\n\r" " \t"))
899 (num (abs (or n
1))))
900 (skip-chars-backward (if preserve-nl-back
" \t" skip-characters
))
901 (constrain-to-field nil orig-pos
)
903 ;; Command run for the first time, single-shot mode or different argument
904 ((or (eq 'single-shot mode
)
905 (not (equal last-command this-command
))
906 (not cycle-spacing--context
)
907 (not (eq (car cycle-spacing--context
) n
)))
908 (let* ((start (point))
909 (num (- num
(skip-chars-forward " " (+ num
(point)))))
912 (skip-chars-forward skip-characters
)
913 (constrain-to-field nil orig-pos t
))))
914 (setq cycle-spacing--context
;; Save for later.
915 ;; Special handling for case where there was no space at all.
916 (unless (= start end
)
917 (cons n
(cons orig-pos
(buffer-substring start
(point))))))
918 ;; If this run causes no change in buffer content, delete all spaces,
919 ;; otherwise delete all excess spaces.
920 (delete-region (if (and (eq mode
'fast
) (zerop num
) (= mid end
))
922 (insert (make-string num ?\s
))))
924 ;; Command run for the second time.
925 ((not (equal orig-pos
(point)))
926 (delete-region (point) orig-pos
))
928 ;; Command run for the third time.
930 (insert (cddr cycle-spacing--context
))
931 (goto-char (cadr cycle-spacing--context
))
932 (setq cycle-spacing--context nil
)))))
934 (defun beginning-of-buffer (&optional arg
)
935 "Move point to the beginning of the buffer.
936 With numeric arg N, put point N/10 of the way from the beginning.
937 If the buffer is narrowed, this command uses the beginning of the
938 accessible part of the buffer.
940 Push mark at previous position, unless either a \\[universal-argument] prefix
941 is supplied, or Transient Mark mode is enabled and the mark is active."
942 (declare (interactive-only "use `(goto-char (point-min))' instead."))
947 (let ((size (- (point-max) (point-min))))
948 (goto-char (if (and arg
(not (consp arg
)))
951 ;; Avoid overflow for large buffer sizes!
952 (* (prefix-numeric-value arg
)
954 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
956 (if (and arg
(not (consp arg
))) (forward-line 1)))
958 (defun end-of-buffer (&optional arg
)
959 "Move point to the end of the buffer.
960 With numeric arg N, put point N/10 of the way from the end.
961 If the buffer is narrowed, this command uses the end of the
962 accessible part of the buffer.
964 Push mark at previous position, unless either a \\[universal-argument] prefix
965 is supplied, or Transient Mark mode is enabled and the mark is active."
966 (declare (interactive-only "use `(goto-char (point-max))' instead."))
968 (or (consp arg
) (region-active-p) (push-mark))
969 (let ((size (- (point-max) (point-min))))
970 (goto-char (if (and arg
(not (consp arg
)))
973 ;; Avoid overflow for large buffer sizes!
974 (* (prefix-numeric-value arg
)
976 (/ (* size
(prefix-numeric-value arg
)) 10)))
978 ;; If we went to a place in the middle of the buffer,
979 ;; adjust it to the beginning of a line.
980 (cond ((and arg
(not (consp arg
))) (forward-line 1))
981 ((and (eq (current-buffer) (window-buffer))
982 (> (point) (window-end nil t
)))
983 ;; If the end of the buffer is not already on the screen,
984 ;; then scroll specially to put it near, but not at, the bottom.
985 (overlay-recenter (point))
988 (defcustom delete-active-region t
989 "Whether single-char deletion commands delete an active region.
990 This has an effect only if Transient Mark mode is enabled, and
991 affects `delete-forward-char' and `delete-backward-char', though
994 If the value is the symbol `kill', the active region is killed
996 :type
'(choice (const :tag
"Delete active region" t
)
997 (const :tag
"Kill active region" kill
)
998 (const :tag
"Do ordinary deletion" nil
))
1002 (defvar region-extract-function
1004 (when (region-beginning)
1006 ((eq method
'bounds
)
1007 (list (cons (region-beginning) (region-end))))
1008 ((eq method
'delete-only
)
1009 (delete-region (region-beginning) (region-end)))
1011 (filter-buffer-substring (region-beginning) (region-end) method
)))))
1012 "Function to get the region's content.
1013 Called with one argument METHOD which can be:
1014 - nil: return the content as a string.
1015 - `delete-only': delete the region; the return value is undefined.
1016 - `bounds': return the boundaries of the region as a list of cons
1017 cells of the form (START . END).
1018 - anything else: delete the region and return its content
1019 as a string, after filtering it with `filter-buffer-substring', which
1020 is called with METHOD as its 3rd argument.")
1022 (defvar region-insert-function
1028 (insert-for-yank (car lines
))
1029 (setq lines
(cdr lines
)
1031 "Function to insert the region's content.
1032 Called with one argument LINES.
1033 Insert the region as a list of lines.")
1035 (defun delete-backward-char (n &optional killflag
)
1036 "Delete the previous N characters (following if N is negative).
1037 If Transient Mark mode is enabled, the mark is active, and N is 1,
1038 delete the text in the region and deactivate the mark instead.
1039 To disable this, set option `delete-active-region' to nil.
1041 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1042 kill ring) instead of delete. Interactively, N is the prefix
1043 arg, and KILLFLAG is set if N is explicitly specified.
1045 When killing, the killed text is filtered by
1046 `filter-buffer-substring' before it is saved in the kill ring, so
1047 the actual saved text might be different from what was killed.
1049 In Overwrite mode, single character backward deletion may replace
1050 tabs with spaces so as to back over columns, unless point is at
1051 the end of the line."
1052 (declare (interactive-only delete-char
))
1053 (interactive "p\nP")
1054 (unless (integerp n
)
1055 (signal 'wrong-type-argument
(list 'integerp n
)))
1056 (cond ((and (use-region-p)
1057 delete-active-region
1059 ;; If a region is active, kill or delete it.
1060 (if (eq delete-active-region
'kill
)
1061 (kill-region (region-beginning) (region-end) 'region
)
1062 (funcall region-extract-function
'delete-only
)))
1063 ;; In Overwrite mode, maybe untabify while deleting
1064 ((null (or (null overwrite-mode
)
1066 (memq (char-before) '(?
\t ?
\n))
1068 (eq (char-after) ?
\n)))
1069 (let ((ocol (current-column)))
1070 (delete-char (- n
) killflag
)
1072 (insert-char ?\s
(- ocol
(current-column)) nil
))))
1073 ;; Otherwise, do simple deletion.
1074 (t (delete-char (- n
) killflag
))))
1076 (defun delete-forward-char (n &optional killflag
)
1077 "Delete the following N characters (previous if N is negative).
1078 If Transient Mark mode is enabled, the mark is active, and N is 1,
1079 delete the text in the region and deactivate the mark instead.
1080 To disable this, set variable `delete-active-region' to nil.
1082 Optional second arg KILLFLAG non-nil means to kill (save in kill
1083 ring) instead of delete. Interactively, N is the prefix arg, and
1084 KILLFLAG is set if N was explicitly specified.
1086 When killing, the killed text is filtered by
1087 `filter-buffer-substring' before it is saved in the kill ring, so
1088 the actual saved text might be different from what was killed."
1089 (declare (interactive-only delete-char
))
1090 (interactive "p\nP")
1091 (unless (integerp n
)
1092 (signal 'wrong-type-argument
(list 'integerp n
)))
1093 (cond ((and (use-region-p)
1094 delete-active-region
1096 ;; If a region is active, kill or delete it.
1097 (if (eq delete-active-region
'kill
)
1098 (kill-region (region-beginning) (region-end) 'region
)
1099 (funcall region-extract-function
'delete-only
)))
1101 ;; Otherwise, do simple deletion.
1102 (t (delete-char n killflag
))))
1104 (defun mark-whole-buffer ()
1105 "Put point at beginning and mark at end of buffer.
1106 If narrowing is in effect, only uses the accessible part of the buffer.
1107 You probably should not use this function in Lisp programs;
1108 it is usually a mistake for a Lisp function to use any subroutine
1109 that uses or sets the mark."
1110 (declare (interactive-only t
))
1113 (push-mark (point-max) nil t
)
1114 ;; This is really `point-min' in most cases, but if we're in the
1115 ;; minibuffer, this is at the end of the prompt.
1116 (goto-char (minibuffer-prompt-end)))
1119 ;; Counting lines, one way or another.
1121 (defun goto-line (line &optional buffer
)
1122 "Go to LINE, counting from line 1 at beginning of buffer.
1123 If called interactively, a numeric prefix argument specifies
1124 LINE; without a numeric prefix argument, read LINE from the
1127 If optional argument BUFFER is non-nil, switch to that buffer and
1128 move to line LINE there. If called interactively with \\[universal-argument]
1129 as argument, BUFFER is the most recently selected other buffer.
1131 Prior to moving point, this function sets the mark (without
1132 activating it), unless Transient Mark mode is enabled and the
1133 mark is already active.
1135 This function is usually the wrong thing to use in a Lisp program.
1136 What you probably want instead is something like:
1137 (goto-char (point-min))
1138 (forward-line (1- N))
1139 If at all possible, an even better solution is to use char counts
1140 rather than line counts."
1141 (declare (interactive-only forward-line
))
1143 (if (and current-prefix-arg
(not (consp current-prefix-arg
)))
1144 (list (prefix-numeric-value current-prefix-arg
))
1145 ;; Look for a default, a number in the buffer at point.
1148 (skip-chars-backward "0-9")
1149 (if (looking-at "[0-9]")
1151 (buffer-substring-no-properties
1153 (progn (skip-chars-forward "0-9")
1155 ;; Decide if we're switching buffers.
1157 (if (consp current-prefix-arg
)
1158 (other-buffer (current-buffer) t
)))
1161 (concat " in " (buffer-name buffer
))
1163 ;; Read the argument, offering that number (if any) as default.
1164 (list (read-number (format "Goto line%s: " buffer-prompt
)
1165 (list default
(line-number-at-pos)))
1167 ;; Switch to the desired buffer, one way or another.
1169 (let ((window (get-buffer-window buffer
)))
1170 (if window
(select-window window
)
1171 (switch-to-buffer-other-window buffer
))))
1172 ;; Leave mark at previous position
1173 (or (region-active-p) (push-mark))
1174 ;; Move to the specified line number in that buffer.
1177 (goto-char (point-min))
1178 (if (eq selective-display t
)
1179 (re-search-forward "[\n\C-m]" nil
'end
(1- line
))
1180 (forward-line (1- line
)))))
1182 (defun count-words-region (start end
&optional arg
)
1183 "Count the number of words in the region.
1184 If called interactively, print a message reporting the number of
1185 lines, words, and characters in the region (whether or not the
1186 region is active); with prefix ARG, report for the entire buffer
1187 rather than the region.
1189 If called from Lisp, return the number of words between positions
1191 (interactive (if current-prefix-arg
1192 (list nil nil current-prefix-arg
)
1193 (list (region-beginning) (region-end) nil
)))
1194 (cond ((not (called-interactively-p 'any
))
1195 (count-words start end
))
1197 (count-words--buffer-message))
1199 (count-words--message "Region" start end
))))
1201 (defun count-words (start end
)
1202 "Count words between START and END.
1203 If called interactively, START and END are normally the start and
1204 end of the buffer; but if the region is active, START and END are
1205 the start and end of the region. Print a message reporting the
1206 number of lines, words, and chars.
1208 If called from Lisp, return the number of words between START and
1209 END, without printing any message."
1210 (interactive (list nil nil
))
1211 (cond ((not (called-interactively-p 'any
))
1215 (narrow-to-region start end
)
1216 (goto-char (point-min))
1217 (while (forward-word-strictly 1)
1218 (setq words
(1+ words
)))))
1221 (call-interactively 'count-words-region
))
1223 (count-words--buffer-message))))
1225 (defun count-words--buffer-message ()
1226 (count-words--message
1227 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1228 (point-min) (point-max)))
1230 (defun count-words--message (str start end
)
1231 (let ((lines (count-lines start end
))
1232 (words (count-words start end
))
1233 (chars (- end start
)))
1234 (message "%s has %d line%s, %d word%s, and %d character%s."
1236 lines
(if (= lines
1) "" "s")
1237 words
(if (= words
1) "" "s")
1238 chars
(if (= chars
1) "" "s"))))
1240 (define-obsolete-function-alias 'count-lines-region
'count-words-region
"24.1")
1243 "Print the current buffer line number and narrowed line number of point."
1245 (let ((start (point-min))
1246 (n (line-number-at-pos)))
1248 (message "Line %d" n
)
1252 (message "line %d (narrowed line %d)"
1253 (+ n
(line-number-at-pos start
) -
1) n
))))))
1255 (defun count-lines (start end
)
1256 "Return number of lines between START and END.
1257 This is usually the number of newlines between them,
1258 but can be one more if START is not equal to END
1259 and the greater of them is not at the start of a line."
1262 (narrow-to-region start end
)
1263 (goto-char (point-min))
1264 (if (eq selective-display t
)
1267 (while (re-search-forward "[\n\C-m]" nil t
40)
1268 (setq done
(+ 40 done
)))
1269 (while (re-search-forward "[\n\C-m]" nil t
1)
1270 (setq done
(+ 1 done
)))
1271 (goto-char (point-max))
1272 (if (and (/= start end
)
1276 (- (buffer-size) (forward-line (buffer-size)))))))
1278 (defun line-number-at-pos (&optional pos absolute
)
1279 "Return buffer line number at position POS.
1280 If POS is nil, use current buffer location.
1282 If ABSOLUTE is nil, the default, counting starts
1283 at (point-min), so the value refers to the contents of the
1284 accessible portion of the (potentially narrowed) buffer. If
1285 ABSOLUTE is non-nil, ignore any narrowing and return the
1286 absolute line number."
1290 (let ((opoint (or pos
(point))) start
)
1292 (goto-char (point-min))
1293 (setq start
(point))
1296 (1+ (count-lines start
(point)))))))
1298 (defun what-cursor-position (&optional detail
)
1299 "Print info on cursor position (on screen and within buffer).
1300 Also describe the character after point, and give its character code
1301 in octal, decimal and hex.
1303 For a non-ASCII multibyte character, also give its encoding in the
1304 buffer's selected coding system if the coding system encodes the
1305 character safely. If the character is encoded into one byte, that
1306 code is shown in hex. If the character is encoded into more than one
1307 byte, just \"...\" is shown.
1309 In addition, with prefix argument, show details about that character
1310 in *Help* buffer. See also the command `describe-char'."
1312 (let* ((char (following-char))
1314 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1315 ;; start a directional embedding, which could completely
1316 ;; disrupt the rest of the line (e.g., RLO will display the
1317 ;; rest of the line right-to-left). So we put an invisible
1318 ;; PDF character after these characters, to end the
1319 ;; embedding, which eliminates any effects on the rest of
1320 ;; the line. For RLE and RLO we also append an invisible
1321 ;; LRM, to avoid reordering the following numerical
1322 ;; characters. For LRI/RLI/FSI we append a PDI.
1323 (cond ((memq char
'(?
\x202a ?
\x202d
))
1324 (propertize (string ?
\x202c
) 'invisible t
))
1325 ((memq char
'(?
\x202b ?
\x202e
))
1326 (propertize (string ?
\x202c ?
\x200e
) 'invisible t
))
1327 ((memq char
'(?
\x2066 ?
\x2067 ?
\x2068
))
1328 (propertize (string ?
\x2069
) 'invisible t
))
1329 ;; Strong right-to-left characters cause reordering of
1330 ;; the following numerical characters which show the
1331 ;; codepoint, so append LRM to countermand that.
1332 ((memq (get-char-code-property char
'bidi-class
) '(R AL
))
1333 (propertize (string ?
\x200e
) 'invisible t
))
1339 (total (buffer-size))
1340 (percent (round (* 100.0 (1- pos
)) (max 1 total
)))
1341 (hscroll (if (= (window-hscroll) 0)
1343 (format " Hscroll=%d" (window-hscroll))))
1344 (col (current-column)))
1346 (if (or (/= beg
1) (/= end
(1+ total
)))
1347 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1348 pos total percent beg end col hscroll
)
1349 (message "point=%d of %d (EOB) column=%d%s"
1350 pos total col hscroll
))
1351 (let ((coding buffer-file-coding-system
)
1352 encoded encoding-msg display-prop under-display
)
1353 (if (or (not coding
)
1354 (eq (coding-system-type coding
) t
))
1355 (setq coding
(default-value 'buffer-file-coding-system
)))
1356 (if (eq (char-charset char
) 'eight-bit
)
1358 (format "(%d, #o%o, #x%x, raw-byte)" char char char
))
1359 ;; Check if the character is displayed with some `display'
1360 ;; text property. In that case, set under-display to the
1361 ;; buffer substring covered by that property.
1362 (setq display-prop
(get-char-property pos
'display
))
1364 (let ((to (or (next-single-char-property-change pos
'display
)
1366 (if (< to
(+ pos
4))
1367 (setq under-display
"")
1368 (setq under-display
"..."
1371 (concat (buffer-substring-no-properties pos to
)
1373 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
1376 (if (not (stringp display-prop
))
1377 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1378 char char char under-display
)
1379 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1380 char char char under-display display-prop
))
1382 (format "(%d, #o%o, #x%x, file %s)"
1384 (if (> (length encoded
) 1)
1386 (encoded-string-description encoded coding
)))
1387 (format "(%d, #o%o, #x%x)" char char char
)))))
1389 ;; We show the detailed information about CHAR.
1390 (describe-char (point)))
1391 (if (or (/= beg
1) (/= end
(1+ total
)))
1392 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1394 (single-key-description char
)
1395 (buffer-substring-no-properties (point) (1+ (point))))
1397 encoding-msg pos total percent beg end col hscroll
)
1398 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1399 (if enable-multibyte-characters
1401 (single-key-description char
)
1402 (buffer-substring-no-properties (point) (1+ (point))))
1403 (single-key-description char
))
1404 bidi-fixer encoding-msg pos total percent col hscroll
))))))
1406 ;; Initialize read-expression-map. It is defined at C level.
1407 (defvar read-expression-map
1408 (let ((m (make-sparse-keymap)))
1409 (define-key m
"\M-\t" 'completion-at-point
)
1410 ;; Might as well bind TAB to completion, since inserting a TAB char is
1411 ;; much too rarely useful.
1412 (define-key m
"\t" 'completion-at-point
)
1413 (set-keymap-parent m minibuffer-local-map
)
1416 (defun read-minibuffer (prompt &optional initial-contents
)
1417 "Return a Lisp object read using the minibuffer, unevaluated.
1418 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1419 is a string to insert in the minibuffer before reading.
1420 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1421 Such arguments are used as in `read-from-minibuffer'.)"
1422 ;; Used for interactive spec `x'.
1423 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1424 t
'minibuffer-history
))
1426 (defun eval-minibuffer (prompt &optional initial-contents
)
1427 "Return value of Lisp expression read using the minibuffer.
1428 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1429 is a string to insert in the minibuffer before reading.
1430 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1431 Such arguments are used as in `read-from-minibuffer'.)"
1432 ;; Used for interactive spec `X'.
1433 (eval (read--expression prompt initial-contents
)))
1435 (defvar minibuffer-completing-symbol nil
1436 "Non-nil means completing a Lisp symbol in the minibuffer.")
1437 (make-obsolete-variable 'minibuffer-completing-symbol nil
"24.1" 'get
)
1439 (defvar minibuffer-default nil
1440 "The current default value or list of default values in the minibuffer.
1441 The functions `read-from-minibuffer' and `completing-read' bind
1442 this variable locally.")
1444 (defcustom eval-expression-print-level
4
1445 "Value for `print-level' while printing value in `eval-expression'.
1446 A value of nil means no limit."
1448 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1451 (defcustom eval-expression-print-length
12
1452 "Value for `print-length' while printing value in `eval-expression'.
1453 A value of nil means no limit."
1455 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1458 (defcustom eval-expression-debug-on-error t
1459 "If non-nil set `debug-on-error' to t in `eval-expression'.
1460 If nil, don't change the value of `debug-on-error'."
1465 (defcustom eval-expression-print-maximum-character
127
1466 "The largest integer that will be displayed as a character.
1467 This affects printing by `eval-expression' (via
1468 `eval-expression-print-format')."
1473 (defun eval-expression-print-format (value)
1474 "If VALUE in an integer, return a specially formatted string.
1475 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1476 If VALUE is not an integer, nil is returned.
1477 This function is used by commands like `eval-expression' that
1478 display the result of expression evaluation."
1479 (when (integerp value
)
1481 (and (characterp value
)
1482 (<= value eval-expression-print-maximum-character
)
1483 (char-displayable-p value
)
1484 (prin1-char value
))))
1486 (format " (#o%o, #x%x, %s)" value value char-string
)
1487 (format " (#o%o, #x%x)" value value
)))))
1489 (defvar eval-expression-minibuffer-setup-hook nil
1490 "Hook run by `eval-expression' when entering the minibuffer.")
1492 (defun read--expression (prompt &optional initial-contents
)
1493 (let ((minibuffer-completing-symbol t
))
1494 (minibuffer-with-setup-hook
1496 ;; FIXME: call emacs-lisp-mode?
1497 (add-function :before-until
(local 'eldoc-documentation-function
)
1498 #'elisp-eldoc-documentation-function
)
1500 (add-hook 'completion-at-point-functions
1501 #'elisp-completion-at-point nil t
)
1502 (run-hooks 'eval-expression-minibuffer-setup-hook
))
1503 (read-from-minibuffer prompt initial-contents
1504 read-expression-map t
1505 'read-expression-history
))))
1507 (defun eval-expression-get-print-arguments (prefix-argument)
1508 "Get arguments for commands that print an expression result.
1509 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1510 based on PREFIX-ARG. This function determines the interpretation
1511 of the prefix argument for `eval-expression' and
1513 (let ((num (prefix-numeric-value prefix-argument
)))
1514 (list (not (memq prefix-argument
'(- nil
)))
1516 (cond ((not (memq prefix-argument
'(0 -
1 - nil
))) nil
)
1517 ((= num -
1) most-positive-fixnum
)
1518 (t eval-expression-print-maximum-character
)))))
1520 ;; We define this, rather than making `eval' interactive,
1521 ;; for the sake of completion of names like eval-region, eval-buffer.
1522 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit
)
1523 "Evaluate EXP and print value in the echo area.
1524 When called interactively, read an Emacs Lisp expression and
1525 evaluate it. Value is also consed on to front of the variable
1526 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1527 with a non `-' prefix argument) means insert the result into the
1528 current buffer instead of printing it in the echo area.
1530 Normally, this function truncates long output according to the
1531 value of the variables `eval-expression-print-length' and
1532 `eval-expression-print-level'. When NO-TRUNCATE is
1533 non-nil (interactively, with a prefix argument of zero), however,
1534 there is no such truncation.
1536 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1537 non-nil (interactively, unless given a positive prefix argument)
1538 it will be printed in several additional formats (octal,
1539 hexadecimal, and character). The character format is only used
1540 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1541 prefix argument is -1 or the value is below
1542 `eval-expression-print-maximum-character').
1544 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1547 If `eval-expression-debug-on-error' is non-nil, which is the default,
1548 this command arranges for all errors to enter the debugger."
1550 (cons (read--expression "Eval: ")
1551 (eval-expression-get-print-arguments current-prefix-arg
)))
1553 (if (null eval-expression-debug-on-error
)
1554 (push (eval exp lexical-binding
) values
)
1555 (let ((old-value (make-symbol "t")) new-value
)
1556 ;; Bind debug-on-error to something unique so that we can
1557 ;; detect when evalled code changes it.
1558 (let ((debug-on-error old-value
))
1559 (push (eval (macroexpand-all exp
) lexical-binding
) values
)
1560 (setq new-value debug-on-error
))
1561 ;; If evalled code has changed the value of debug-on-error,
1562 ;; propagate that change to the global binding.
1563 (unless (eq old-value new-value
)
1564 (setq debug-on-error new-value
))))
1566 (let ((print-length (unless no-truncate eval-expression-print-length
))
1567 (print-level (unless no-truncate eval-expression-print-level
))
1568 (eval-expression-print-maximum-character char-print-limit
)
1570 (let ((out (if insert-value
(current-buffer) t
)))
1572 (prin1 (car values
) out
)
1573 (let ((str (and char-print-limit
1574 (eval-expression-print-format (car values
)))))
1575 (when str
(princ str out
)))))))
1577 (defun edit-and-eval-command (prompt command
)
1578 "Prompting with PROMPT, let user edit COMMAND and eval result.
1579 COMMAND is a Lisp expression. Let user edit that expression in
1580 the minibuffer, then read and evaluate the result."
1582 (let ((print-level nil
)
1583 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1585 (read-from-minibuffer prompt
1586 (prin1-to-string command
)
1587 read-expression-map t
1589 ;; If command was added to command-history as a string,
1590 ;; get rid of that. We want only evaluable expressions there.
1591 (if (stringp (car command-history
))
1592 (setq command-history
(cdr command-history
)))))))
1594 ;; If command to be redone does not match front of history,
1595 ;; add it to the history.
1596 (or (equal command
(car command-history
))
1597 (setq command-history
(cons command command-history
)))
1600 (defun repeat-complex-command (arg)
1601 "Edit and re-evaluate last complex command, or ARGth from last.
1602 A complex command is one which used the minibuffer.
1603 The command is placed in the minibuffer as a Lisp form for editing.
1604 The result is executed, repeating the command as changed.
1605 If the command has been changed or is not the most recent previous
1606 command it is added to the front of the command history.
1607 You can use the minibuffer history commands \
1608 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1609 to get different commands to edit and resubmit."
1611 (let ((elt (nth (1- arg
) command-history
))
1616 (let ((print-level nil
)
1617 (minibuffer-history-position arg
)
1618 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1620 (read-from-minibuffer
1621 "Redo: " (prin1-to-string elt
) read-expression-map t
1622 (cons 'command-history arg
))
1624 ;; If command was added to command-history as a
1625 ;; string, get rid of that. We want only
1626 ;; evaluable expressions there.
1627 (if (stringp (car command-history
))
1628 (setq command-history
(cdr command-history
))))))
1630 ;; If command to be redone does not match front of history,
1631 ;; add it to the history.
1632 (or (equal newcmd
(car command-history
))
1633 (setq command-history
(cons newcmd command-history
)))
1634 (apply #'funcall-interactively
1636 (mapcar (lambda (e) (eval e t
)) (cdr newcmd
))))
1638 (error "Argument %d is beyond length of command history" arg
)
1639 (error "There are no previous complex commands to repeat")))))
1642 (defvar extended-command-history nil
)
1643 (defvar execute-extended-command--last-typed nil
)
1645 (defun read-extended-command ()
1646 "Read command name to invoke in `execute-extended-command'."
1647 (minibuffer-with-setup-hook
1649 (add-hook 'post-self-insert-hook
1651 (setq execute-extended-command--last-typed
1652 (minibuffer-contents)))
1654 (set (make-local-variable 'minibuffer-default-add-function
)
1656 ;; Get a command name at point in the original buffer
1657 ;; to propose it after M-n.
1658 (with-current-buffer (window-buffer (minibuffer-selected-window))
1659 (and (commandp (function-called-at-point))
1660 (format "%S" (function-called-at-point)))))))
1661 ;; Read a string, completing from and restricting to the set of
1662 ;; all defined commands. Don't provide any initial input.
1663 ;; Save the command read on the extended-command history list.
1666 ((eq current-prefix-arg
'-
) "- ")
1667 ((and (consp current-prefix-arg
)
1668 (eq (car current-prefix-arg
) 4)) "C-u ")
1669 ((and (consp current-prefix-arg
)
1670 (integerp (car current-prefix-arg
)))
1671 (format "%d " (car current-prefix-arg
)))
1672 ((integerp current-prefix-arg
)
1673 (format "%d " current-prefix-arg
)))
1674 ;; This isn't strictly correct if `execute-extended-command'
1675 ;; is bound to anything else (e.g. [menu]).
1676 ;; It could use (key-description (this-single-command-keys)),
1677 ;; but actually a prompt other than "M-x" would be confusing,
1678 ;; because "M-x" is a well-known prompt to read a command
1679 ;; and it serves as a shorthand for "Extended command: ".
1681 (lambda (string pred action
)
1683 (if (memq action
'(nil t
))
1684 ;; Exclude obsolete commands from completions.
1686 (and (funcall pred sym
)
1687 (or (equal string
(symbol-name sym
))
1688 (not (get sym
'byte-obsolete-info
)))))
1690 (complete-with-action action obarray string pred
)))
1691 #'commandp t nil
'extended-command-history
)))
1693 (defcustom suggest-key-bindings t
1694 "Non-nil means show the equivalent key-binding when M-x command has one.
1695 The value can be a length of time to show the message for.
1696 If the value is non-nil and not a number, we wait 2 seconds."
1698 :type
'(choice (const :tag
"off" nil
)
1699 (integer :tag
"time" 2)
1702 (defcustom extended-command-suggest-shorter t
1703 "If non-nil, show a shorter M-x invocation when there is one."
1708 (defun execute-extended-command--shorter-1 (name length
)
1710 ((zerop length
) (list ""))
1711 ((equal name
"") nil
)
1713 (nconc (mapcar (lambda (s) (concat (substring name
0 1) s
))
1714 (execute-extended-command--shorter-1
1715 (substring name
1) (1- length
)))
1716 (when (string-match "\\`\\(-\\)?[^-]*" name
)
1717 (execute-extended-command--shorter-1
1718 (substring name
(match-end 0)) length
))))))
1720 (defun execute-extended-command--shorter (name typed
)
1721 (let ((candidates '())
1722 (max (length typed
))
1725 (while (and (not binding
)
1729 (setq candidates
(execute-extended-command--shorter-1
1731 ;; Don't show the help message if the binding isn't
1732 ;; significantly shorter than the M-x command the user typed.
1734 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1735 (let ((candidate (pop candidates
)))
1737 (car-safe (completion-try-completion
1738 candidate obarray
'commandp len
)))
1739 (setq binding candidate
))))
1742 (defun execute-extended-command (prefixarg &optional command-name typed
)
1743 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1744 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1745 "Read a command name, then read the arguments and call the command.
1746 To pass a prefix argument to the command you are
1747 invoking, give a prefix argument to `execute-extended-command'."
1748 (declare (interactive-only command-execute
))
1749 ;; FIXME: Remember the actual text typed by the user before completion,
1750 ;; so that we don't later on suggest the same shortening.
1752 (let ((execute-extended-command--last-typed nil
))
1753 (list current-prefix-arg
1754 (read-extended-command)
1755 execute-extended-command--last-typed
)))
1756 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1757 (unless command-name
1758 (let ((current-prefix-arg prefixarg
) ; for prompt
1759 (execute-extended-command--last-typed nil
))
1760 (setq command-name
(read-extended-command))
1761 (setq typed execute-extended-command--last-typed
)))
1762 (let* ((function (and (stringp command-name
) (intern-soft command-name
)))
1763 (binding (and suggest-key-bindings
1764 (not executing-kbd-macro
)
1765 (where-is-internal function overriding-local-map t
))))
1766 (unless (commandp function
)
1767 (error "`%s' is not a valid command name" command-name
))
1768 ;; Some features, such as novice.el, rely on this-command-keys
1769 ;; including M-x COMMAND-NAME RET.
1770 (set--this-command-keys (concat "\M-x" (symbol-name function
) "\r"))
1771 (setq this-command function
)
1772 ;; Normally `real-this-command' should never be changed, but here we really
1773 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1774 ;; binding" for <cmd>, so the command the user really wanted to run is
1775 ;; `function' and not `execute-extended-command'. The difference is
1776 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1777 (setq real-this-command function
)
1778 (let ((prefix-arg prefixarg
))
1779 (command-execute function
'record
))
1780 ;; If enabled, show which key runs this command.
1781 ;; But first wait, and skip the message if there is input.
1783 ;; If this command displayed something in the echo area;
1784 ;; wait a few seconds, then display our suggestion message.
1785 ;; FIXME: Wait *after* running post-command-hook!
1786 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1787 ;; find a better answer anyway!
1788 (when suggest-key-bindings
1790 ((zerop (length (current-message))) 0)
1791 ((numberp suggest-key-bindings
) suggest-key-bindings
)
1793 (when (and waited
(not (consp unread-command-events
)))
1794 (unless (or (not extended-command-suggest-shorter
)
1795 binding executing-kbd-macro
(not (symbolp function
))
1796 (<= (length (symbol-name function
)) 2))
1797 ;; There's no binding for CMD. Let's try and find the shortest
1798 ;; string to use in M-x.
1799 ;; FIXME: Can be slow. Cache it maybe?
1801 (setq binding
(execute-extended-command--shorter
1802 (symbol-name function
) typed
))))
1805 (format-message "You can run the command `%s' with %s"
1807 (if (stringp binding
)
1808 (concat "M-x " binding
" RET")
1809 (key-description binding
)))
1810 (sit-for (if (numberp suggest-key-bindings
)
1811 suggest-key-bindings
1814 (defun command-execute (cmd &optional record-flag keys special
)
1815 ;; BEWARE: Called directly from the C code.
1816 "Execute CMD as an editor command.
1817 CMD must be a symbol that satisfies the `commandp' predicate.
1818 Optional second arg RECORD-FLAG non-nil
1819 means unconditionally put this command in the variable `command-history'.
1820 Otherwise, that is done only if an arg is read using the minibuffer.
1821 The argument KEYS specifies the value to use instead of (this-command-keys)
1822 when reading the arguments; if it is nil, (this-command-keys) is used.
1823 The argument SPECIAL, if non-nil, means that this command is executing
1824 a special event, so ignore the prefix argument and don't clear it."
1825 (setq debug-on-next-call nil
)
1826 (let ((prefixarg (unless special
1827 ;; FIXME: This should probably be done around
1828 ;; pre-command-hook rather than here!
1830 (setq current-prefix-arg prefix-arg
)
1831 (setq prefix-arg nil
)
1832 (when current-prefix-arg
1833 (prefix-command-update))))))
1834 (if (and (symbolp cmd
)
1836 disabled-command-function
)
1837 ;; FIXME: Weird calling convention!
1838 (run-hooks 'disabled-command-function
)
1842 (setq final
(indirect-function final
))
1843 (if (autoloadp final
)
1844 (setq final
(autoload-do-load final cmd
)))))
1847 ;; If requested, place the macro in the command history. For
1848 ;; other sorts of commands, call-interactively takes care of this.
1850 (push `(execute-kbd-macro ,final
,prefixarg
) command-history
)
1851 ;; Don't keep command history around forever.
1852 (when (and (numberp history-length
) (> history-length
0))
1853 (let ((cell (nthcdr history-length command-history
)))
1854 (if (consp cell
) (setcdr cell nil
)))))
1855 (execute-kbd-macro final prefixarg
))
1857 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1858 (prog1 (call-interactively cmd record-flag keys
)
1859 (when (and (symbolp cmd
)
1860 (get cmd
'byte-obsolete-info
)
1861 (not (get cmd
'command-execute-obsolete-warned
)))
1862 (put cmd
'command-execute-obsolete-warned t
)
1863 (message "%s" (macroexp--obsolete-warning
1864 cmd
(get cmd
'byte-obsolete-info
) "command"))))))))))
1866 (defvar minibuffer-history nil
1867 "Default minibuffer history list.
1868 This is used for all minibuffer input
1869 except when an alternate history list is specified.
1871 Maximum length of the history list is determined by the value
1872 of `history-length', which see.")
1873 (defvar minibuffer-history-sexp-flag nil
1874 "Control whether history list elements are expressions or strings.
1875 If the value of this variable equals current minibuffer depth,
1876 they are expressions; otherwise they are strings.
1877 \(That convention is designed to do the right thing for
1878 recursive uses of the minibuffer.)")
1879 (setq minibuffer-history-variable
'minibuffer-history
)
1880 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1881 (defvar minibuffer-history-search-history nil
)
1883 (defvar minibuffer-text-before-history nil
1884 "Text that was in this minibuffer before any history commands.
1885 This is nil if there have not yet been any history commands
1886 in this use of the minibuffer.")
1888 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1890 (defun minibuffer-history-initialize ()
1891 (setq minibuffer-text-before-history nil
))
1893 (defun minibuffer-avoid-prompt (_new _old
)
1894 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1895 (declare (obsolete cursor-intangible-mode
"25.1"))
1896 (constrain-to-field nil
(point-max)))
1898 (defcustom minibuffer-history-case-insensitive-variables nil
1899 "Minibuffer history variables for which matching should ignore case.
1900 If a history variable is a member of this list, then the
1901 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1902 commands ignore case when searching it, regardless of `case-fold-search'."
1903 :type
'(repeat variable
)
1906 (defun previous-matching-history-element (regexp n
)
1907 "Find the previous history element that matches REGEXP.
1908 \(Previous history elements refer to earlier actions.)
1909 With prefix argument N, search for Nth previous match.
1910 If N is negative, find the next or Nth next match.
1911 Normally, history elements are matched case-insensitively if
1912 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1913 makes the search case-sensitive.
1914 See also `minibuffer-history-case-insensitive-variables'."
1916 (let* ((enable-recursive-minibuffers t
)
1917 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1919 minibuffer-local-map
1921 'minibuffer-history-search-history
1922 (car minibuffer-history-search-history
))))
1923 ;; Use the last regexp specified, by default, if input is empty.
1924 (list (if (string= regexp
"")
1925 (if minibuffer-history-search-history
1926 (car minibuffer-history-search-history
)
1927 (user-error "No previous history search regexp"))
1929 (prefix-numeric-value current-prefix-arg
))))
1931 (if (and (zerop minibuffer-history-position
)
1932 (null minibuffer-text-before-history
))
1933 (setq minibuffer-text-before-history
1934 (minibuffer-contents-no-properties)))
1935 (let ((history (symbol-value minibuffer-history-variable
))
1937 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1938 ;; On some systems, ignore case for file names.
1939 (if (memq minibuffer-history-variable
1940 minibuffer-history-case-insensitive-variables
)
1942 ;; Respect the user's setting for case-fold-search:
1948 (pos minibuffer-history-position
))
1951 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1952 (when (= pos prevpos
)
1953 (user-error (if (= pos
1)
1954 "No later matching history item"
1955 "No earlier matching history item")))
1957 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1958 (let ((print-level nil
))
1959 (prin1-to-string (nth (1- pos
) history
)))
1960 (nth (1- pos
) history
)))
1963 (and (string-match regexp match-string
)
1965 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1966 (match-beginning 1))))
1968 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1969 (setq minibuffer-history-position pos
)
1970 (goto-char (point-max))
1971 (delete-minibuffer-contents)
1972 (insert match-string
)
1973 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1974 (if (memq (car (car command-history
)) '(previous-matching-history-element
1975 next-matching-history-element
))
1976 (setq command-history
(cdr command-history
))))
1978 (defun next-matching-history-element (regexp n
)
1979 "Find the next history element that matches REGEXP.
1980 \(The next history element refers to a more recent action.)
1981 With prefix argument N, search for Nth next match.
1982 If N is negative, find the previous or Nth previous match.
1983 Normally, history elements are matched case-insensitively if
1984 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1985 makes the search case-sensitive."
1987 (let* ((enable-recursive-minibuffers t
)
1988 (regexp (read-from-minibuffer "Next element matching (regexp): "
1990 minibuffer-local-map
1992 'minibuffer-history-search-history
1993 (car minibuffer-history-search-history
))))
1994 ;; Use the last regexp specified, by default, if input is empty.
1995 (list (if (string= regexp
"")
1996 (if minibuffer-history-search-history
1997 (car minibuffer-history-search-history
)
1998 (user-error "No previous history search regexp"))
2000 (prefix-numeric-value current-prefix-arg
))))
2001 (previous-matching-history-element regexp
(- n
)))
2003 (defvar minibuffer-temporary-goal-position nil
)
2005 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
2006 "Function run by `goto-history-element' before consuming default values.
2007 This is useful to dynamically add more elements to the list of default values
2008 when `goto-history-element' reaches the end of this list.
2009 Before calling this function `goto-history-element' sets the variable
2010 `minibuffer-default-add-done' to t, so it will call this function only
2011 once. In special cases, when this function needs to be called more
2012 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2013 overriding the setting of this variable to t in `goto-history-element'.")
2015 (defvar minibuffer-default-add-done nil
2016 "When nil, add more elements to the end of the list of default values.
2017 The value nil causes `goto-history-element' to add more elements to
2018 the list of defaults when it reaches the end of this list. It does
2019 this by calling a function defined by `minibuffer-default-add-function'.")
2021 (make-variable-buffer-local 'minibuffer-default-add-done
)
2023 (defun minibuffer-default-add-completions ()
2024 "Return a list of all completions without the default value.
2025 This function is used to add all elements of the completion table to
2026 the end of the list of defaults just after the default value."
2027 (let ((def minibuffer-default
)
2028 (all (all-completions ""
2029 minibuffer-completion-table
2030 minibuffer-completion-predicate
)))
2033 (cons def
(delete def all
)))))
2035 (defun goto-history-element (nabs)
2036 "Puts element of the minibuffer history in the minibuffer.
2037 The argument NABS specifies the absolute history position."
2039 (when (and (not minibuffer-default-add-done
)
2040 (functionp minibuffer-default-add-function
)
2041 (< nabs
(- (if (listp minibuffer-default
)
2042 (length minibuffer-default
)
2044 (setq minibuffer-default-add-done t
2045 minibuffer-default
(funcall minibuffer-default-add-function
)))
2046 (let ((minimum (if minibuffer-default
2047 (- (if (listp minibuffer-default
)
2048 (length minibuffer-default
)
2051 elt minibuffer-returned-to-present
)
2052 (if (and (zerop minibuffer-history-position
)
2053 (null minibuffer-text-before-history
))
2054 (setq minibuffer-text-before-history
2055 (minibuffer-contents-no-properties)))
2056 (if (< nabs minimum
)
2057 (user-error (if minibuffer-default
2058 "End of defaults; no next item"
2059 "End of history; no default available")))
2060 (if (> nabs
(if (listp (symbol-value minibuffer-history-variable
))
2061 (length (symbol-value minibuffer-history-variable
))
2063 (user-error "Beginning of history; no preceding item"))
2064 (unless (memq last-command
'(next-history-element
2065 previous-history-element
))
2066 (let ((prompt-end (minibuffer-prompt-end)))
2067 (set (make-local-variable 'minibuffer-temporary-goal-position
)
2068 (cond ((<= (point) prompt-end
) prompt-end
)
2071 (goto-char (point-max))
2072 (delete-minibuffer-contents)
2073 (setq minibuffer-history-position nabs
)
2075 (setq elt
(if (listp minibuffer-default
)
2076 (nth (1- (abs nabs
)) minibuffer-default
)
2077 minibuffer-default
)))
2079 (setq elt
(or minibuffer-text-before-history
""))
2080 (setq minibuffer-returned-to-present t
)
2081 (setq minibuffer-text-before-history nil
))
2082 (t (setq elt
(nth (1- minibuffer-history-position
)
2083 (symbol-value minibuffer-history-variable
)))))
2085 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
2086 (not minibuffer-returned-to-present
))
2087 (let ((print-level nil
))
2088 (prin1-to-string elt
))
2090 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
2092 (defun next-history-element (n)
2093 "Puts next element of the minibuffer history in the minibuffer.
2094 With argument N, it uses the Nth following element."
2097 (goto-history-element (- minibuffer-history-position n
))))
2099 (defun previous-history-element (n)
2100 "Puts previous element of the minibuffer history in the minibuffer.
2101 With argument N, it uses the Nth previous element."
2104 (goto-history-element (+ minibuffer-history-position n
))))
2106 (defun next-line-or-history-element (&optional arg
)
2107 "Move cursor vertically down ARG lines, or to the next history element.
2108 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2109 next element of the minibuffer history in the minibuffer."
2111 (or arg
(setq arg
1))
2112 (let* ((old-point (point))
2113 ;; Don't add newlines if they have the mode enabled globally.
2114 (next-line-add-newlines nil
)
2115 ;; Remember the original goal column of possibly multi-line input
2116 ;; excluding the length of the prompt on the first line.
2117 (prompt-end (minibuffer-prompt-end))
2118 (old-column (unless (and (eolp) (> (point) prompt-end
))
2119 (if (= (line-number-at-pos) 1)
2120 (max (- (current-column) (1- prompt-end
)) 0)
2121 (current-column)))))
2126 ;; Restore old position since `line-move-visual' moves point to
2127 ;; the end of the line when it fails to go to the next line.
2128 (goto-char old-point
)
2129 (next-history-element arg
)
2130 ;; Reset `temporary-goal-column' because a correct value is not
2131 ;; calculated when `next-line' above fails by bumping against
2132 ;; the bottom of the minibuffer (bug#22544).
2133 (setq temporary-goal-column
0)
2134 ;; Restore the original goal column on the last line
2135 ;; of possibly multi-line input.
2136 (goto-char (point-max))
2138 (if (= (line-number-at-pos) 1)
2139 (move-to-column (+ old-column
(1- (minibuffer-prompt-end))))
2140 (move-to-column old-column
)))))))
2142 (defun previous-line-or-history-element (&optional arg
)
2143 "Move cursor vertically up ARG lines, or to the previous history element.
2144 When point moves over the top line of multi-line minibuffer, puts ARGth
2145 previous element of the minibuffer history in the minibuffer."
2147 (or arg
(setq arg
1))
2148 (let* ((old-point (point))
2149 ;; Remember the original goal column of possibly multi-line input
2150 ;; excluding the length of the prompt on the first line.
2151 (prompt-end (minibuffer-prompt-end))
2152 (old-column (unless (and (eolp) (> (point) prompt-end
))
2153 (if (= (line-number-at-pos) 1)
2154 (max (- (current-column) (1- prompt-end
)) 0)
2155 (current-column)))))
2158 (previous-line arg
))
2159 (beginning-of-buffer
2160 ;; Restore old position since `line-move-visual' moves point to
2161 ;; the beginning of the line when it fails to go to the previous line.
2162 (goto-char old-point
)
2163 (previous-history-element arg
)
2164 ;; Reset `temporary-goal-column' because a correct value is not
2165 ;; calculated when `previous-line' above fails by bumping against
2166 ;; the top of the minibuffer (bug#22544).
2167 (setq temporary-goal-column
0)
2168 ;; Restore the original goal column on the first line
2169 ;; of possibly multi-line input.
2170 (goto-char (minibuffer-prompt-end))
2172 (if (= (line-number-at-pos) 1)
2173 (move-to-column (+ old-column
(1- (minibuffer-prompt-end))))
2174 (move-to-column old-column
))
2175 ;; Put the cursor at the end of the visual line instead of the
2176 ;; logical line, so the next `previous-line-or-history-element'
2177 ;; would move to the previous history element, not to a possible upper
2178 ;; visual line from the end of logical line in `line-move-visual' mode.
2179 (end-of-visual-line)
2180 ;; Since `end-of-visual-line' puts the cursor at the beginning
2181 ;; of the next visual line, move it one char back to the end
2182 ;; of the first visual line (bug#22544).
2183 (unless (eolp) (backward-char 1)))))))
2185 (defun next-complete-history-element (n)
2186 "Get next history element which completes the minibuffer before the point.
2187 The contents of the minibuffer after the point are deleted, and replaced
2188 by the new completion."
2190 (let ((point-at-start (point)))
2191 (next-matching-history-element
2193 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2195 ;; next-matching-history-element always puts us at (point-min).
2196 ;; Move to the position we were at before changing the buffer contents.
2197 ;; This is still sensible, because the text before point has not changed.
2198 (goto-char point-at-start
)))
2200 (defun previous-complete-history-element (n)
2202 Get previous history element which completes the minibuffer before the point.
2203 The contents of the minibuffer after the point are deleted, and replaced
2204 by the new completion."
2206 (next-complete-history-element (- n
)))
2208 ;; For compatibility with the old subr of the same name.
2209 (defun minibuffer-prompt-width ()
2210 "Return the display width of the minibuffer prompt.
2211 Return 0 if current buffer is not a minibuffer."
2212 ;; Return the width of everything before the field at the end of
2213 ;; the buffer; this should be 0 for normal buffers.
2214 (1- (minibuffer-prompt-end)))
2216 ;; isearch minibuffer history
2217 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
2219 (defvar minibuffer-history-isearch-message-overlay
)
2220 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
2222 (defun minibuffer-history-isearch-setup ()
2223 "Set up a minibuffer for using isearch to search the minibuffer history.
2224 Intended to be added to `minibuffer-setup-hook'."
2225 (set (make-local-variable 'isearch-search-fun-function
)
2226 'minibuffer-history-isearch-search
)
2227 (set (make-local-variable 'isearch-message-function
)
2228 'minibuffer-history-isearch-message
)
2229 (set (make-local-variable 'isearch-wrap-function
)
2230 'minibuffer-history-isearch-wrap
)
2231 (set (make-local-variable 'isearch-push-state-function
)
2232 'minibuffer-history-isearch-push-state
)
2233 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
2235 (defun minibuffer-history-isearch-end ()
2236 "Clean up the minibuffer after terminating isearch in the minibuffer."
2237 (if minibuffer-history-isearch-message-overlay
2238 (delete-overlay minibuffer-history-isearch-message-overlay
)))
2240 (defun minibuffer-history-isearch-search ()
2241 "Return the proper search function, for isearch in minibuffer history."
2242 (lambda (string bound noerror
)
2244 ;; Use standard functions to search within minibuffer text
2245 (isearch-search-fun-default))
2247 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2248 ;; searching forward. Lazy-highlight calls this lambda with the
2249 ;; bound arg, so skip the minibuffer prompt.
2250 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
2251 (goto-char (minibuffer-prompt-end)))
2253 ;; 1. First try searching in the initial minibuffer text
2254 (funcall search-fun string
2255 (if isearch-forward bound
(minibuffer-prompt-end))
2257 ;; 2. If the above search fails, start putting next/prev history
2258 ;; elements in the minibuffer successively, and search the string
2259 ;; in them. Do this only when bound is nil (i.e. not while
2260 ;; lazy-highlighting search strings in the current minibuffer text).
2265 (cond (isearch-forward
2266 (next-history-element 1)
2267 (goto-char (minibuffer-prompt-end)))
2269 (previous-history-element 1)
2270 (goto-char (point-max))))
2271 (setq isearch-barrier
(point) isearch-opoint
(point))
2272 ;; After putting the next/prev history element, search
2273 ;; the string in them again, until next-history-element
2274 ;; or previous-history-element raises an error at the
2275 ;; beginning/end of history.
2276 (setq found
(funcall search-fun string
2277 (unless isearch-forward
2278 ;; For backward search, don't search
2279 ;; in the minibuffer prompt
2280 (minibuffer-prompt-end))
2282 ;; Return point of the new search result
2284 ;; Return nil when next(prev)-history-element fails
2287 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
2288 "Display the minibuffer history search prompt.
2289 If there are no search errors, this function displays an overlay with
2290 the isearch prompt which replaces the original minibuffer prompt.
2291 Otherwise, it displays the standard isearch message returned from
2292 the function `isearch-message'."
2293 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
2294 ;; Use standard function `isearch-message' when not in the minibuffer,
2295 ;; or search fails, or has an error (like incomplete regexp).
2296 ;; This function overwrites minibuffer text with isearch message,
2297 ;; so it's possible to see what is wrong in the search string.
2298 (isearch-message c-q-hack ellipsis
)
2299 ;; Otherwise, put the overlay with the standard isearch prompt over
2300 ;; the initial minibuffer prompt.
2301 (if (overlayp minibuffer-history-isearch-message-overlay
)
2302 (move-overlay minibuffer-history-isearch-message-overlay
2303 (point-min) (minibuffer-prompt-end))
2304 (setq minibuffer-history-isearch-message-overlay
2305 (make-overlay (point-min) (minibuffer-prompt-end)))
2306 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
2307 (overlay-put minibuffer-history-isearch-message-overlay
2308 'display
(isearch-message-prefix c-q-hack ellipsis
))
2309 ;; And clear any previous isearch message.
2312 (defun minibuffer-history-isearch-wrap ()
2313 "Wrap the minibuffer history search when search fails.
2314 Move point to the first history element for a forward search,
2315 or to the last history element for a backward search."
2316 ;; When `minibuffer-history-isearch-search' fails on reaching the
2317 ;; beginning/end of the history, wrap the search to the first/last
2318 ;; minibuffer history element.
2320 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
2321 (goto-history-element 0))
2322 (setq isearch-success t
)
2323 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
2325 (defun minibuffer-history-isearch-push-state ()
2326 "Save a function restoring the state of minibuffer history search.
2327 Save `minibuffer-history-position' to the additional state parameter
2328 in the search status stack."
2329 (let ((pos minibuffer-history-position
))
2331 (minibuffer-history-isearch-pop-state cmd pos
))))
2333 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos
)
2334 "Restore the minibuffer history search state.
2335 Go to the history element by the absolute history position HIST-POS."
2336 (goto-history-element hist-pos
))
2339 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2340 (define-obsolete-function-alias 'advertised-undo
'undo
"23.2")
2342 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
2343 "Table mapping redo records to the corresponding undo one.
2344 A redo record for undo-in-region maps to t.
2345 A redo record for ordinary undo maps to the following (earlier) undo.")
2347 (defvar undo-in-region nil
2348 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2350 (defvar undo-no-redo nil
2351 "If t, `undo' doesn't go through redo entries.")
2353 (defvar pending-undo-list nil
2354 "Within a run of consecutive undo commands, list remaining to be undone.
2355 If t, we undid all the way to the end of it.")
2357 (defun undo (&optional arg
)
2358 "Undo some previous changes.
2359 Repeat this command to undo more changes.
2360 A numeric ARG serves as a repeat count.
2362 In Transient Mark mode when the mark is active, only undo changes within
2363 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2364 as an argument limits undo to changes within the current region."
2366 ;; Make last-command indicate for the next command that this was an undo.
2367 ;; That way, another undo will undo more.
2368 ;; If we get to the end of the undo history and get an error,
2369 ;; another undo command will find the undo history empty
2370 ;; and will get another error. To begin undoing the undos,
2371 ;; you must type some other command.
2372 (let* ((modified (buffer-modified-p))
2373 ;; For an indirect buffer, look in the base buffer for the
2375 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2376 (recent-save (with-current-buffer base-buffer
2377 (recent-auto-save-p)))
2379 ;; If we get an error in undo-start,
2380 ;; the next command should not be a "consecutive undo".
2381 ;; So set `this-command' to something other than `undo'.
2382 (setq this-command
'undo-start
)
2384 (unless (and (eq last-command
'undo
)
2385 (or (eq pending-undo-list t
)
2386 ;; If something (a timer or filter?) changed the buffer
2387 ;; since the previous command, don't continue the undo seq.
2388 (let ((list buffer-undo-list
))
2389 (while (eq (car list
) nil
)
2390 (setq list
(cdr list
)))
2391 ;; If the last undo record made was made by undo
2392 ;; it shows nothing else happened in between.
2393 (gethash list undo-equiv-table
))))
2394 (setq undo-in-region
2395 (or (region-active-p) (and arg
(not (numberp arg
)))))
2397 (undo-start (region-beginning) (region-end))
2399 ;; get rid of initial undo boundary
2401 ;; If we got this far, the next command should be a consecutive undo.
2402 (setq this-command
'undo
)
2403 ;; Check to see whether we're hitting a redo record, and if
2404 ;; so, ask the user whether she wants to skip the redo/undo pair.
2405 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
2406 (or (eq (selected-window) (minibuffer-window))
2407 (setq message
(format "%s%s!"
2408 (if (or undo-no-redo
(not equiv
))
2410 (if undo-in-region
" in region" ""))))
2411 (when (and (consp equiv
) undo-no-redo
)
2412 ;; The equiv entry might point to another redo record if we have done
2413 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2414 (while (let ((next (gethash equiv undo-equiv-table
)))
2415 (if next
(setq equiv next
))))
2416 (setq pending-undo-list equiv
)))
2419 (prefix-numeric-value arg
)
2421 ;; Record the fact that the just-generated undo records come from an
2422 ;; undo operation--that is, they are redo records.
2423 ;; In the ordinary case (not within a region), map the redo
2424 ;; record to the following undos.
2425 ;; I don't know how to do that in the undo-in-region case.
2426 (let ((list buffer-undo-list
))
2427 ;; Strip any leading undo boundaries there might be, like we do
2428 ;; above when checking.
2429 (while (eq (car list
) nil
)
2430 (setq list
(cdr list
)))
2432 ;; Prevent identity mapping. This can happen if
2433 ;; consecutive nils are erroneously in undo list.
2434 (if (or undo-in-region
(eq list pending-undo-list
))
2438 ;; Don't specify a position in the undo record for the undo command.
2439 ;; Instead, undoing this should move point to where the change is.
2440 (let ((tail buffer-undo-list
)
2443 (when (integerp (car tail
))
2444 (let ((pos (car tail
)))
2446 (setcdr prev
(cdr tail
))
2447 (setq buffer-undo-list
(cdr tail
)))
2448 (setq tail
(cdr tail
))
2450 (if (eq pos
(car tail
))
2452 (setcdr prev
(cdr tail
))
2453 (setq buffer-undo-list
(cdr tail
)))
2455 (setq tail
(cdr tail
)))
2457 (setq prev tail tail
(cdr tail
))))
2458 ;; Record what the current undo list says,
2459 ;; so the next command can tell if the buffer was modified in between.
2460 (and modified
(not (buffer-modified-p))
2461 (with-current-buffer base-buffer
2462 (delete-auto-save-file-if-necessary recent-save
)))
2463 ;; Display a message announcing success.
2465 (message "%s" message
))))
2467 (defun buffer-disable-undo (&optional buffer
)
2468 "Make BUFFER stop keeping undo information.
2469 No argument or nil as argument means do this for the current buffer."
2471 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
2472 (setq buffer-undo-list t
)))
2474 (defun undo-only (&optional arg
)
2475 "Undo some previous changes.
2476 Repeat this command to undo more changes.
2477 A numeric ARG serves as a repeat count.
2478 Contrary to `undo', this will not redo a previous undo."
2480 (let ((undo-no-redo t
)) (undo arg
)))
2482 (defvar undo-in-progress nil
2483 "Non-nil while performing an undo.
2484 Some change-hooks test this variable to do something different.")
2486 (defun undo-more (n)
2487 "Undo back N undo-boundaries beyond what was already undone recently.
2488 Call `undo-start' to get ready to undo recent changes,
2489 then call `undo-more' one or more times to undo them."
2490 (or (listp pending-undo-list
)
2491 (user-error (concat "No further undo information"
2492 (and undo-in-region
" for region"))))
2493 (let ((undo-in-progress t
))
2494 ;; Note: The following, while pulling elements off
2495 ;; `pending-undo-list' will call primitive change functions which
2496 ;; will push more elements onto `buffer-undo-list'.
2497 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
2498 (if (null pending-undo-list
)
2499 (setq pending-undo-list t
))))
2501 (defun primitive-undo (n list
)
2502 "Undo N records from the front of the list LIST.
2503 Return what remains of the list."
2505 ;; This is a good feature, but would make undo-start
2506 ;; unable to do what is expected.
2507 ;;(when (null (car (list)))
2508 ;; ;; If the head of the list is a boundary, it is the boundary
2509 ;; ;; preceding this command. Get rid of it and don't count it.
2510 ;; (setq list (cdr list))))
2513 ;; In a writable buffer, enable undoing read-only text that is
2514 ;; so because of text properties.
2515 (inhibit-read-only t
)
2516 ;; Don't let `intangible' properties interfere with undo.
2517 (inhibit-point-motion-hooks t
)
2518 ;; We use oldlist only to check for EQ. ++kfs
2519 (oldlist buffer-undo-list
)
2523 (while (setq next
(pop list
)) ;Exit inner loop at undo boundary.
2524 ;; Handle an integer by setting point to that value.
2526 ((pred integerp
) (goto-char next
))
2527 ;; Element (t . TIME) records previous modtime.
2528 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2529 ;; UNKNOWN_MODTIME_NSECS.
2531 ;; If this records an obsolete save
2532 ;; (not matching the actual disk file)
2533 ;; then don't mark unmodified.
2534 (when (or (equal time
(visited-file-modtime))
2536 (equal (list (car time
) (cdr time
))
2537 (visited-file-modtime))))
2538 (when (fboundp 'unlock-buffer
)
2540 (set-buffer-modified-p nil
)))
2541 ;; Element (nil PROP VAL BEG . END) is property change.
2542 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2543 (when (or (> (point-min) beg
) (< (point-max) end
))
2544 (error "Changes to be undone are outside visible portion of buffer"))
2545 (put-text-property beg end prop val
))
2546 ;; Element (BEG . END) means range was inserted.
2547 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2548 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2549 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2550 (when (or (> (point-min) beg
) (< (point-max) end
))
2551 (error "Changes to be undone are outside visible portion of buffer"))
2552 ;; Set point first thing, so that undoing this undo
2553 ;; does not send point back to where it is now.
2555 (delete-region beg end
))
2556 ;; Element (apply FUN . ARGS) means call FUN to undo.
2557 (`(apply .
,fun-args
)
2558 (let ((currbuff (current-buffer)))
2559 (if (integerp (car fun-args
))
2560 ;; Long format: (apply DELTA START END FUN . ARGS).
2561 (pcase-let* ((`(,delta
,start
,end
,fun .
,args
) fun-args
)
2562 (start-mark (copy-marker start nil
))
2563 (end-mark (copy-marker end t
)))
2564 (when (or (> (point-min) start
) (< (point-max) end
))
2565 (error "Changes to be undone are outside visible portion of buffer"))
2566 (apply fun args
) ;; Use `save-current-buffer'?
2567 ;; Check that the function did what the entry
2568 ;; said it would do.
2569 (unless (and (= start start-mark
)
2570 (= (+ delta end
) end-mark
))
2571 (error "Changes to be undone by function different than announced"))
2572 (set-marker start-mark nil
)
2573 (set-marker end-mark nil
))
2575 (unless (eq currbuff
(current-buffer))
2576 (error "Undo function switched buffer"))
2577 (setq did-apply t
)))
2578 ;; Element (STRING . POS) means STRING was deleted.
2579 (`(,(and string
(pred stringp
)) .
,(and pos
(pred integerp
)))
2580 (let ((valid-marker-adjustments nil
)
2582 (when (or (< apos
(point-min)) (> apos
(point-max)))
2583 (error "Changes to be undone are outside visible portion of buffer"))
2584 ;; Check that marker adjustments which were recorded
2585 ;; with the (STRING . POS) record are still valid, ie
2586 ;; the markers haven't moved. We check their validity
2587 ;; before reinserting the string so as we don't need to
2588 ;; mind marker insertion-type.
2589 (while (and (markerp (car-safe (car list
)))
2590 (integerp (cdr-safe (car list
))))
2591 (let* ((marker-adj (pop list
))
2592 (m (car marker-adj
)))
2593 (and (eq (marker-buffer m
) (current-buffer))
2595 (push marker-adj valid-marker-adjustments
))))
2596 ;; Insert string and adjust point
2604 ;; Adjust the valid marker adjustments
2605 (dolist (adj valid-marker-adjustments
)
2606 ;; Insert might have invalidated some of the markers
2607 ;; via modification hooks. Update only the currently
2608 ;; valid ones (bug#25599).
2609 (if (marker-buffer (car adj
))
2610 (set-marker (car adj
)
2611 (- (car adj
) (cdr adj
)))))))
2612 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2613 (`(,(and marker
(pred markerp
)) .
,(and offset
(pred integerp
)))
2614 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2616 ;; Even though these elements are not expected in the undo
2617 ;; list, adjust them to be conservative for the 24.4
2618 ;; release. (Bug#16818)
2619 (when (marker-buffer marker
)
2622 (marker-buffer marker
))))
2623 (_ (error "Unrecognized entry in undo list %S" next
))))
2624 (setq arg
(1- arg
)))
2625 ;; Make sure an apply entry produces at least one undo entry,
2626 ;; so the test in `undo' for continuing an undo series
2629 (eq oldlist buffer-undo-list
))
2630 (setq buffer-undo-list
2631 (cons (list 'apply
'cdr nil
) buffer-undo-list
))))
2634 ;; Deep copy of a list
2635 (defun undo-copy-list (list)
2636 "Make a copy of undo list LIST."
2637 (mapcar 'undo-copy-list-1 list
))
2639 (defun undo-copy-list-1 (elt)
2641 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
2644 (defun undo-start (&optional beg end
)
2645 "Set `pending-undo-list' to the front of the undo list.
2646 The next call to `undo-more' will undo the most recently made change.
2647 If BEG and END are specified, then only undo elements
2648 that apply to text between BEG and END are used; other undo elements
2649 are ignored. If BEG and END are nil, all undo elements are used."
2650 (if (eq buffer-undo-list t
)
2651 (user-error "No undo information in this buffer"))
2652 (setq pending-undo-list
2653 (if (and beg end
(not (= beg end
)))
2654 (undo-make-selective-list (min beg end
) (max beg end
))
2657 ;; The positions given in elements of the undo list are the positions
2658 ;; as of the time that element was recorded to undo history. In
2659 ;; general, subsequent buffer edits render those positions invalid in
2660 ;; the current buffer, unless adjusted according to the intervening
2663 ;; Undo in region is a use case that requires adjustments to undo
2664 ;; elements. It must adjust positions of elements in the region based
2665 ;; on newer elements not in the region so as they may be correctly
2666 ;; applied in the current buffer. undo-make-selective-list
2667 ;; accomplishes this with its undo-deltas list of adjustments. An
2668 ;; example undo history from oldest to newest:
2671 ;; 123456789 buffer-undo-list undo-deltas
2672 ;; --------- ---------------- -----------
2673 ;; aaa (1 . 4) (1 . -3)
2674 ;; aaba (3 . 4) N/A (in region)
2675 ;; ccaaba (1 . 3) (1 . -2)
2676 ;; ccaabaddd (7 . 10) (7 . -3)
2677 ;; ccaabdd ("ad" . 6) (6 . 2)
2678 ;; ccaabaddd (6 . 8) (6 . -2)
2679 ;; | |<-- region: "caab", from 2 to 6
2681 ;; When the user starts a run of undos in region,
2682 ;; undo-make-selective-list is called to create the full list of in
2683 ;; region elements. Each element is adjusted forward chronologically
2684 ;; through undo-deltas to determine if it is in the region.
2686 ;; In the above example, the insertion of "b" is (3 . 4) in the
2687 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2688 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2689 ;; . 6) is assessed as in the region and placed in the selective list.
2690 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2691 ;; due to the selected element. The "b" insertion is the only element
2692 ;; fully in the region, so in this example undo-make-selective-list
2693 ;; returns (nil (5 . 6)).
2695 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2696 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2697 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2698 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2699 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2701 ;; More interesting is how to adjust the "ddd" insertion due to the
2702 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2703 ;; If the reinsertion was a manual retyping of "ad", then the total
2704 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2705 ;; the reinsertion was due to undo, one might expect the first "d"
2706 ;; character would again be a part of the "ddd" text, meaning its
2707 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2709 ;; undo-make-selective-list assumes in this situation that "ad" was a
2710 ;; new edit, even if it was inserted because of an undo.
2711 ;; Consequently, if the user undos in region "8 to 10" of the
2712 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2713 ;; "ccaabad", as though the first "d" became detached from the
2714 ;; original "ddd" insertion. This quirk is a FIXME.
2716 (defun undo-make-selective-list (start end
)
2717 "Return a list of undo elements for the region START to END.
2718 The elements come from `buffer-undo-list', but we keep only the
2719 elements inside this region, and discard those outside this
2720 region. The elements' positions are adjusted so as the returned
2721 list can be applied to the current buffer."
2722 (let ((ulist buffer-undo-list
)
2723 ;; A list of position adjusted undo elements in the region.
2724 (selective-list (list nil
))
2725 ;; A list of undo-deltas for out of region undo elements.
2730 (while (gethash ulist undo-equiv-table
)
2731 (setq ulist
(gethash ulist undo-equiv-table
))))
2732 (setq undo-elt
(car ulist
))
2735 ;; Don't put two nils together in the list
2736 (when (car selective-list
)
2737 (push nil selective-list
)))
2738 ((and (consp undo-elt
) (eq (car undo-elt
) t
))
2739 ;; This is a "was unmodified" element. Keep it
2740 ;; if we have kept everything thus far.
2741 (when (not undo-deltas
)
2742 (push undo-elt selective-list
)))
2743 ;; Skip over marker adjustments, instead relying
2744 ;; on finding them after (TEXT . POS) elements
2745 ((markerp (car-safe undo-elt
))
2748 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2750 (if (undo-elt-in-region adjusted-undo-elt start end
)
2752 (setq end
(+ end
(cdr (undo-delta adjusted-undo-elt
))))
2753 (push adjusted-undo-elt selective-list
)
2754 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2755 ;; kept. primitive-undo may discard them later.
2756 (when (and (stringp (car-safe adjusted-undo-elt
))
2757 (integerp (cdr-safe adjusted-undo-elt
)))
2758 (let ((list-i (cdr ulist
)))
2759 (while (markerp (car-safe (car list-i
)))
2760 (push (pop list-i
) selective-list
)))))
2761 (let ((delta (undo-delta undo-elt
)))
2762 (when (/= 0 (cdr delta
))
2763 (push delta undo-deltas
)))))))
2765 (nreverse selective-list
)))
2767 (defun undo-elt-in-region (undo-elt start end
)
2768 "Determine whether UNDO-ELT falls inside the region START ... END.
2769 If it crosses the edge, we return nil.
2771 Generally this function is not useful for determining
2772 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2773 because markers can be arbitrarily relocated. Instead, pass the
2774 marker adjustment's corresponding (TEXT . POS) element."
2775 (cond ((integerp undo-elt
)
2776 (and (>= undo-elt start
)
2782 ((stringp (car undo-elt
))
2783 ;; (TEXT . POSITION)
2784 (and (>= (abs (cdr undo-elt
)) start
)
2785 (<= (abs (cdr undo-elt
)) end
)))
2786 ((and (consp undo-elt
) (markerp (car undo-elt
)))
2787 ;; (MARKER . ADJUSTMENT)
2788 (<= start
(car undo-elt
) end
))
2789 ((null (car undo-elt
))
2790 ;; (nil PROPERTY VALUE BEG . END)
2791 (let ((tail (nthcdr 3 undo-elt
)))
2792 (and (>= (car tail
) start
)
2793 (<= (cdr tail
) end
))))
2794 ((integerp (car undo-elt
))
2796 (and (>= (car undo-elt
) start
)
2797 (<= (cdr undo-elt
) end
)))))
2799 (defun undo-elt-crosses-region (undo-elt start end
)
2800 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2801 This assumes we have already decided that UNDO-ELT
2802 is not *inside* the region START...END."
2803 (declare (obsolete nil
"25.1"))
2804 (cond ((atom undo-elt
) nil
)
2805 ((null (car undo-elt
))
2806 ;; (nil PROPERTY VALUE BEG . END)
2807 (let ((tail (nthcdr 3 undo-elt
)))
2808 (and (< (car tail
) end
)
2809 (> (cdr tail
) start
))))
2810 ((integerp (car undo-elt
))
2812 (and (< (car undo-elt
) end
)
2813 (> (cdr undo-elt
) start
)))))
2815 (defun undo-adjust-elt (elt deltas
)
2816 "Return adjustment of undo element ELT by the undo DELTAS
2821 (undo-adjust-pos elt deltas
))
2823 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2824 (undo-adjust-beg-end beg end deltas
))
2825 ;; (TEXT . POSITION)
2826 (`(,(and text
(pred stringp
)) .
,(and pos
(pred integerp
)))
2827 (cons text
(* (if (< pos
0) -
1 1)
2828 (undo-adjust-pos (abs pos
) deltas
))))
2829 ;; (nil PROPERTY VALUE BEG . END)
2830 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2831 `(nil ,prop
,val .
,(undo-adjust-beg-end beg end deltas
)))
2832 ;; (apply DELTA START END FUN . ARGS)
2834 ;; All others return same elt
2837 ;; (BEG . END) can adjust to the same positions, commonly when an
2838 ;; insertion was undone and they are out of region, for example:
2841 ;; 123456789 buffer-undo-list undo-deltas
2842 ;; --------- ---------------- -----------
2844 ;; abbaa (2 . 4) (2 . -2)
2845 ;; aaa ("bb" . 2) (2 . 2)
2848 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2849 ;; undo. Further adjustments to such an element should be the same as
2850 ;; for (TEXT . POSITION) elements. The options are:
2852 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2853 ;; analogous to marker insertion-type t.
2855 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2856 ;; marker insertion-type nil.
2858 ;; There was no strong reason to prefer one or the other, except that
2859 ;; the first is more consistent with prior undo in region behavior.
2860 (defun undo-adjust-beg-end (beg end deltas
)
2861 "Return cons of adjustments to BEG and END by the undo DELTAS
2863 (let ((adj-beg (undo-adjust-pos beg deltas
)))
2864 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2866 (max adj-beg
(undo-adjust-pos end deltas t
)))))
2868 (defun undo-adjust-pos (pos deltas
&optional use-
<)
2869 "Return adjustment of POS by the undo DELTAS list, comparing
2870 with < or <= based on USE-<."
2871 (dolist (d deltas pos
)
2876 ;; Don't allow pos to become less than the undo-delta
2877 ;; position. This edge case is described in the overview
2879 (max (car d
) (- pos
(cdr d
)))))))
2881 ;; Return the first affected buffer position and the delta for an undo element
2882 ;; delta is defined as the change in subsequent buffer positions if we *did*
2884 (defun undo-delta (undo-elt)
2885 (if (consp undo-elt
)
2886 (cond ((stringp (car undo-elt
))
2887 ;; (TEXT . POSITION)
2888 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
2889 ((integerp (car undo-elt
))
2891 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
2896 ;;; Default undo-boundary addition
2898 ;; This section adds a new undo-boundary at either after a command is
2899 ;; called or in some cases on a timer called after a change is made in
2901 (defvar-local undo-auto--last-boundary-cause nil
2902 "Describe the cause of the last undo-boundary.
2904 If `explicit', the last boundary was caused by an explicit call to
2905 `undo-boundary', that is one not called by the code in this
2908 If it is equal to `timer', then the last boundary was inserted
2909 by `undo-auto--boundary-timer'.
2911 If it is equal to `command', then the last boundary was inserted
2912 automatically after a command, that is by the code defined in
2915 If it is equal to a list, then the last boundary was inserted by
2916 an amalgamating command. The car of the list is the number of
2917 times an amalgamating command has been called, and the cdr are the
2918 buffers that were changed during the last command.")
2920 (defvar undo-auto-current-boundary-timer nil
2921 "Current timer which will run `undo-auto--boundary-timer' or nil.
2923 If set to non-nil, this will effectively disable the timer.")
2925 (defvar undo-auto--this-command-amalgamating nil
2926 "Non-nil if `this-command' should be amalgamated.
2927 This variable is set to nil by `undo-auto--boundaries' and is set
2928 by `undo-auto-amalgamate'." )
2930 (defun undo-auto--needs-boundary-p ()
2931 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2932 (car-safe buffer-undo-list
))
2934 (defun undo-auto--last-boundary-amalgamating-number ()
2935 "Return the number of amalgamating last commands or nil.
2936 Amalgamating commands are, by default, either
2937 `self-insert-command' and `delete-char', but can be any command
2938 that calls `undo-auto-amalgamate'."
2939 (car-safe undo-auto--last-boundary-cause
))
2941 (defun undo-auto--ensure-boundary (cause)
2942 "Add an `undo-boundary' to the current buffer if needed.
2943 REASON describes the reason that the boundary is being added; see
2944 `undo-auto--last-boundary' for more information."
2946 (undo-auto--needs-boundary-p))
2947 (let ((last-amalgamating
2948 (undo-auto--last-boundary-amalgamating-number)))
2950 (setq undo-auto--last-boundary-cause
2951 (if (eq 'amalgamate cause
)
2953 (if last-amalgamating
(1+ last-amalgamating
) 0)
2954 undo-auto--undoably-changed-buffers
)
2957 (defun undo-auto--boundaries (cause)
2958 "Check recently changed buffers and add a boundary if necessary.
2959 REASON describes the reason that the boundary is being added; see
2960 `undo-last-boundary' for more information."
2961 ;; (Bug #23785) All commands should ensure that there is an undo
2962 ;; boundary whether they have changed the current buffer or not.
2963 (when (eq cause
'command
)
2964 (add-to-list 'undo-auto--undoably-changed-buffers
(current-buffer)))
2965 (dolist (b undo-auto--undoably-changed-buffers
)
2966 (when (buffer-live-p b
)
2967 (with-current-buffer b
2968 (undo-auto--ensure-boundary cause
))))
2969 (setq undo-auto--undoably-changed-buffers nil
))
2971 (defun undo-auto--boundary-timer ()
2972 "Timer function run by `undo-auto-current-boundary-timer'."
2973 (setq undo-auto-current-boundary-timer nil
)
2974 (undo-auto--boundaries 'timer
))
2976 (defun undo-auto--boundary-ensure-timer ()
2977 "Ensure that the `undo-auto-current-boundary-timer' is set."
2978 (unless undo-auto-current-boundary-timer
2979 (setq undo-auto-current-boundary-timer
2980 (run-at-time 10 nil
#'undo-auto--boundary-timer
))))
2982 (defvar undo-auto--undoably-changed-buffers nil
2983 "List of buffers that have changed recently.
2985 This list is maintained by `undo-auto--undoable-change' and
2986 `undo-auto--boundaries' and can be affected by changes to their
2989 (defun undo-auto--add-boundary ()
2990 "Add an `undo-boundary' in appropriate buffers."
2991 (undo-auto--boundaries
2992 (let ((amal undo-auto--this-command-amalgamating
))
2993 (setq undo-auto--this-command-amalgamating nil
)
2998 (defun undo-auto-amalgamate ()
2999 "Amalgamate undo if necessary.
3000 This function can be called before an amalgamating command. It
3001 removes the previous `undo-boundary' if a series of such calls
3002 have been made. By default `self-insert-command' and
3003 `delete-char' are the only amalgamating commands, although this
3004 function could be called by any command wishing to have this
3006 (let ((last-amalgamating-count
3007 (undo-auto--last-boundary-amalgamating-number)))
3008 (setq undo-auto--this-command-amalgamating t
)
3010 last-amalgamating-count
3013 (< last-amalgamating-count
20)
3014 (eq this-command last-command
))
3015 ;; Amalgamate all buffers that have changed.
3016 (dolist (b (cdr undo-auto--last-boundary-cause
))
3017 (when (buffer-live-p b
)
3018 (with-current-buffer
3021 ;; The head of `buffer-undo-list' is nil.
3022 ;; `car-safe' doesn't work because
3023 ;; `buffer-undo-list' need not be a list!
3024 (and (listp buffer-undo-list
)
3025 (not (car buffer-undo-list
)))
3026 (setq buffer-undo-list
3027 (cdr buffer-undo-list
))))))
3028 (setq undo-auto--last-boundary-cause
0)))))
3030 (defun undo-auto--undoable-change ()
3031 "Called after every undoable buffer change."
3032 (add-to-list 'undo-auto--undoably-changed-buffers
(current-buffer))
3033 (undo-auto--boundary-ensure-timer))
3034 ;; End auto-boundary section
3036 (defun undo-amalgamate-change-group (handle)
3037 "Amalgamate changes in change-group since HANDLE.
3038 Remove all undo boundaries between the state of HANDLE and now.
3039 HANDLE is as returned by `prepare-change-group'."
3040 (dolist (elt handle
)
3041 (with-current-buffer (car elt
)
3042 (setq elt
(cdr elt
))
3043 (when (consp buffer-undo-list
)
3044 (let ((old-car (car-safe elt
))
3045 (old-cdr (cdr-safe elt
)))
3048 ;; Temporarily truncate the undo log at ELT.
3050 (setcar elt t
) (setcdr elt nil
))
3052 (or (null elt
) ;The undo-log was empty.
3053 ;; `elt' is still in the log: normal case.
3054 (eq elt
(last buffer-undo-list
))
3055 ;; `elt' is not in the log any more, but that's because
3056 ;; the log is "all new", so we should remove all
3057 ;; boundaries from it.
3058 (not (eq (last buffer-undo-list
) (last old-cdr
))))
3059 (cl-callf (lambda (x) (delq nil x
))
3060 (if (car buffer-undo-list
)
3062 ;; Preserve the undo-boundaries at either ends of the
3064 (cdr buffer-undo-list
)))))
3065 ;; Reset the modified cons cell ELT to its original content.
3067 (setcar elt old-car
)
3068 (setcdr elt old-cdr
))))))))
3071 (defcustom undo-ask-before-discard nil
3072 "If non-nil ask about discarding undo info for the current command.
3073 Normally, Emacs discards the undo info for the current command if
3074 it exceeds `undo-outer-limit'. But if you set this option
3075 non-nil, it asks in the echo area whether to discard the info.
3076 If you answer no, there is a slight risk that Emacs might crash, so
3077 only do it if you really want to undo the command.
3079 This option is mainly intended for debugging. You have to be
3080 careful if you use it for other purposes. Garbage collection is
3081 inhibited while the question is asked, meaning that Emacs might
3082 leak memory. So you should make sure that you do not wait
3083 excessively long before answering the question."
3088 (defvar undo-extra-outer-limit nil
3089 "If non-nil, an extra level of size that's ok in an undo item.
3090 We don't ask the user about truncating the undo list until the
3091 current item gets bigger than this amount.
3093 This variable only matters if `undo-ask-before-discard' is non-nil.")
3094 (make-variable-buffer-local 'undo-extra-outer-limit
)
3096 ;; When the first undo batch in an undo list is longer than
3097 ;; undo-outer-limit, this function gets called to warn the user that
3098 ;; the undo info for the current command was discarded. Garbage
3099 ;; collection is inhibited around the call, so it had better not do a
3101 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
3102 (defun undo-outer-limit-truncate (size)
3103 (if undo-ask-before-discard
3104 (when (or (null undo-extra-outer-limit
)
3105 (> size undo-extra-outer-limit
))
3106 ;; Don't ask the question again unless it gets even bigger.
3107 ;; This applies, in particular, if the user quits from the question.
3108 ;; Such a quit quits out of GC, but something else will call GC
3109 ;; again momentarily. It will call this function again,
3110 ;; but we don't want to ask the question again.
3111 (setq undo-extra-outer-limit
(+ size
50000))
3112 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
3113 (yes-or-no-p (format-message
3114 "Buffer `%s' undo info is %d bytes long; discard it? "
3115 (buffer-name) size
)))
3116 (progn (setq buffer-undo-list nil
)
3117 (setq undo-extra-outer-limit nil
)
3120 (display-warning '(undo discard-info
)
3123 "Buffer `%s' undo info was %d bytes long.\n"
3125 "The undo info was discarded because it exceeded \
3128 This is normal if you executed a command that made a huge change
3129 to the buffer. In that case, to prevent similar problems in the
3130 future, set `undo-outer-limit' to a value that is large enough to
3131 cover the maximum size of normal changes you expect a single
3132 command to make, but not so large that it might exceed the
3133 maximum memory allotted to Emacs.
3135 If you did not execute any such command, the situation is
3136 probably due to a bug and you should report it.
3138 You can disable the popping up of this buffer by adding the entry
3139 \(undo discard-info) to the user option `warning-suppress-types',
3140 which is defined in the `warnings' library.\n")
3142 (setq buffer-undo-list nil
)
3145 (defcustom password-word-equivalents
3146 '("password" "passcode" "passphrase" "pass phrase"
3147 ; These are sorted according to the GNU en_US locale.
3150 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3176 "пароль" ; kk, ru, uk
3191 "List of words equivalent to \"password\".
3192 This is used by Shell mode and other parts of Emacs to recognize
3193 password prompts, including prompts in languages other than
3194 English. Different case choices should not be assumed to be
3195 included; callers should bind `case-fold-search' to t."
3196 :type
'(repeat string
)
3200 (defvar shell-command-history nil
3201 "History list for some commands that read shell commands.
3203 Maximum length of the history list is determined by the value
3204 of `history-length', which see.")
3206 (defvar shell-command-switch
(purecopy "-c")
3207 "Switch used to have the shell execute its command line argument.")
3209 (defvar shell-command-default-error-buffer nil
3210 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3211 This buffer is used when `shell-command' or `shell-command-on-region'
3212 is run interactively. A value of nil means that output to stderr and
3213 stdout will be intermixed in the output stream.")
3215 (declare-function mailcap-file-default-commands
"mailcap" (files))
3216 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
3218 (defun minibuffer-default-add-shell-commands ()
3219 "Return a list of all commands associated with the current file.
3220 This function is used to add all related commands retrieved by `mailcap'
3221 to the end of the list of defaults just after the default value."
3223 (let* ((filename (if (listp minibuffer-default
)
3224 (car minibuffer-default
)
3225 minibuffer-default
))
3226 (commands (and filename
(require 'mailcap nil t
)
3227 (mailcap-file-default-commands (list filename
)))))
3228 (setq commands
(mapcar (lambda (command)
3229 (concat command
" " filename
))
3231 (if (listp minibuffer-default
)
3232 (append minibuffer-default commands
)
3233 (cons minibuffer-default commands
))))
3235 (declare-function shell-completion-vars
"shell" ())
3237 (defvar minibuffer-local-shell-command-map
3238 (let ((map (make-sparse-keymap)))
3239 (set-keymap-parent map minibuffer-local-map
)
3240 (define-key map
"\t" 'completion-at-point
)
3242 "Keymap used for completing shell commands in minibuffer.")
3244 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
3245 "Read a shell command from the minibuffer.
3246 The arguments are the same as the ones of `read-from-minibuffer',
3247 except READ and KEYMAP are missing and HIST defaults
3248 to `shell-command-history'."
3250 (minibuffer-with-setup-hook
3252 (shell-completion-vars)
3253 (set (make-local-variable 'minibuffer-default-add-function
)
3254 'minibuffer-default-add-shell-commands
))
3255 (apply 'read-from-minibuffer prompt initial-contents
3256 minibuffer-local-shell-command-map
3258 (or hist
'shell-command-history
)
3261 (defcustom async-shell-command-buffer
'confirm-new-buffer
3262 "What to do when the output buffer is used by another shell command.
3263 This option specifies how to resolve the conflict where a new command
3264 wants to direct its output to the buffer `*Async Shell Command*',
3265 but this buffer is already taken by another running shell command.
3267 The value `confirm-kill-process' is used to ask for confirmation before
3268 killing the already running process and running a new process
3269 in the same buffer, `confirm-new-buffer' for confirmation before running
3270 the command in a new buffer with a name other than the default buffer name,
3271 `new-buffer' for doing the same without confirmation,
3272 `confirm-rename-buffer' for confirmation before renaming the existing
3273 output buffer and running a new command in the default buffer,
3274 `rename-buffer' for doing the same without confirmation."
3275 :type
'(choice (const :tag
"Confirm killing of running command"
3276 confirm-kill-process
)
3277 (const :tag
"Confirm creation of a new buffer"
3279 (const :tag
"Create a new buffer"
3281 (const :tag
"Confirm renaming of existing buffer"
3282 confirm-rename-buffer
)
3283 (const :tag
"Rename the existing buffer"
3288 (defcustom async-shell-command-display-buffer t
3289 "Whether to display the command buffer immediately.
3290 If t, display the buffer immediately; if nil, wait until there
3292 :type
'(choice (const :tag
"Display buffer immediately"
3294 (const :tag
"Display buffer on output"
3299 (defun shell-command--save-pos-or-erase ()
3300 "Store a buffer position or erase the buffer.
3301 See `shell-command-dont-erase-buffer'."
3302 (let ((sym shell-command-dont-erase-buffer
)
3304 (setq buffer-read-only nil
)
3305 ;; Setting buffer-read-only to nil doesn't suffice
3306 ;; if some text has a non-nil read-only property,
3307 ;; which comint sometimes adds for prompts.
3309 (cond ((eq sym
'save-point
) (point))
3310 ((eq sym
'beg-last-out
) (point-max))
3312 (let ((inhibit-read-only t
))
3313 (erase-buffer) nil
))))
3315 (goto-char (point-max))
3316 (push (cons (current-buffer) pos
)
3317 shell-command-saved-pos
))))
3319 (defun shell-command--set-point-after-cmd (&optional buffer
)
3320 "Set point in BUFFER after command complete.
3321 BUFFER is the output buffer of the command; if nil, then defaults
3322 to the current BUFFER.
3323 Set point to the `cdr' of the element in `shell-command-saved-pos'
3324 whose `car' is BUFFER."
3325 (when shell-command-dont-erase-buffer
3326 (let* ((sym shell-command-dont-erase-buffer
)
3327 (buf (or buffer
(current-buffer)))
3328 (pos (alist-get buf shell-command-saved-pos
)))
3329 (setq shell-command-saved-pos
3330 (assq-delete-all buf shell-command-saved-pos
))
3331 (when (buffer-live-p buf
)
3332 (let ((win (car (get-buffer-window-list buf
)))
3333 (pmax (with-current-buffer buf
(point-max))))
3334 (unless (and pos
(memq sym
'(save-point beg-last-out
)))
3336 ;; Set point in the window displaying buf, if any; otherwise
3337 ;; display buf temporary in selected frame and set the point.
3339 (set-window-point win pos
)
3340 (save-window-excursion
3341 (let ((win (display-buffer
3343 '(nil (inhibit-switch-frame . t
)))))
3344 (set-window-point win pos
)))))))))
3346 (defun async-shell-command (command &optional output-buffer error-buffer
)
3347 "Execute string COMMAND asynchronously in background.
3349 Like `shell-command', but adds `&' at the end of COMMAND
3350 to execute it asynchronously.
3352 The output appears in the buffer `*Async Shell Command*'.
3353 That buffer is in shell mode.
3355 You can configure `async-shell-command-buffer' to specify what to do
3356 when the `*Async Shell Command*' buffer is already taken by another
3357 running shell command. To run COMMAND without displaying the output
3358 in a window you can configure `display-buffer-alist' to use the action
3359 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3361 In Elisp, you will often be better served by calling `start-process'
3362 directly, since it offers more control and does not impose the use of
3363 a shell (with its need to quote arguments)."
3366 (read-shell-command "Async shell command: " nil nil
3370 ((eq major-mode
'dired-mode
)
3371 (dired-get-filename nil t
)))))
3372 (and filename
(file-relative-name filename
))))
3374 shell-command-default-error-buffer
))
3375 (unless (string-match "&[ \t]*\\'" command
)
3376 (setq command
(concat command
" &")))
3377 (shell-command command output-buffer error-buffer
))
3379 (defun shell-command (command &optional output-buffer error-buffer
)
3380 "Execute string COMMAND in inferior shell; display output, if any.
3381 With prefix argument, insert the COMMAND's output at point.
3383 Interactively, prompt for COMMAND in the minibuffer.
3385 If COMMAND ends in `&', execute it asynchronously.
3386 The output appears in the buffer `*Async Shell Command*'.
3387 That buffer is in shell mode. You can also use
3388 `async-shell-command' that automatically adds `&'.
3390 Otherwise, COMMAND is executed synchronously. The output appears in
3391 the buffer `*Shell Command Output*'. If the output is short enough to
3392 display in the echo area (which is determined by the variables
3393 `resize-mini-windows' and `max-mini-window-height'), it is shown
3394 there, but it is nonetheless available in buffer `*Shell Command
3395 Output*' even though that buffer is not automatically displayed.
3397 To specify a coding system for converting non-ASCII characters
3398 in the shell command output, use \\[universal-coding-system-argument] \
3399 before this command.
3401 Noninteractive callers can specify coding systems by binding
3402 `coding-system-for-read' and `coding-system-for-write'.
3404 The optional second argument OUTPUT-BUFFER, if non-nil,
3405 says to put the output in some other buffer.
3406 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3407 and insert the output there; a non-nil value of
3408 `shell-command-dont-erase-buffer' prevents the buffer from being
3409 erased. If OUTPUT-BUFFER is not a buffer and not nil, insert the
3410 output in current buffer after point leaving mark after it. This
3411 cannot be done asynchronously.
3413 If the command terminates without error, but generates output,
3414 and you did not specify \"insert it in the current buffer\",
3415 the output can be displayed in the echo area or in its buffer.
3416 If the output is short enough to display in the echo area
3417 \(determined by the variable `max-mini-window-height' if
3418 `resize-mini-windows' is non-nil), it is shown there.
3419 Otherwise, the buffer containing the output is displayed.
3421 If there is output and an error, and you did not specify \"insert it
3422 in the current buffer\", a message about the error goes at the end
3425 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3426 or buffer name to which to direct the command's standard error output.
3427 If it is nil, error output is mingled with regular output.
3428 In an interactive call, the variable `shell-command-default-error-buffer'
3429 specifies the value of ERROR-BUFFER.
3431 In Elisp, you will often be better served by calling `call-process' or
3432 `start-process' directly, since they offer more control and do not
3433 impose the use of a shell (with its need to quote arguments)."
3437 (read-shell-command "Shell command: " nil nil
3441 ((eq major-mode
'dired-mode
)
3442 (dired-get-filename nil t
)))))
3443 (and filename
(file-relative-name filename
))))
3445 shell-command-default-error-buffer
))
3446 ;; Look for a handler in case default-directory is a remote file name.
3448 (find-file-name-handler (directory-file-name default-directory
)
3451 (funcall handler
'shell-command command output-buffer error-buffer
)
3452 (if (and output-buffer
3453 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
3454 ;; Output goes in current buffer.
3458 (expand-file-name "scor"
3459 (or small-temporary-file-directory
3460 temporary-file-directory
)))
3462 (barf-if-buffer-read-only)
3464 ;; We do not use -f for csh; we will not support broken use of
3465 ;; .cshrcs. Even the BSD csh manual says to use
3466 ;; "if ($?prompt) exit" before things which are not useful
3467 ;; non-interactively. Besides, if someone wants their other
3468 ;; aliases for shell commands then they can still have them.
3469 (call-process shell-file-name nil
3473 nil shell-command-switch command
)
3474 (when (and error-file
(file-exists-p error-file
))
3475 (if (< 0 (nth 7 (file-attributes error-file
)))
3476 (with-current-buffer (get-buffer-create error-buffer
)
3477 (let ((pos-from-end (- (point-max) (point))))
3480 ;; Do no formatting while reading error file,
3481 ;; because that can run a shell command, and we
3482 ;; don't want that to cause an infinite recursion.
3483 (format-insert-file error-file nil
)
3484 ;; Put point after the inserted errors.
3485 (goto-char (- (point-max) pos-from-end
)))
3486 (display-buffer (current-buffer))))
3487 (delete-file error-file
))
3488 ;; This is like exchange-point-and-mark, but doesn't
3489 ;; activate the mark. It is cleaner to avoid activation,
3490 ;; even though the command loop would deactivate the mark
3491 ;; because we inserted text.
3492 (goto-char (prog1 (mark t
)
3493 (set-marker (mark-marker) (point)
3494 (current-buffer)))))
3495 ;; Output goes in a separate buffer.
3496 ;; Preserve the match data in case called from a program.
3497 ;; FIXME: It'd be ridiculous for an Elisp function to call
3498 ;; shell-command and assume that it won't mess the match-data!
3500 (if (string-match "[ \t]*&[ \t]*\\'" command
)
3501 ;; Command ending with ampersand means asynchronous.
3502 (let* ((buffer (get-buffer-create
3503 (or output-buffer
"*Async Shell Command*")))
3504 (bname (buffer-name buffer
))
3505 (directory default-directory
)
3507 ;; Remove the ampersand.
3508 (setq command
(substring command
0 (match-beginning 0)))
3509 ;; Ask the user what to do with already running process.
3510 (setq proc
(get-buffer-process buffer
))
3513 ((eq async-shell-command-buffer
'confirm-kill-process
)
3514 ;; If will kill a process, query first.
3515 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3517 (error "Shell command in progress")))
3518 ((eq async-shell-command-buffer
'confirm-new-buffer
)
3519 ;; If will create a new buffer, query first.
3520 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3521 (setq buffer
(generate-new-buffer bname
))
3522 (error "Shell command in progress")))
3523 ((eq async-shell-command-buffer
'new-buffer
)
3524 ;; It will create a new buffer.
3525 (setq buffer
(generate-new-buffer bname
)))
3526 ((eq async-shell-command-buffer
'confirm-rename-buffer
)
3527 ;; If will rename the buffer, query first.
3528 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3530 (with-current-buffer buffer
3532 (setq buffer
(get-buffer-create bname
)))
3533 (error "Shell command in progress")))
3534 ((eq async-shell-command-buffer
'rename-buffer
)
3535 ;; It will rename the buffer.
3536 (with-current-buffer buffer
3538 (setq buffer
(get-buffer-create bname
)))))
3539 (with-current-buffer buffer
3540 (shell-command--save-pos-or-erase)
3541 (setq default-directory directory
)
3542 (setq proc
(start-process "Shell" buffer shell-file-name
3543 shell-command-switch command
))
3544 (setq mode-line-process
'(":%s"))
3545 (require 'shell
) (shell-mode)
3546 (set-process-sentinel proc
'shell-command-sentinel
)
3547 ;; Use the comint filter for proper handling of
3548 ;; carriage motion (see comint-inhibit-carriage-motion).
3549 (set-process-filter proc
'comint-output-filter
)
3550 (if async-shell-command-display-buffer
3551 ;; Display buffer immediately.
3552 (display-buffer buffer
'(nil (allow-no-window . t
)))
3553 ;; Defer displaying buffer until first process output.
3554 ;; Use disposable named advice so that the buffer is
3555 ;; displayed at most once per process lifetime.
3556 (let ((nonce (make-symbol "nonce")))
3557 (add-function :before
(process-filter proc
)
3558 (lambda (proc _string
)
3559 (let ((buf (process-buffer proc
)))
3560 (when (buffer-live-p buf
)
3561 (remove-function (process-filter proc
)
3563 (display-buffer buf
))))
3564 `((name .
,nonce
)))))))
3565 ;; Otherwise, command is executed synchronously.
3566 (shell-command-on-region (point) (point) command
3567 output-buffer nil error-buffer
)))))))
3569 (defun display-message-or-buffer (message &optional buffer-name action frame
)
3570 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3571 MESSAGE may be either a string or a buffer.
3573 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3574 for maximum height of the echo area, as defined by `max-mini-window-height'
3575 if `resize-mini-windows' is non-nil.
3577 Returns either the string shown in the echo area, or when a pop-up
3578 buffer is used, the window used to display it.
3580 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3581 name of the buffer used to display it in the case where a pop-up buffer
3582 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3583 string and it is displayed in the echo area, it is not specified whether
3584 the contents are inserted into the buffer anyway.
3586 Optional arguments ACTION and FRAME are as for `display-buffer',
3587 and are only used if a pop-up buffer is displayed."
3588 (cond ((and (stringp message
) (not (string-match "\n" message
)))
3589 ;; Trivial case where we can use the echo area
3590 (message "%s" message
))
3591 ((and (stringp message
)
3592 (= (string-match "\n" message
) (1- (length message
))))
3593 ;; Trivial case where we can just remove single trailing newline
3594 (message "%s" (substring message
0 (1- (length message
)))))
3597 (with-current-buffer
3598 (if (bufferp message
)
3600 (get-buffer-create (or buffer-name
"*Message*")))
3602 (unless (bufferp message
)
3607 (if (= (buffer-size) 0)
3609 (count-screen-lines nil nil nil
(minibuffer-window)))))
3611 ((and (or (<= lines
1)
3613 (if resize-mini-windows
3614 (cond ((floatp max-mini-window-height
)
3616 max-mini-window-height
))
3617 ((integerp max-mini-window-height
)
3618 max-mini-window-height
)
3622 ;; Don't use the echo area if the output buffer is
3623 ;; already displayed in the selected frame.
3624 (not (get-buffer-window (current-buffer))))
3626 (goto-char (point-max))
3629 (message "%s" (buffer-substring (point-min) (point))))
3632 (goto-char (point-min))
3633 (display-buffer (current-buffer) action frame
))))))))
3636 ;; We have a sentinel to prevent insertion of a termination message
3637 ;; in the buffer itself, and to set the point in the buffer when
3638 ;; `shell-command-dont-erase-buffer' is non-nil.
3639 (defun shell-command-sentinel (process signal
)
3640 (when (memq (process-status process
) '(exit signal
))
3641 (shell-command--set-point-after-cmd (process-buffer process
))
3643 (car (cdr (cdr (process-command process
))))
3644 (substring signal
0 -
1))))
3646 (defun shell-command-on-region (start end command
3647 &optional output-buffer replace
3648 error-buffer display-error-buffer
3649 region-noncontiguous-p
)
3650 "Execute string COMMAND in inferior shell with region as input.
3651 Normally display output (if any) in temp buffer `*Shell Command Output*';
3652 Prefix arg means replace the region with it. Return the exit code of
3655 To specify a coding system for converting non-ASCII characters
3656 in the input and output to the shell command, use \\[universal-coding-system-argument]
3657 before this command. By default, the input (from the current buffer)
3658 is encoded using coding-system specified by `process-coding-system-alist',
3659 falling back to `default-process-coding-system' if no match for COMMAND
3660 is found in `process-coding-system-alist'.
3662 Noninteractive callers can specify coding systems by binding
3663 `coding-system-for-read' and `coding-system-for-write'.
3665 If the command generates output, the output may be displayed
3666 in the echo area or in a buffer.
3667 If the output is short enough to display in the echo area
3668 \(determined by the variable `max-mini-window-height' if
3669 `resize-mini-windows' is non-nil), it is shown there.
3670 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3671 The output is available in that buffer in both cases.
3673 If there is output and an error, a message about the error
3674 appears at the end of the output.
3676 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3677 command's output. If the value is a buffer or buffer name,
3678 erase that buffer and insert the output there; a non-nil value of
3679 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3680 If the value is nil, use the buffer `*Shell Command Output*'.
3681 Any other non-nil value means to insert the output in the
3682 current buffer after START.
3684 Optional fifth arg REPLACE, if non-nil, means to insert the
3685 output in place of text from START to END, putting point and mark
3688 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3689 or buffer name to which to direct the command's standard error
3690 output. If nil, error output is mingled with regular output.
3691 When called interactively, `shell-command-default-error-buffer'
3692 is used for ERROR-BUFFER.
3694 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3695 display the error buffer if there were any errors. When called
3696 interactively, this is t."
3697 (interactive (let (string)
3699 (user-error "The mark is not set now, so there is no region"))
3700 ;; Do this before calling region-beginning
3701 ;; and region-end, in case subprocess output
3702 ;; relocates them while we are in the minibuffer.
3703 (setq string
(read-shell-command "Shell command on region: "))
3704 ;; call-interactively recognizes region-beginning and
3705 ;; region-end specially, leaving them in the history.
3706 (list (region-beginning) (region-end)
3710 shell-command-default-error-buffer
3712 (region-noncontiguous-p))))
3716 (expand-file-name "scor"
3717 (or small-temporary-file-directory
3718 temporary-file-directory
)))
3721 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3722 (if region-noncontiguous-p
3723 (let ((input (concat (funcall region-extract-function
'delete
) "\n"))
3727 (call-process-region (point-min) (point-max)
3729 nil shell-command-switch
3731 (setq output
(split-string (buffer-string) "\n")))
3733 (funcall region-insert-function output
))
3736 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
3737 ;; Replace specified region with output from command.
3738 (let ((swap (and replace
(< start end
))))
3739 ;; Don't muck with mark unless REPLACE says we should.
3741 (and replace
(push-mark (point) 'nomsg
))
3743 (call-shell-region start end command replace
3747 ;; It is rude to delete a buffer which the command is not using.
3748 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3749 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3750 ;; (kill-buffer shell-buffer)))
3751 ;; Don't muck with mark unless REPLACE says we should.
3752 (and replace swap
(exchange-point-and-mark)))
3753 ;; No prefix argument: put the output in a temp buffer,
3754 ;; replacing its entire contents.
3755 (let ((buffer (get-buffer-create
3756 (or output-buffer
"*Shell Command Output*"))))
3758 (if (and (eq buffer
(current-buffer))
3759 (or (not shell-command-dont-erase-buffer
)
3760 (and (not (eq buffer
(get-buffer "*Shell Command Output*")))
3761 (not (region-active-p)))))
3762 ;; If the input is the same buffer as the output,
3763 ;; delete everything but the specified region,
3764 ;; then replace that region with the output.
3765 (progn (setq buffer-read-only nil
)
3766 (delete-region (max start end
) (point-max))
3767 (delete-region (point-min) (min start end
))
3769 (call-process-region (point-min) (point-max)
3774 nil shell-command-switch
3776 ;; Clear the output buffer, then run the command with
3778 (let ((directory default-directory
))
3779 (with-current-buffer buffer
3780 (if (not output-buffer
)
3781 (setq default-directory directory
))
3782 (shell-command--save-pos-or-erase)))
3784 (call-shell-region start end command nil
3786 (list buffer error-file
)
3788 ;; Report the output.
3789 (with-current-buffer buffer
3790 (setq mode-line-process
3791 (cond ((null exit-status
)
3793 ((stringp exit-status
)
3794 (format " - Signal [%s]" exit-status
))
3795 ((not (equal 0 exit-status
))
3796 (format " - Exit [%d]" exit-status
)))))
3797 (if (with-current-buffer buffer
(> (point-max) (point-min)))
3798 ;; There's some output, display it
3800 (display-message-or-buffer buffer
)
3801 (shell-command--set-point-after-cmd buffer
))
3802 ;; No output; error?
3805 (< 0 (nth 7 (file-attributes error-file
))))
3806 (format "some error output%s"
3807 (if shell-command-default-error-buffer
3808 (format " to the \"%s\" buffer"
3809 shell-command-default-error-buffer
)
3812 (cond ((null exit-status
)
3813 (message "(Shell command failed with error)"))
3814 ((equal 0 exit-status
)
3815 (message "(Shell command succeeded with %s)"
3817 ((stringp exit-status
)
3818 (message "(Shell command killed by signal %s)"
3821 (message "(Shell command failed with code %d and %s)"
3822 exit-status output
))))
3823 ;; Don't kill: there might be useful info in the undo-log.
3824 ;; (kill-buffer buffer)
3827 (when (and error-file
(file-exists-p error-file
))
3828 (if (< 0 (nth 7 (file-attributes error-file
)))
3829 (with-current-buffer (get-buffer-create error-buffer
)
3830 (let ((pos-from-end (- (point-max) (point))))
3833 ;; Do no formatting while reading error file,
3834 ;; because that can run a shell command, and we
3835 ;; don't want that to cause an infinite recursion.
3836 (format-insert-file error-file nil
)
3837 ;; Put point after the inserted errors.
3838 (goto-char (- (point-max) pos-from-end
)))
3839 (and display-error-buffer
3840 (display-buffer (current-buffer)))))
3841 (delete-file error-file
))
3844 (defun shell-command-to-string (command)
3845 "Execute shell command COMMAND and return its output as a string."
3846 (with-output-to-string
3847 (with-current-buffer
3849 (process-file shell-file-name nil t nil shell-command-switch command
))))
3851 (defun process-file (program &optional infile buffer display
&rest args
)
3852 "Process files synchronously in a separate process.
3853 Similar to `call-process', but may invoke a file handler based on
3854 `default-directory'. The current working directory of the
3855 subprocess is `default-directory'.
3857 File names in INFILE and BUFFER are handled normally, but file
3858 names in ARGS should be relative to `default-directory', as they
3859 are passed to the process verbatim. (This is a difference to
3860 `call-process' which does not support file handlers for INFILE
3863 Some file handlers might not support all variants, for example
3864 they might behave as if DISPLAY was nil, regardless of the actual
3866 (let ((fh (find-file-name-handler default-directory
'process-file
))
3869 (if fh
(apply fh
'process-file program infile buffer display args
)
3870 (when infile
(setq lc
(file-local-copy infile
)))
3871 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
3872 (make-temp-file "emacs")))
3874 (apply 'call-process program
3876 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
3878 (when stderr-file
(copy-file stderr-file
(cadr buffer
) t
))))
3879 (when stderr-file
(delete-file stderr-file
))
3880 (when lc
(delete-file lc
)))))
3882 (defvar process-file-side-effects t
3883 "Whether a call of `process-file' changes remote files.
3885 By default, this variable is always set to t, meaning that a
3886 call of `process-file' could potentially change any file on a
3887 remote host. When set to nil, a file handler could optimize
3888 its behavior with respect to remote file attribute caching.
3890 You should only ever change this variable with a let-binding;
3891 never with `setq'.")
3893 (defun start-file-process (name buffer program
&rest program-args
)
3894 "Start a program in a subprocess. Return the process object for it.
3896 Similar to `start-process', but may invoke a file handler based on
3897 `default-directory'. See Info node `(elisp)Magic File Names'.
3899 This handler ought to run PROGRAM, perhaps on the local host,
3900 perhaps on a remote host that corresponds to `default-directory'.
3901 In the latter case, the local part of `default-directory' becomes
3902 the working directory of the process.
3904 PROGRAM and PROGRAM-ARGS might be file names. They are not
3905 objects of file handler invocation. File handlers might not
3906 support pty association, if PROGRAM is nil."
3907 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
3908 (if fh
(apply fh
'start-file-process name buffer program program-args
)
3909 (apply 'start-process name buffer program program-args
))))
3913 (defvar tabulated-list-format
)
3914 (defvar tabulated-list-entries
)
3915 (defvar tabulated-list-sort-key
)
3916 (declare-function tabulated-list-init-header
"tabulated-list" ())
3917 (declare-function tabulated-list-print
"tabulated-list"
3918 (&optional remember-pos update
))
3920 (defvar process-menu-query-only nil
)
3922 (defvar process-menu-mode-map
3923 (let ((map (make-sparse-keymap)))
3924 (define-key map
[?d
] 'process-menu-delete-process
)
3927 (define-derived-mode process-menu-mode tabulated-list-mode
"Process Menu"
3928 "Major mode for listing the processes called by Emacs."
3929 (setq tabulated-list-format
[("Process" 15 t
)
3935 (make-local-variable 'process-menu-query-only
)
3936 (setq tabulated-list-sort-key
(cons "Process" nil
))
3937 (add-hook 'tabulated-list-revert-hook
'list-processes--refresh nil t
))
3939 (defun process-menu-delete-process ()
3940 "Kill process at point in a `list-processes' buffer."
3942 (let ((pos (point)))
3943 (delete-process (tabulated-list-get-id))
3945 (goto-char (min pos
(point-max)))
3948 (beginning-of-line))))
3950 (defun list-processes--refresh ()
3951 "Recompute the list of processes for the Process List buffer.
3952 Also, delete any process that is exited or signaled."
3953 (setq tabulated-list-entries nil
)
3954 (dolist (p (process-list))
3955 (cond ((memq (process-status p
) '(exit signal closed
))
3957 ((or (not process-menu-query-only
)
3958 (process-query-on-exit-flag p
))
3959 (let* ((buf (process-buffer p
))
3960 (type (process-type p
))
3961 (pid (if (process-id p
) (format "%d" (process-id p
)) "--"))
3962 (name (process-name p
))
3963 (status (symbol-name (process-status p
)))
3964 (buf-label (if (buffer-live-p buf
)
3965 `(,(buffer-name buf
)
3967 help-echo
,(format-message
3972 action process-menu-visit-buffer
)
3974 (tty (or (process-tty-name p
) "--"))
3976 (if (memq type
'(network serial
))
3977 (let ((contact (process-contact p t
)))
3978 (if (eq type
'network
)
3980 (if (plist-get contact
:type
)
3983 (if (plist-get contact
:server
)
3984 (format "server on %s"
3986 (plist-get contact
:host
)
3987 (plist-get contact
:local
)))
3988 (format "connection to %s"
3989 (plist-get contact
:host
))))
3990 (format "(serial port %s%s)"
3991 (or (plist-get contact
:port
) "?")
3992 (let ((speed (plist-get contact
:speed
)))
3994 (format " at %s b/s" speed
)
3996 (mapconcat 'identity
(process-command p
) " "))))
3997 (push (list p
(vector name pid status buf-label tty cmd
))
3998 tabulated-list-entries
)))))
3999 (tabulated-list-init-header))
4001 (defun process-menu-visit-buffer (button)
4002 (display-buffer (button-get button
'process-buffer
)))
4004 (defun list-processes (&optional query-only buffer
)
4005 "Display a list of all processes that are Emacs sub-processes.
4006 If optional argument QUERY-ONLY is non-nil, only processes with
4007 the query-on-exit flag set are listed.
4008 Any process listed as exited or signaled is actually eliminated
4009 after the listing is made.
4010 Optional argument BUFFER specifies a buffer to use, instead of
4012 The return value is always nil.
4014 This function lists only processes that were launched by Emacs. To
4015 see other processes running on the system, use `list-system-processes'."
4017 (or (fboundp 'process-list
)
4018 (error "Asynchronous subprocesses are not supported on this system"))
4019 (unless (bufferp buffer
)
4020 (setq buffer
(get-buffer-create "*Process List*")))
4021 (with-current-buffer buffer
4023 (setq process-menu-query-only query-only
)
4024 (list-processes--refresh)
4025 (tabulated-list-print))
4026 (display-buffer buffer
)
4029 ;;;; Prefix commands
4031 (setq prefix-command--needs-update nil
)
4032 (setq prefix-command--last-echo nil
)
4034 (defun internal-echo-keystrokes-prefix ()
4035 ;; BEWARE: Called directly from C code.
4036 ;; If the return value is non-nil, it means we are in the middle of
4037 ;; a command with prefix, such as a command invoked with prefix-arg.
4038 (if (not prefix-command--needs-update
)
4039 prefix-command--last-echo
4040 (setq prefix-command--last-echo
4042 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4043 (lambda (fun) (push (funcall fun
) strs
)))
4044 (setq strs
(delq nil strs
))
4045 (when strs
(mapconcat #'identity strs
" "))))))
4047 (defvar prefix-command-echo-keystrokes-functions nil
4048 "Abnormal hook which constructs the description of the current prefix state.
4049 Each function is called with no argument, should return a string or nil.")
4051 (defun prefix-command-update ()
4052 "Update state of prefix commands.
4053 Call it whenever you change the \"prefix command state\"."
4054 (setq prefix-command--needs-update t
))
4056 (defvar prefix-command-preserve-state-hook nil
4057 "Normal hook run when a command needs to preserve the prefix.")
4059 (defun prefix-command-preserve-state ()
4060 "Pass the current prefix command state to the next command.
4061 Should be called by all prefix commands.
4062 Runs `prefix-command-preserve-state-hook'."
4063 (run-hooks 'prefix-command-preserve-state-hook
)
4064 ;; If the current command is a prefix command, we don't want the next (real)
4065 ;; command to have `last-command' set to, say, `universal-argument'.
4066 (setq this-command last-command
)
4067 (setq real-this-command real-last-command
)
4068 (prefix-command-update))
4070 (defun reset-this-command-lengths ()
4071 (declare (obsolete prefix-command-preserve-state
"25.1"))
4074 ;;;;; The main prefix command.
4076 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4078 (add-hook 'prefix-command-echo-keystrokes-functions
4079 #'universal-argument--description
)
4080 (defun universal-argument--description ()
4085 (`(,(and (pred integerp
) n
))
4087 (while (and (> n
4) (= (mod n
4) 0))
4088 (setq str
(concat str
" C-u"))
4090 (if (= n
4) str
(format " %s" prefix-arg
))))
4091 (_ (format " %s" prefix-arg
))))))
4093 (add-hook 'prefix-command-preserve-state-hook
4094 #'universal-argument--preserve
)
4095 (defun universal-argument--preserve ()
4096 (setq prefix-arg current-prefix-arg
))
4098 (defvar universal-argument-map
4099 (let ((map (make-sparse-keymap))
4100 (universal-argument-minus
4101 ;; For backward compatibility, minus with no modifiers is an ordinary
4102 ;; command if digits have already been entered.
4103 `(menu-item "" negative-argument
4104 :filter
,(lambda (cmd)
4105 (if (integerp prefix-arg
) nil cmd
)))))
4106 (define-key map
[switch-frame
]
4107 (lambda (e) (interactive "e")
4108 (handle-switch-frame e
) (universal-argument--mode)))
4109 (define-key map
[?\C-u
] 'universal-argument-more
)
4110 (define-key map
[?-
] universal-argument-minus
)
4111 (define-key map
[?
0] 'digit-argument
)
4112 (define-key map
[?
1] 'digit-argument
)
4113 (define-key map
[?
2] 'digit-argument
)
4114 (define-key map
[?
3] 'digit-argument
)
4115 (define-key map
[?
4] 'digit-argument
)
4116 (define-key map
[?
5] 'digit-argument
)
4117 (define-key map
[?
6] 'digit-argument
)
4118 (define-key map
[?
7] 'digit-argument
)
4119 (define-key map
[?
8] 'digit-argument
)
4120 (define-key map
[?
9] 'digit-argument
)
4121 (define-key map
[kp-0
] 'digit-argument
)
4122 (define-key map
[kp-1
] 'digit-argument
)
4123 (define-key map
[kp-2
] 'digit-argument
)
4124 (define-key map
[kp-3
] 'digit-argument
)
4125 (define-key map
[kp-4
] 'digit-argument
)
4126 (define-key map
[kp-5
] 'digit-argument
)
4127 (define-key map
[kp-6
] 'digit-argument
)
4128 (define-key map
[kp-7
] 'digit-argument
)
4129 (define-key map
[kp-8
] 'digit-argument
)
4130 (define-key map
[kp-9
] 'digit-argument
)
4131 (define-key map
[kp-subtract
] universal-argument-minus
)
4133 "Keymap used while processing \\[universal-argument].")
4135 (defun universal-argument--mode ()
4136 (prefix-command-update)
4137 (set-transient-map universal-argument-map nil
))
4139 (defun universal-argument ()
4140 "Begin a numeric argument for the following command.
4141 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4142 \\[universal-argument] following the digits or minus sign ends the argument.
4143 \\[universal-argument] without digits or minus sign provides 4 as argument.
4144 Repeating \\[universal-argument] without digits or minus sign
4145 multiplies the argument by 4 each time.
4146 For some commands, just \\[universal-argument] by itself serves as a flag
4147 which is different in effect from any particular numeric argument.
4148 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4150 (prefix-command-preserve-state)
4151 (setq prefix-arg
(list 4))
4152 (universal-argument--mode))
4154 (defun universal-argument-more (arg)
4155 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4156 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4158 (prefix-command-preserve-state)
4159 (setq prefix-arg
(if (consp arg
)
4160 (list (* 4 (car arg
)))
4164 (when (consp prefix-arg
) (universal-argument--mode)))
4166 (defun negative-argument (arg)
4167 "Begin a negative numeric argument for the next command.
4168 \\[universal-argument] following digits or minus sign ends the argument."
4170 (prefix-command-preserve-state)
4171 (setq prefix-arg
(cond ((integerp arg
) (- arg
))
4174 (universal-argument--mode))
4176 (defun digit-argument (arg)
4177 "Part of the numeric argument for the next command.
4178 \\[universal-argument] following digits or minus sign ends the argument."
4180 (prefix-command-preserve-state)
4181 (let* ((char (if (integerp last-command-event
)
4183 (get last-command-event
'ascii-character
)))
4184 (digit (- (logand char ?
\177) ?
0)))
4185 (setq prefix-arg
(cond ((integerp arg
)
4187 (if (< arg
0) (- digit
) digit
)))
4189 ;; Treat -0 as just -, so that -01 will work.
4190 (if (zerop digit
) '-
(- digit
)))
4193 (universal-argument--mode))
4196 (defvar filter-buffer-substring-functions nil
4197 "This variable is a wrapper hook around `buffer-substring--filter'.
4198 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4199 (make-obsolete-variable 'filter-buffer-substring-functions
4200 'filter-buffer-substring-function
"24.4")
4202 (defvar filter-buffer-substring-function
#'buffer-substring--filter
4203 "Function to perform the filtering in `filter-buffer-substring'.
4204 The function is called with the same 3 arguments (BEG END DELETE)
4205 that `filter-buffer-substring' received. It should return the
4206 buffer substring between BEG and END, after filtering. If DELETE is
4207 non-nil, it should delete the text between BEG and END from the buffer.")
4209 (defvar buffer-substring-filters nil
4210 "List of filter functions for `buffer-substring--filter'.
4211 Each function must accept a single argument, a string, and return a string.
4212 The buffer substring is passed to the first function in the list,
4213 and the return value of each function is passed to the next.
4214 As a special convention, point is set to the start of the buffer text
4215 being operated on (i.e., the first argument of `buffer-substring--filter')
4216 before these functions are called.")
4217 (make-obsolete-variable 'buffer-substring-filters
4218 'filter-buffer-substring-function
"24.1")
4220 (defun filter-buffer-substring (beg end
&optional delete
)
4221 "Return the buffer substring between BEG and END, after filtering.
4222 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4224 This calls the function that `filter-buffer-substring-function' specifies
4225 \(passing the same three arguments that it received) to do the work,
4226 and returns whatever it does. The default function does no filtering,
4227 unless a hook has been set.
4229 Use `filter-buffer-substring' instead of `buffer-substring',
4230 `buffer-substring-no-properties', or `delete-and-extract-region' when
4231 you want to allow filtering to take place. For example, major or minor
4232 modes can use `filter-buffer-substring-function' to extract characters
4233 that are special to a buffer, and should not be copied into other buffers."
4234 (funcall filter-buffer-substring-function beg end delete
))
4236 (defun buffer-substring--filter (beg end
&optional delete
)
4237 "Default function to use for `filter-buffer-substring-function'.
4238 Its arguments and return value are as specified for `filter-buffer-substring'.
4239 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4240 \(see `with-wrapper-hook' for details about wrapper hooks),
4241 and the abnormal hook `buffer-substring-filters'.
4242 No filtering is done unless a hook says to."
4243 (subr--with-wrapper-hook-no-warnings
4244 filter-buffer-substring-functions
(beg end delete
)
4246 ((or delete buffer-substring-filters
)
4249 (let ((string (if delete
(delete-and-extract-region beg end
)
4250 (buffer-substring beg end
))))
4251 (dolist (filter buffer-substring-filters
)
4252 (setq string
(funcall filter string
)))
4255 (buffer-substring beg end
)))))
4258 ;;;; Window system cut and paste hooks.
4260 (defvar interprogram-cut-function
#'gui-select-text
4261 "Function to call to make a killed region available to other programs.
4262 Most window systems provide a facility for cutting and pasting
4263 text between different programs, such as the clipboard on X and
4264 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4266 This variable holds a function that Emacs calls whenever text is
4267 put in the kill ring, to make the new kill available to other
4268 programs. The function takes one argument, TEXT, which is a
4269 string containing the text which should be made available.")
4271 (defvar interprogram-paste-function
#'gui-selection-value
4272 "Function to call to get text cut from other programs.
4273 Most window systems provide a facility for cutting and pasting
4274 text between different programs, such as the clipboard on X and
4275 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4277 This variable holds a function that Emacs calls to obtain text
4278 that other programs have provided for pasting. The function is
4279 called with no arguments. If no other program has provided text
4280 to paste, the function should return nil (in which case the
4281 caller, usually `current-kill', should use the top of the Emacs
4282 kill ring). If another program has provided text to paste, the
4283 function should return that text as a string (in which case the
4284 caller should put this string in the kill ring as the latest
4287 The function may also return a list of strings if the window
4288 system supports multiple selections. The first string will be
4289 used as the pasted text, but the other will be placed in the kill
4290 ring for easy access via `yank-pop'.
4292 Note that the function should return a string only if a program
4293 other than Emacs has provided a string for pasting; if Emacs
4294 provided the most recent string, the function should return nil.
4295 If it is difficult to tell whether Emacs or some other program
4296 provided the current string, it is probably good enough to return
4297 nil if the string is equal (according to `string=') to the last
4298 text Emacs provided.")
4302 ;;;; The kill ring data structure.
4304 (defvar kill-ring nil
4305 "List of killed text sequences.
4306 Since the kill ring is supposed to interact nicely with cut-and-paste
4307 facilities offered by window systems, use of this variable should
4308 interact nicely with `interprogram-cut-function' and
4309 `interprogram-paste-function'. The functions `kill-new',
4310 `kill-append', and `current-kill' are supposed to implement this
4311 interaction; you may want to use them instead of manipulating the kill
4314 (defcustom kill-ring-max
60
4315 "Maximum length of kill ring before oldest elements are thrown away."
4319 (defvar kill-ring-yank-pointer nil
4320 "The tail of the kill ring whose car is the last thing yanked.")
4322 (defcustom save-interprogram-paste-before-kill nil
4323 "Save existing clipboard text into kill ring before replacing it.
4324 A non-nil value ensures that Emacs kill operations do not
4325 irrevocably overwrite existing clipboard text by saving it to the
4326 `kill-ring' prior to the kill. Such text can subsequently be
4327 retrieved via \\[yank] \\[yank-pop]]."
4332 (defcustom kill-do-not-save-duplicates nil
4333 "Do not add a new string to `kill-ring' if it duplicates the last one.
4334 The comparison is done using `equal-including-properties'."
4339 (defun kill-new (string &optional replace
)
4340 "Make STRING the latest kill in the kill ring.
4341 Set `kill-ring-yank-pointer' to point to it.
4342 If `interprogram-cut-function' is non-nil, apply it to STRING.
4343 Optional second argument REPLACE non-nil means that STRING will replace
4344 the front of the kill ring, rather than being added to the list.
4346 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4347 are non-nil, save the interprogram paste string(s) into `kill-ring' before
4350 When the yank handler has a non-nil PARAM element, the original STRING
4351 argument is not used by `insert-for-yank'. However, since Lisp code
4352 may access and use elements from the kill ring directly, the STRING
4353 argument should still be a \"useful\" string for such uses."
4354 (unless (and kill-do-not-save-duplicates
4355 ;; Due to text properties such as 'yank-handler that
4356 ;; can alter the contents to yank, comparison using
4357 ;; `equal' is unsafe.
4358 (equal-including-properties string
(car kill-ring
)))
4359 (if (fboundp 'menu-bar-update-yank-menu
)
4360 (menu-bar-update-yank-menu string
(and replace
(car kill-ring
)))))
4361 (when save-interprogram-paste-before-kill
4362 (let ((interprogram-paste (and interprogram-paste-function
4363 (funcall interprogram-paste-function
))))
4364 (when interprogram-paste
4365 (dolist (s (if (listp interprogram-paste
)
4366 (nreverse interprogram-paste
)
4367 (list interprogram-paste
)))
4368 (unless (and kill-do-not-save-duplicates
4369 (equal-including-properties s
(car kill-ring
)))
4370 (push s kill-ring
))))))
4371 (unless (and kill-do-not-save-duplicates
4372 (equal-including-properties string
(car kill-ring
)))
4373 (if (and replace kill-ring
)
4374 (setcar kill-ring string
)
4375 (push string kill-ring
)
4376 (if (> (length kill-ring
) kill-ring-max
)
4377 (setcdr (nthcdr (1- kill-ring-max
) kill-ring
) nil
))))
4378 (setq kill-ring-yank-pointer kill-ring
)
4379 (if interprogram-cut-function
4380 (funcall interprogram-cut-function string
)))
4382 ;; It has been argued that this should work like `self-insert-command'
4383 ;; which merges insertions in `buffer-undo-list' in groups of 20
4384 ;; (hard-coded in `undo-auto-amalgamate').
4385 (defcustom kill-append-merge-undo nil
4386 "Amalgamate appending kills with the last kill for undo.
4387 When non-nil, appending or prepending text to the last kill makes
4388 \\[undo] restore both pieces of text simultaneously."
4393 (defun kill-append (string before-p
)
4394 "Append STRING to the end of the latest kill in the kill ring.
4395 If BEFORE-P is non-nil, prepend STRING to the kill instead.
4396 If `interprogram-cut-function' is non-nil, call it with the
4398 If `kill-append-merge-undo' is non-nil, remove the last undo
4399 boundary in the current buffer."
4400 (let* ((cur (car kill-ring
)))
4401 (kill-new (if before-p
(concat string cur
) (concat cur string
))
4402 (or (= (length cur
) 0)
4403 (equal nil
(get-text-property 0 'yank-handler cur
))))
4404 (when (and kill-append-merge-undo
(not buffer-read-only
))
4405 (let ((prev buffer-undo-list
)
4406 (next (cdr buffer-undo-list
)))
4407 ;; find the next undo boundary
4411 ;; remove this undo boundary
4413 (setcdr prev
(cdr next
)))))))
4415 (defcustom yank-pop-change-selection nil
4416 "Whether rotating the kill ring changes the window system selection.
4417 If non-nil, whenever the kill ring is rotated (usually via the
4418 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4419 to copy the new kill to the window system selection."
4424 (defun current-kill (n &optional do-not-move
)
4425 "Rotate the yanking point by N places, and then return that kill.
4426 If N is zero and `interprogram-paste-function' is set to a
4427 function that returns a string or a list of strings, and if that
4428 function doesn't return nil, then that string (or list) is added
4429 to the front of the kill ring and the string (or first string in
4430 the list) is returned as the latest kill.
4432 If N is not zero, and if `yank-pop-change-selection' is
4433 non-nil, use `interprogram-cut-function' to transfer the
4434 kill at the new yank point into the window system selection.
4436 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4437 move the yanking point; just return the Nth kill forward."
4439 (let ((interprogram-paste (and (= n
0)
4440 interprogram-paste-function
4441 (funcall interprogram-paste-function
))))
4442 (if interprogram-paste
4444 ;; Disable the interprogram cut function when we add the new
4445 ;; text to the kill ring, so Emacs doesn't try to own the
4446 ;; selection, with identical text.
4447 (let ((interprogram-cut-function nil
))
4448 (if (listp interprogram-paste
)
4449 (mapc 'kill-new
(nreverse interprogram-paste
))
4450 (kill-new interprogram-paste
)))
4452 (or kill-ring
(error "Kill ring is empty"))
4453 (let ((ARGth-kill-element
4454 (nthcdr (mod (- n
(length kill-ring-yank-pointer
))
4458 (setq kill-ring-yank-pointer ARGth-kill-element
)
4459 (when (and yank-pop-change-selection
4461 interprogram-cut-function
)
4462 (funcall interprogram-cut-function
(car ARGth-kill-element
))))
4463 (car ARGth-kill-element
)))))
4467 ;;;; Commands for manipulating the kill ring.
4469 (defcustom kill-read-only-ok nil
4470 "Non-nil means don't signal an error for killing read-only text."
4474 (defun kill-region (beg end
&optional region
)
4475 "Kill (\"cut\") text between point and mark.
4476 This deletes the text from the buffer and saves it in the kill ring.
4477 The command \\[yank] can retrieve it from there.
4478 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4480 If you want to append the killed region to the last killed text,
4481 use \\[append-next-kill] before \\[kill-region].
4483 Any command that calls this function is a \"kill command\".
4484 If the previous command was also a kill command,
4485 the text killed this time appends to the text killed last time
4486 to make one entry in the kill ring.
4488 The killed text is filtered by `filter-buffer-substring' before it is
4489 saved in the kill ring, so the actual saved text might be different
4490 from what was killed.
4492 If the buffer is read-only, Emacs will beep and refrain from deleting
4493 the text, but put the text in the kill ring anyway. This means that
4494 you can use the killing commands to copy text from a read-only buffer.
4496 Lisp programs should use this function for killing text.
4497 (To delete text, use `delete-region'.)
4498 Supply two arguments, character positions BEG and END indicating the
4499 stretch of text to be killed. If the optional argument REGION is
4500 non-nil, the function ignores BEG and END, and kills the current
4502 ;; Pass mark first, then point, because the order matters when
4503 ;; calling `kill-append'.
4504 (interactive (list (mark) (point) 'region
))
4505 (unless (and beg end
)
4506 (user-error "The mark is not set now, so there is no region"))
4508 (let ((string (if region
4509 (funcall region-extract-function
'delete
)
4510 (filter-buffer-substring beg end
'delete
))))
4511 (when string
;STRING is nil if BEG = END
4512 ;; Add that string to the kill ring, one way or another.
4513 (if (eq last-command
'kill-region
)
4514 (kill-append string
(< end beg
))
4516 (when (or string
(eq last-command
'kill-region
))
4517 (setq this-command
'kill-region
))
4518 (setq deactivate-mark t
)
4520 ((buffer-read-only text-read-only
)
4521 ;; The code above failed because the buffer, or some of the characters
4522 ;; in the region, are read-only.
4523 ;; We should beep, in case the user just isn't aware of this.
4524 ;; However, there's no harm in putting
4525 ;; the region's text in the kill ring, anyway.
4526 (copy-region-as-kill beg end region
)
4527 ;; Set this-command now, so it will be set even if we get an error.
4528 (setq this-command
'kill-region
)
4529 ;; This should barf, if appropriate, and give us the correct error.
4530 (if kill-read-only-ok
4531 (progn (message "Read only text copied to kill ring") nil
)
4532 ;; Signal an error if the buffer is read-only.
4533 (barf-if-buffer-read-only)
4534 ;; If the buffer isn't read-only, the text is.
4535 (signal 'text-read-only
(list (current-buffer)))))))
4537 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4538 ;; to get two copies of the text when the user accidentally types M-w and
4539 ;; then corrects it with the intended C-w.
4540 (defun copy-region-as-kill (beg end
&optional region
)
4541 "Save the region as if killed, but don't kill it.
4542 In Transient Mark mode, deactivate the mark.
4543 If `interprogram-cut-function' is non-nil, also save the text for a window
4544 system cut and paste.
4546 The copied text is filtered by `filter-buffer-substring' before it is
4547 saved in the kill ring, so the actual saved text might be different
4548 from what was in the buffer.
4550 When called from Lisp, save in the kill ring the stretch of text
4551 between BEG and END, unless the optional argument REGION is
4552 non-nil, in which case ignore BEG and END, and save the current
4555 This command's old key binding has been given to `kill-ring-save'."
4556 ;; Pass mark first, then point, because the order matters when
4557 ;; calling `kill-append'.
4558 (interactive (list (mark) (point)
4559 (prefix-numeric-value current-prefix-arg
)))
4560 (let ((str (if region
4561 (funcall region-extract-function nil
)
4562 (filter-buffer-substring beg end
))))
4563 (if (eq last-command
'kill-region
)
4564 (kill-append str
(< end beg
))
4566 (setq deactivate-mark t
)
4569 (defun kill-ring-save (beg end
&optional region
)
4570 "Save the region as if killed, but don't kill it.
4571 In Transient Mark mode, deactivate the mark.
4572 If `interprogram-cut-function' is non-nil, also save the text for a window
4573 system cut and paste.
4575 If you want to append the killed line to the last killed text,
4576 use \\[append-next-kill] before \\[kill-ring-save].
4578 The copied text is filtered by `filter-buffer-substring' before it is
4579 saved in the kill ring, so the actual saved text might be different
4580 from what was in the buffer.
4582 When called from Lisp, save in the kill ring the stretch of text
4583 between BEG and END, unless the optional argument REGION is
4584 non-nil, in which case ignore BEG and END, and save the current
4587 This command is similar to `copy-region-as-kill', except that it gives
4588 visual feedback indicating the extent of the region being copied."
4589 ;; Pass mark first, then point, because the order matters when
4590 ;; calling `kill-append'.
4591 (interactive (list (mark) (point)
4592 (prefix-numeric-value current-prefix-arg
)))
4593 (copy-region-as-kill beg end region
)
4594 ;; This use of called-interactively-p is correct because the code it
4595 ;; controls just gives the user visual feedback.
4596 (if (called-interactively-p 'interactive
)
4597 (indicate-copied-region)))
4599 (defun indicate-copied-region (&optional message-len
)
4600 "Indicate that the region text has been copied interactively.
4601 If the mark is visible in the selected window, blink the cursor
4602 between point and mark if there is currently no active region
4605 If the mark lies outside the selected window, display an
4606 informative message containing a sample of the copied text. The
4607 optional argument MESSAGE-LEN, if non-nil, specifies the length
4608 of this sample text; it defaults to 40."
4609 (let ((mark (mark t
))
4611 ;; Inhibit quitting so we can make a quit here
4612 ;; look like a C-g typed as a command.
4614 (if (pos-visible-in-window-p mark
(selected-window))
4615 ;; Swap point-and-mark quickly so as to show the region that
4616 ;; was selected. Don't do it if the region is highlighted.
4617 (unless (and (region-active-p)
4618 (face-background 'region
))
4619 ;; Swap point and mark.
4620 (set-marker (mark-marker) (point) (current-buffer))
4622 (sit-for blink-matching-delay
)
4624 (set-marker (mark-marker) mark
(current-buffer))
4626 ;; If user quit, deactivate the mark
4627 ;; as C-g would as a command.
4628 (and quit-flag
(region-active-p)
4630 (let ((len (min (abs (- mark point
))
4631 (or message-len
40))))
4633 ;; Don't say "killed"; that is misleading.
4634 (message "Saved text until \"%s\""
4635 (buffer-substring-no-properties (- mark len
) mark
))
4636 (message "Saved text from \"%s\""
4637 (buffer-substring-no-properties mark
(+ mark len
))))))))
4639 (defun append-next-kill (&optional interactive
)
4640 "Cause following command, if it kills, to add to previous kill.
4641 If the next command kills forward from point, the kill is
4642 appended to the previous killed text. If the command kills
4643 backward, the kill is prepended. Kill commands that act on the
4644 region, such as `kill-region', are regarded as killing forward if
4645 point is after mark, and killing backward if point is before
4648 If the next command is not a kill command, `append-next-kill' has
4651 The argument is used for internal purposes; do not supply one."
4653 ;; We don't use (interactive-p), since that breaks kbd macros.
4656 (setq this-command
'kill-region
)
4657 (message "If the next command is a kill, it will append"))
4658 (setq last-command
'kill-region
)))
4660 (defvar bidi-directional-controls-chars
"\x202a-\x202e\x2066-\x2069"
4661 "Character set that matches bidirectional formatting control characters.")
4663 (defvar bidi-directional-non-controls-chars
"^\x202a-\x202e\x2066-\x2069"
4664 "Character set that matches any character except bidirectional controls.")
4666 (defun squeeze-bidi-context-1 (from to category replacement
)
4667 "A subroutine of `squeeze-bidi-context'.
4668 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4669 (let ((pt (copy-marker from
))
4670 (limit (copy-marker to
))
4679 ;; L and R categories include embedding and
4680 ;; override controls, but we don't want to
4681 ;; replace them, because that might change
4682 ;; the visual order. Likewise with PDF and
4683 ;; isolate controls.
4684 (+ pt
(skip-chars-forward
4685 bidi-directional-non-controls-chars
4687 ;; Replace any run of non-RTL characters by a single LRM.
4688 (if (null (re-search-forward category lim1 t
))
4689 ;; No more characters of CATEGORY, we are done.
4691 (replace-match replacement nil t
)
4692 (move-marker pt
(point)))
4694 ;; Skip directional controls, if any.
4696 pt
(+ pt
(skip-chars-forward bidi-directional-controls-chars limit
))))))
4698 (defun squeeze-bidi-context (from to
)
4699 "Replace characters between FROM and TO while keeping bidi context.
4701 This function replaces the region of text with as few characters
4702 as possible, while preserving the effect that region will have on
4703 bidirectional display before and after the region."
4704 (let ((start (set-marker (make-marker)
4705 (if (> from
0) from
(+ (point-max) from
))))
4706 (end (set-marker (make-marker) to
))
4707 ;; This is for when they copy text with read-only text
4709 (inhibit-read-only t
))
4710 (if (null (marker-position end
))
4711 (setq end
(point-max-marker)))
4712 ;; Replace each run of non-RTL characters with a single LRM.
4713 (squeeze-bidi-context-1 start end
"\\CR+" "\x200e")
4714 ;; Replace each run of non-LTR characters with a single RLM. Note
4715 ;; that the \cR category includes both the Arabic Letter (AL) and
4716 ;; R characters; here we ignore the distinction between them,
4717 ;; because that distinction only affects Arabic Number (AN)
4718 ;; characters, which are weak and don't affect the reordering.
4719 (squeeze-bidi-context-1 start end
"\\CL+" "\x200f")))
4721 (defun line-substring-with-bidi-context (start end
&optional no-properties
)
4722 "Return buffer text between START and END with its bidi context.
4724 START and END are assumed to belong to the same physical line
4725 of buffer text. This function prepends and appends to the text
4726 between START and END bidi control characters that preserve the
4727 visual order of that text when it is inserted at some other place."
4728 (if (or (< start
(point-min))
4729 (> end
(point-max)))
4730 (signal 'args-out-of-range
(list (current-buffer) start end
)))
4731 (let ((buf (current-buffer))
4732 substr para-dir from to
)
4735 (setq para-dir
(current-bidi-paragraph-direction))
4736 (setq from
(line-beginning-position)
4737 to
(line-end-position))
4739 ;; If we don't have any mixed directional characters in the
4740 ;; entire line, we can just copy the substring without adding
4742 (if (or (looking-at-p "\\CR*$")
4743 (looking-at-p "\\CL*$"))
4744 (setq substr
(if no-properties
4745 (buffer-substring-no-properties start end
)
4746 (buffer-substring start end
)))
4750 (insert-buffer-substring-no-properties buf from to
)
4751 (insert-buffer-substring buf from to
))
4752 (squeeze-bidi-context 1 (1+ (- start from
)))
4753 (squeeze-bidi-context (- end to
) nil
)
4754 (buffer-substring 1 (point-max)))))
4756 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4757 ;; (1) force the string to have the same base embedding
4758 ;; direction as the paragraph direction at the source, no matter
4759 ;; what is the paragraph direction at destination; and (2) avoid
4760 ;; affecting the visual order of the surrounding text at
4761 ;; destination if there are characters of different
4762 ;; directionality there.
4763 (concat (if (eq para-dir
'left-to-right
) "\x2066" "\x2067")
4766 (defun buffer-substring-with-bidi-context (start end
&optional no-properties
)
4767 "Return portion of current buffer between START and END with bidi context.
4769 This function works similar to `buffer-substring', but it prepends and
4770 appends to the text bidi directional control characters necessary to
4771 preserve the visual appearance of the text if it is inserted at another
4772 place. This is useful when the buffer substring includes bidirectional
4773 text and control characters that cause non-trivial reordering on display.
4774 If copied verbatim, such text can have a very different visual appearance,
4775 and can also change the visual appearance of the surrounding text at the
4776 destination of the copy.
4778 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4779 the text properties."
4780 (let (line-end substr
)
4781 (if (or (< start
(point-min))
4782 (> end
(point-max)))
4783 (signal 'args-out-of-range
(list (current-buffer) start end
)))
4786 (setq line-end
(min end
(line-end-position)))
4787 (while (< start end
)
4791 (line-substring-with-bidi-context start line-end
4794 (setq start
(point))
4795 (setq line-end
(min end
(line-end-position))))
4800 (defcustom yank-handled-properties
4801 '((font-lock-face . yank-handle-font-lock-face-property
)
4802 (category . yank-handle-category-property
))
4803 "List of special text property handling conditions for yanking.
4804 Each element should have the form (PROP . FUN), where PROP is a
4805 property symbol and FUN is a function. When the `yank' command
4806 inserts text into the buffer, it scans the inserted text for
4807 stretches of text that have `eq' values of the text property
4808 PROP; for each such stretch of text, FUN is called with three
4809 arguments: the property's value in that text, and the start and
4810 end positions of the text.
4812 This is done prior to removing the properties specified by
4813 `yank-excluded-properties'."
4815 :type
'(repeat (cons (symbol :tag
"property symbol")
4819 ;; This is actually used in subr.el but defcustom does not work there.
4820 (defcustom yank-excluded-properties
4821 '(category field follow-link fontified font-lock-face help-echo
4822 intangible invisible keymap local-map mouse-face read-only
4824 "Text properties to discard when yanking.
4825 The value should be a list of text properties to discard or t,
4826 which means to discard all text properties.
4828 See also `yank-handled-properties'."
4829 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
4833 (defvar yank-window-start nil
)
4834 (defvar yank-undo-function nil
4835 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4836 Function is called with two parameters, START and END corresponding to
4837 the value of the mark and point; it is guaranteed that START <= END.
4838 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4840 (defun yank-pop (&optional arg
)
4841 "Replace just-yanked stretch of killed text with a different stretch.
4842 This command is allowed only immediately after a `yank' or a `yank-pop'.
4843 At such a time, the region contains a stretch of reinserted
4844 previously-killed text. `yank-pop' deletes that text and inserts in its
4845 place a different stretch of killed text.
4847 With no argument, the previous kill is inserted.
4848 With argument N, insert the Nth previous kill.
4849 If N is negative, this is a more recent kill.
4851 The sequence of kills wraps around, so that after the oldest one
4852 comes the newest one.
4854 This command honors the `yank-handled-properties' and
4855 `yank-excluded-properties' variables, and the `yank-handler' text
4856 property, in the way that `yank' does."
4858 (if (not (eq last-command
'yank
))
4859 (user-error "Previous command was not a yank"))
4860 (setq this-command
'yank
)
4861 (unless arg
(setq arg
1))
4862 (let ((inhibit-read-only t
)
4863 (before (< (point) (mark t
))))
4865 (funcall (or yank-undo-function
'delete-region
) (point) (mark t
))
4866 (funcall (or yank-undo-function
'delete-region
) (mark t
) (point)))
4867 (setq yank-undo-function nil
)
4868 (set-marker (mark-marker) (point) (current-buffer))
4869 (insert-for-yank (current-kill arg
))
4870 ;; Set the window start back where it was in the yank command,
4872 (set-window-start (selected-window) yank-window-start t
)
4874 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4875 ;; It is cleaner to avoid activation, even though the command
4876 ;; loop would deactivate the mark because we inserted text.
4877 (goto-char (prog1 (mark t
)
4878 (set-marker (mark-marker) (point) (current-buffer))))))
4881 (defun yank (&optional arg
)
4882 "Reinsert (\"paste\") the last stretch of killed text.
4883 More precisely, reinsert the most recent kill, which is the
4884 stretch of killed text most recently killed OR yanked. Put point
4885 at the end, and set mark at the beginning without activating it.
4886 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4887 With argument N, reinsert the Nth most recent kill.
4889 This command honors the `yank-handled-properties' and
4890 `yank-excluded-properties' variables, and the `yank-handler' text
4891 property, as described below.
4893 Properties listed in `yank-handled-properties' are processed,
4894 then those listed in `yank-excluded-properties' are discarded.
4896 If STRING has a non-nil `yank-handler' property anywhere, the
4897 normal insert behavior is altered, and instead, for each contiguous
4898 segment of STRING that has a given value of the `yank-handler'
4899 property, that value is used as follows:
4901 The value of a `yank-handler' property must be a list of one to four
4902 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4903 FUNCTION, if non-nil, should be a function of one argument (the
4904 object to insert); FUNCTION is called instead of `insert'.
4905 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4906 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4907 PARAM may be a list of strings to insert as a rectangle). If PARAM
4908 is nil, then the current segment of STRING is used.
4909 If NOEXCLUDE is present and non-nil, the normal removal of
4910 `yank-excluded-properties' is not performed; instead FUNCTION is
4911 responsible for the removal. This may be necessary if FUNCTION
4912 adjusts point before or after inserting the object.
4913 UNDO, if present and non-nil, should be a function to be called
4914 by `yank-pop' to undo the insertion of the current PARAM. It is
4915 given two arguments, the start and end of the region. FUNCTION
4916 may set `yank-undo-function' to override UNDO.
4918 See also the command `yank-pop' (\\[yank-pop])."
4920 (setq yank-window-start
(window-start))
4921 ;; If we don't get all the way thru, make last-command indicate that
4922 ;; for the following command.
4923 (setq this-command t
)
4925 (insert-for-yank (current-kill (cond
4930 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4931 ;; It is cleaner to avoid activation, even though the command
4932 ;; loop would deactivate the mark because we inserted text.
4933 (goto-char (prog1 (mark t
)
4934 (set-marker (mark-marker) (point) (current-buffer)))))
4935 ;; If we do get all the way thru, make this-command indicate that.
4936 (if (eq this-command t
)
4937 (setq this-command
'yank
))
4940 (defun rotate-yank-pointer (arg)
4941 "Rotate the yanking point in the kill ring.
4942 With ARG, rotate that many kills forward (or backward, if negative)."
4946 ;; Some kill commands.
4948 ;; Internal subroutine of delete-char
4949 (defun kill-forward-chars (arg)
4950 (if (listp arg
) (setq arg
(car arg
)))
4951 (if (eq arg
'-
) (setq arg -
1))
4952 (kill-region (point) (+ (point) arg
)))
4954 ;; Internal subroutine of backward-delete-char
4955 (defun kill-backward-chars (arg)
4956 (if (listp arg
) (setq arg
(car arg
)))
4957 (if (eq arg
'-
) (setq arg -
1))
4958 (kill-region (point) (- (point) arg
)))
4960 (defcustom backward-delete-char-untabify-method
'untabify
4961 "The method for untabifying when deleting backward.
4962 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4963 `hungry' -- delete all whitespace, both tabs and spaces;
4964 `all' -- delete all whitespace, including tabs, spaces and newlines;
4965 nil -- just delete one character."
4966 :type
'(choice (const untabify
) (const hungry
) (const all
) (const nil
))
4970 (defun backward-delete-char-untabify (arg &optional killp
)
4971 "Delete characters backward, changing tabs into spaces.
4972 The exact behavior depends on `backward-delete-char-untabify-method'.
4973 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4974 Interactively, ARG is the prefix arg (default 1)
4975 and KILLP is t if a prefix arg was specified."
4976 (interactive "*p\nP")
4977 (when (eq backward-delete-char-untabify-method
'untabify
)
4980 (while (and (> count
0) (not (bobp)))
4981 (if (= (preceding-char) ?
\t)
4982 (let ((col (current-column)))
4984 (setq col
(- col
(current-column)))
4985 (insert-char ?\s col
)
4988 (setq count
(1- count
))))))
4989 (let* ((skip (cond ((eq backward-delete-char-untabify-method
'hungry
) " \t")
4990 ((eq backward-delete-char-untabify-method
'all
)
4993 (let* ((oldpt (point))
4994 (wh (- oldpt
(save-excursion
4995 (skip-chars-backward skip
)
4996 (constrain-to-field nil oldpt
)))))
4997 (+ arg
(if (zerop wh
) 0 (1- wh
))))
4999 ;; Avoid warning about delete-backward-char
5000 (with-no-warnings (delete-backward-char n killp
))))
5002 (defun zap-to-char (arg char
)
5003 "Kill up to and including ARGth occurrence of CHAR.
5004 Case is ignored if `case-fold-search' is non-nil in the current buffer.
5005 Goes backward if ARG is negative; error if CHAR not found."
5006 (interactive (list (prefix-numeric-value current-prefix-arg
)
5007 (read-char "Zap to char: " t
)))
5008 ;; Avoid "obsolete" warnings for translation-table-for-input.
5010 (if (char-table-p translation-table-for-input
)
5011 (setq char
(or (aref translation-table-for-input char
) char
))))
5012 (kill-region (point) (progn
5013 (search-forward (char-to-string char
) nil nil arg
)
5016 ;; kill-line and its subroutines.
5018 (defcustom kill-whole-line nil
5019 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
5023 (defun kill-line (&optional arg
)
5024 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5025 With prefix argument ARG, kill that many lines from point.
5026 Negative arguments kill lines backward.
5027 With zero argument, kills the text before point on the current line.
5029 When calling from a program, nil means \"no arg\",
5030 a number counts as a prefix arg.
5032 To kill a whole line, when point is not at the beginning, type \
5033 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5035 If `show-trailing-whitespace' is non-nil, this command will just
5036 kill the rest of the current line, even if there are no nonblanks
5039 If option `kill-whole-line' is non-nil, then this command kills the whole line
5040 including its terminating newline, when used at the beginning of a line
5041 with no argument. As a consequence, you can always kill a whole line
5042 by typing \\[move-beginning-of-line] \\[kill-line].
5044 If you want to append the killed line to the last killed text,
5045 use \\[append-next-kill] before \\[kill-line].
5047 If the buffer is read-only, Emacs will beep and refrain from deleting
5048 the line, but put the line in the kill ring anyway. This means that
5049 you can use this command to copy text from a read-only buffer.
5050 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5053 (kill-region (point)
5054 ;; It is better to move point to the other end of the kill
5055 ;; before killing. That way, in a read-only buffer, point
5056 ;; moves across the text that is copied to the kill ring.
5057 ;; The choice has no effect on undo now that undo records
5058 ;; the value of point from before the command was run.
5061 (forward-visible-line (prefix-numeric-value arg
))
5063 (signal 'end-of-buffer nil
))
5066 (end-of-visible-line) (point))))
5067 (if (or (save-excursion
5068 ;; If trailing whitespace is visible,
5069 ;; don't treat it as nothing.
5070 (unless show-trailing-whitespace
5071 (skip-chars-forward " \t" end
))
5073 (and kill-whole-line
(bolp)))
5074 (forward-visible-line 1)
5078 (defun kill-whole-line (&optional arg
)
5080 With prefix ARG, kill that many lines starting from the current line.
5081 If ARG is negative, kill backward. Also kill the preceding newline.
5082 \(This is meant to make \\[repeat] work well with negative arguments.)
5083 If ARG is zero, kill current line but exclude the trailing newline."
5085 (or arg
(setq arg
1))
5086 (if (and (> arg
0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5087 (signal 'end-of-buffer nil
))
5088 (if (and (< arg
0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5089 (signal 'beginning-of-buffer nil
))
5090 (unless (eq last-command
'kill-region
)
5092 (setq last-command
'kill-region
))
5094 ;; We need to kill in two steps, because the previous command
5095 ;; could have been a kill command, in which case the text
5096 ;; before point needs to be prepended to the current kill
5097 ;; ring entry and the text after point appended. Also, we
5098 ;; need to use save-excursion to avoid copying the same text
5099 ;; twice to the kill ring in read-only buffers.
5101 (kill-region (point) (progn (forward-visible-line 0) (point))))
5102 (kill-region (point) (progn (end-of-visible-line) (point))))
5105 (kill-region (point) (progn (end-of-visible-line) (point))))
5106 (kill-region (point)
5107 (progn (forward-visible-line (1+ arg
))
5108 (unless (bobp) (backward-char))
5112 (kill-region (point) (progn (forward-visible-line 0) (point))))
5113 (kill-region (point)
5114 (progn (forward-visible-line arg
) (point))))))
5116 (defun forward-visible-line (arg)
5117 "Move forward by ARG lines, ignoring currently invisible newlines only.
5118 If ARG is negative, move backward -ARG lines.
5119 If ARG is zero, move to the beginning of the current line."
5124 (or (zerop (forward-line 1))
5125 (signal 'end-of-buffer nil
))
5126 ;; If the newline we just skipped is invisible,
5129 (get-char-property (1- (point)) 'invisible
)))
5130 (if (if (eq buffer-invisibility-spec t
)
5132 (or (memq prop buffer-invisibility-spec
)
5133 (assq prop buffer-invisibility-spec
)))
5134 (setq arg
(1+ arg
))))
5135 (setq arg
(1- arg
)))
5136 ;; If invisible text follows, and it is a number of complete lines,
5138 (let ((opoint (point)))
5139 (while (and (not (eobp))
5141 (get-char-property (point) 'invisible
)))
5142 (if (eq buffer-invisibility-spec t
)
5144 (or (memq prop buffer-invisibility-spec
)
5145 (assq prop buffer-invisibility-spec
)))))
5147 (if (get-text-property (point) 'invisible
)
5148 (or (next-single-property-change (point) 'invisible
)
5150 (next-overlay-change (point)))))
5152 (goto-char opoint
))))
5154 (while (or first
(<= arg
0))
5157 (or (zerop (forward-line -
1))
5158 (signal 'beginning-of-buffer nil
)))
5159 ;; If the newline we just moved to is invisible,
5163 (get-char-property (1- (point)) 'invisible
)))
5164 (unless (if (eq buffer-invisibility-spec t
)
5166 (or (memq prop buffer-invisibility-spec
)
5167 (assq prop buffer-invisibility-spec
)))
5168 (setq arg
(1+ arg
)))))
5170 ;; If invisible text follows, and it is a number of complete lines,
5172 (let ((opoint (point)))
5173 (while (and (not (bobp))
5175 (get-char-property (1- (point)) 'invisible
)))
5176 (if (eq buffer-invisibility-spec t
)
5178 (or (memq prop buffer-invisibility-spec
)
5179 (assq prop buffer-invisibility-spec
)))))
5181 (if (get-text-property (1- (point)) 'invisible
)
5182 (or (previous-single-property-change (point) 'invisible
)
5184 (previous-overlay-change (point)))))
5186 (goto-char opoint
)))))
5187 ((beginning-of-buffer end-of-buffer
)
5190 (defun end-of-visible-line ()
5191 "Move to end of current visible line."
5193 ;; If the following character is currently invisible,
5194 ;; skip all characters with that same `invisible' property value,
5195 ;; then find the next newline.
5196 (while (and (not (eobp))
5198 (skip-chars-forward "^\n")
5200 (get-char-property (point) 'invisible
)))
5201 (if (eq buffer-invisibility-spec t
)
5203 (or (memq prop buffer-invisibility-spec
)
5204 (assq prop buffer-invisibility-spec
))))))
5205 (skip-chars-forward "^\n")
5206 (if (get-text-property (point) 'invisible
)
5207 (goto-char (or (next-single-property-change (point) 'invisible
)
5209 (goto-char (next-overlay-change (point))))
5212 (defun kill-current-buffer ()
5213 "Kill the current buffer.
5214 When called in the minibuffer, get out of the minibuffer
5215 using `abort-recursive-edit'.
5217 This is like `kill-this-buffer', but it doesn't have to be invoked
5218 via the menu bar, and pays no attention to the menu-bar's frame."
5220 (let ((frame (selected-frame)))
5221 (if (and (frame-live-p frame
)
5222 (not (window-minibuffer-p (frame-selected-window frame
))))
5223 (kill-buffer (current-buffer))
5224 (abort-recursive-edit))))
5227 (defun insert-buffer (buffer)
5228 "Insert after point the contents of BUFFER.
5229 Puts mark after the inserted text.
5230 BUFFER may be a buffer or a buffer name."
5231 (declare (interactive-only insert-buffer-substring
))
5235 (barf-if-buffer-read-only)
5236 (read-buffer "Insert buffer: "
5237 (if (eq (selected-window) (next-window))
5238 (other-buffer (current-buffer))
5239 (window-buffer (next-window)))
5243 (insert-buffer-substring (get-buffer buffer
))
5247 (defun append-to-buffer (buffer start end
)
5248 "Append to specified buffer the text of the region.
5249 It is inserted into that buffer before its point.
5251 When calling from a program, give three arguments:
5252 BUFFER (or buffer name), START and END.
5253 START and END specify the portion of the current buffer to be copied."
5255 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t
))
5256 (region-beginning) (region-end)))
5257 (let* ((oldbuf (current-buffer))
5258 (append-to (get-buffer-create buffer
))
5259 (windows (get-buffer-window-list append-to t t
))
5262 (with-current-buffer append-to
5263 (setq point
(point))
5264 (barf-if-buffer-read-only)
5265 (insert-buffer-substring oldbuf start end
)
5266 (dolist (window windows
)
5267 (when (= (window-point window
) point
)
5268 (set-window-point window
(point))))))))
5270 (defun prepend-to-buffer (buffer start end
)
5271 "Prepend to specified buffer the text of the region.
5272 It is inserted into that buffer after its point.
5274 When calling from a program, give three arguments:
5275 BUFFER (or buffer name), START and END.
5276 START and END specify the portion of the current buffer to be copied."
5277 (interactive "BPrepend to buffer: \nr")
5278 (let ((oldbuf (current-buffer)))
5279 (with-current-buffer (get-buffer-create buffer
)
5280 (barf-if-buffer-read-only)
5282 (insert-buffer-substring oldbuf start end
)))))
5284 (defun copy-to-buffer (buffer start end
)
5285 "Copy to specified buffer the text of the region.
5286 It is inserted into that buffer, replacing existing text there.
5288 When calling from a program, give three arguments:
5289 BUFFER (or buffer name), START and END.
5290 START and END specify the portion of the current buffer to be copied."
5291 (interactive "BCopy to buffer: \nr")
5292 (let ((oldbuf (current-buffer)))
5293 (with-current-buffer (get-buffer-create buffer
)
5294 (barf-if-buffer-read-only)
5297 (insert-buffer-substring oldbuf start end
)))))
5299 (define-error 'mark-inactive
(purecopy "The mark is not active now"))
5301 (defvar activate-mark-hook nil
5302 "Hook run when the mark becomes active.
5303 It is also run at the end of a command, if the mark is active and
5304 it is possible that the region may have changed.")
5306 (defvar deactivate-mark-hook nil
5307 "Hook run when the mark becomes inactive.")
5309 (defun mark (&optional force
)
5310 "Return this buffer's mark value as integer, or nil if never set.
5312 In Transient Mark mode, this function signals an error if
5313 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5314 or the argument FORCE is non-nil, it disregards whether the mark
5315 is active, and returns an integer or nil in the usual way.
5317 If you are using this in an editing command, you are most likely making
5318 a mistake; see the documentation of `set-mark'."
5319 (if (or force
(not transient-mark-mode
) mark-active mark-even-if-inactive
)
5320 (marker-position (mark-marker))
5321 (signal 'mark-inactive nil
)))
5323 ;; Behind display-selections-p.
5325 (defun deactivate-mark (&optional force
)
5326 "Deactivate the mark.
5327 If Transient Mark mode is disabled, this function normally does
5328 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5330 Deactivating the mark sets `mark-active' to nil, updates the
5331 primary selection according to `select-active-regions', and runs
5332 `deactivate-mark-hook'.
5334 If Transient Mark mode was temporarily enabled, reset the value
5335 of the variable `transient-mark-mode'; if this causes Transient
5336 Mark mode to be disabled, don't change `mark-active' to nil or
5337 run `deactivate-mark-hook'."
5338 (when (or (region-active-p) force
)
5339 (when (and (if (eq select-active-regions
'only
)
5340 (eq (car-safe transient-mark-mode
) 'only
)
5341 select-active-regions
)
5343 (display-selections-p))
5344 ;; The var `saved-region-selection', if non-nil, is the text in
5345 ;; the region prior to the last command modifying the buffer.
5346 ;; Set the selection to that, or to the current region.
5347 (cond (saved-region-selection
5348 (if (gui-backend-selection-owner-p 'PRIMARY
)
5349 (gui-set-selection 'PRIMARY saved-region-selection
))
5350 (setq saved-region-selection nil
))
5351 ;; If another program has acquired the selection, region
5352 ;; deactivation should not clobber it (Bug#11772).
5353 ((and (/= (region-beginning) (region-end))
5354 (or (gui-backend-selection-owner-p 'PRIMARY
)
5355 (null (gui-backend-selection-exists-p 'PRIMARY
))))
5356 (gui-set-selection 'PRIMARY
5357 (funcall region-extract-function nil
)))))
5358 (when mark-active
(force-mode-line-update)) ;Refresh toolbar (bug#16382).
5360 ((eq (car-safe transient-mark-mode
) 'only
)
5361 (setq transient-mark-mode
(cdr transient-mark-mode
))
5362 (if (eq transient-mark-mode
(default-value 'transient-mark-mode
))
5363 (kill-local-variable 'transient-mark-mode
)))
5364 ((eq transient-mark-mode
'lambda
)
5365 (kill-local-variable 'transient-mark-mode
)))
5366 (setq mark-active nil
)
5367 (run-hooks 'deactivate-mark-hook
)
5368 (redisplay--update-region-highlight (selected-window))))
5370 (defun activate-mark (&optional no-tmm
)
5372 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5374 (unless (region-active-p)
5375 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5376 (setq mark-active t
)
5377 (unless (or transient-mark-mode no-tmm
)
5378 (setq-local transient-mark-mode
'lambda
))
5379 (run-hooks 'activate-mark-hook
))))
5381 (defun set-mark (pos)
5382 "Set this buffer's mark to POS. Don't use this function!
5383 That is to say, don't use this function unless you want
5384 the user to see that the mark has moved, and you want the previous
5385 mark position to be lost.
5387 Normally, when a new mark is set, the old one should go on the stack.
5388 This is why most applications should use `push-mark', not `set-mark'.
5390 Novice Emacs Lisp programmers often try to use the mark for the wrong
5391 purposes. The mark saves a location for the user's convenience.
5392 Most editing commands should not alter the mark.
5393 To remember a location for internal use in the Lisp program,
5394 store it in a Lisp variable. Example:
5396 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5399 (set-marker (mark-marker) pos
(current-buffer))
5400 (activate-mark 'no-tmm
))
5401 ;; Normally we never clear mark-active except in Transient Mark mode.
5402 ;; But when we actually clear out the mark value too, we must
5403 ;; clear mark-active in any mode.
5405 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5406 ;; it should never be nil if the mark is nil.
5407 (setq mark-active nil
)
5408 (set-marker (mark-marker) nil
)))
5410 (defun save-mark-and-excursion--save ()
5412 (let ((mark (mark-marker)))
5413 (and (marker-position mark
) (copy-marker mark
)))
5416 (defun save-mark-and-excursion--restore (saved-mark-info)
5417 (let ((saved-mark (car saved-mark-info
))
5418 (omark (marker-position (mark-marker)))
5420 (saved-mark-active (cdr saved-mark-info
)))
5422 (if (null saved-mark
)
5423 (set-marker (mark-marker) nil
)
5424 (setf nmark
(marker-position saved-mark
))
5425 (set-marker (mark-marker) nmark
)
5426 (set-marker saved-mark nil
))
5428 (let ((cur-mark-active mark-active
))
5429 (setq mark-active saved-mark-active
)
5430 ;; If mark is active now, and either was not active or was at a
5431 ;; different place, run the activate hook.
5432 (if saved-mark-active
5433 (when (or (not cur-mark-active
)
5434 (not (eq omark nmark
)))
5435 (run-hooks 'activate-mark-hook
))
5436 ;; If mark has ceased to be active, run deactivate hook.
5437 (when cur-mark-active
5438 (run-hooks 'deactivate-mark-hook
))))))
5440 (defmacro save-mark-and-excursion
(&rest body
)
5441 "Like `save-excursion', but also save and restore the mark state.
5442 This macro does what `save-excursion' did before Emacs 25.1."
5443 (declare (indent 0) (debug t
))
5444 (let ((saved-marker-sym (make-symbol "saved-marker")))
5445 `(let ((,saved-marker-sym
(save-mark-and-excursion--save)))
5447 (save-excursion ,@body
)
5448 (save-mark-and-excursion--restore ,saved-marker-sym
)))))
5450 (defcustom use-empty-active-region nil
5451 "Whether \"region-aware\" commands should act on empty regions.
5452 If nil, region-aware commands treat the empty region as inactive.
5453 If non-nil, region-aware commands treat the region as active as
5454 long as the mark is active, even if the region is empty.
5456 Region-aware commands are those that act on the region if it is
5457 active and Transient Mark mode is enabled, and on the text near
5461 :group
'editing-basics
)
5463 (defun use-region-p ()
5464 "Return t if the region is active and it is appropriate to act on it.
5465 This is used by commands that act specially on the region under
5466 Transient Mark mode.
5468 The return value is t if Transient Mark mode is enabled and the
5469 mark is active; furthermore, if `use-empty-active-region' is nil,
5470 the region must not be empty. Otherwise, the return value is nil.
5472 For some commands, it may be appropriate to ignore the value of
5473 `use-empty-active-region'; in that case, use `region-active-p'."
5474 (and (region-active-p)
5475 (or use-empty-active-region
(> (region-end) (region-beginning)))))
5477 (defun region-active-p ()
5478 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5480 Some commands act specially on the region when Transient Mark
5481 mode is enabled. Usually, such commands should use
5482 `use-region-p' instead of this function, because `use-region-p'
5483 also checks the value of `use-empty-active-region'."
5484 (and transient-mark-mode mark-active
5485 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5486 ;; without the mark being set (e.g. bug#17324). We really should fix
5487 ;; that problem, but in the mean time, let's make sure we don't say the
5488 ;; region is active when there's no mark.
5489 (progn (cl-assert (mark)) t
)))
5491 (defun region-bounds ()
5492 "Return the boundaries of the region as a pair of positions.
5493 Value is a list of cons cells of the form (START . END)."
5494 (funcall region-extract-function
'bounds
))
5496 (defun region-noncontiguous-p ()
5497 "Return non-nil if the region contains several pieces.
5498 An example is a rectangular region handled as a list of
5499 separate contiguous regions for each line."
5500 (> (length (region-bounds)) 1))
5502 (defvar redisplay-unhighlight-region-function
5503 (lambda (rol) (when (overlayp rol
) (delete-overlay rol
))))
5505 (defvar redisplay-highlight-region-function
5506 (lambda (start end window rol
)
5507 (if (not (overlayp rol
))
5508 (let ((nrol (make-overlay start end
)))
5509 (funcall redisplay-unhighlight-region-function rol
)
5510 (overlay-put nrol
'window window
)
5511 (overlay-put nrol
'face
'region
)
5512 ;; Normal priority so that a large region doesn't hide all the
5513 ;; overlays within it, but high secondary priority so that if it
5514 ;; ends/starts in the middle of a small overlay, that small overlay
5515 ;; won't hide the region's boundaries.
5516 (overlay-put nrol
'priority
'(nil .
100))
5518 (unless (and (eq (overlay-buffer rol
) (current-buffer))
5519 (eq (overlay-start rol
) start
)
5520 (eq (overlay-end rol
) end
))
5521 (move-overlay rol start end
(current-buffer)))
5524 (defun redisplay--update-region-highlight (window)
5525 (let ((rol (window-parameter window
'internal-region-overlay
)))
5526 (if (not (and (region-active-p)
5527 (or highlight-nonselected-windows
5528 (eq window
(selected-window))
5529 (and (window-minibuffer-p)
5530 (eq window
(minibuffer-selected-window))))))
5531 (funcall redisplay-unhighlight-region-function rol
)
5532 (let* ((pt (window-point window
))
5534 (start (min pt mark
))
5537 (funcall redisplay-highlight-region-function
5538 start end window rol
)))
5539 (unless (equal new rol
)
5540 (set-window-parameter window
'internal-region-overlay
5543 (defvar pre-redisplay-functions
(list #'redisplay--update-region-highlight
)
5544 "Hook run just before redisplay.
5545 It is called in each window that is to be redisplayed. It takes one argument,
5546 which is the window that will be redisplayed. When run, the `current-buffer'
5547 is set to the buffer displayed in that window.")
5549 (defun redisplay--pre-redisplay-functions (windows)
5550 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5552 (with-current-buffer (window-buffer (selected-window))
5553 (run-hook-with-args 'pre-redisplay-functions
(selected-window)))
5554 (dolist (win (if (listp windows
) windows
(window-list-1 nil nil t
)))
5555 (with-current-buffer (window-buffer win
)
5556 (run-hook-with-args 'pre-redisplay-functions win
))))))
5558 (add-function :before pre-redisplay-function
5559 #'redisplay--pre-redisplay-functions
)
5562 (defvar-local mark-ring nil
5563 "The list of former marks of the current buffer, most recent first.")
5564 (put 'mark-ring
'permanent-local t
)
5566 (defcustom mark-ring-max
16
5567 "Maximum size of mark ring. Start discarding off end if gets this big."
5569 :group
'editing-basics
)
5571 (defvar global-mark-ring nil
5572 "The list of saved global marks, most recent first.")
5574 (defcustom global-mark-ring-max
16
5575 "Maximum size of global mark ring. \
5576 Start discarding off end if gets this big."
5578 :group
'editing-basics
)
5580 (defun pop-to-mark-command ()
5581 "Jump to mark, and pop a new position for mark off the ring.
5582 \(Does not affect global mark ring)."
5585 (user-error "No mark set in this buffer")
5586 (if (= (point) (mark t
))
5587 (message "Mark popped"))
5588 (goto-char (mark t
))
5591 (defun push-mark-command (arg &optional nomsg
)
5592 "Set mark at where point is.
5593 If no prefix ARG and mark is already set there, just activate it.
5594 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5596 (let ((mark (mark t
)))
5597 (if (or arg
(null mark
) (/= mark
(point)))
5598 (push-mark nil nomsg t
)
5599 (activate-mark 'no-tmm
)
5601 (message "Mark activated")))))
5603 (defcustom set-mark-command-repeat-pop nil
5604 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5605 That means that C-u \\[set-mark-command] \\[set-mark-command]
5606 will pop the mark twice, and
5607 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5608 will pop the mark three times.
5610 A value of nil means \\[set-mark-command]'s behavior does not change
5611 after C-u \\[set-mark-command]."
5613 :group
'editing-basics
)
5615 (defun set-mark-command (arg)
5616 "Set the mark where point is, and activate it; or jump to the mark.
5617 Setting the mark also alters the region, which is the text
5618 between point and mark; this is the closest equivalent in
5619 Emacs to what some editors call the \"selection\".
5621 With no prefix argument, set the mark at point, and push the
5622 old mark position on local mark ring. Also push the new mark on
5623 global mark ring, if the previous mark was set in another buffer.
5625 When Transient Mark Mode is off, immediately repeating this
5626 command activates `transient-mark-mode' temporarily.
5628 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5629 jump to the mark, and set the mark from
5630 position popped off the local mark ring (this does not affect the global
5631 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5632 mark ring (see `pop-global-mark').
5634 If `set-mark-command-repeat-pop' is non-nil, repeating
5635 the \\[set-mark-command] command with no prefix argument pops the next position
5636 off the local (or global) mark ring and jumps there.
5638 With \\[universal-argument] \\[universal-argument] as prefix
5639 argument, unconditionally set mark where point is, even if
5640 `set-mark-command-repeat-pop' is non-nil.
5642 Novice Emacs Lisp programmers often try to use the mark for the wrong
5643 purposes. See the documentation of `set-mark' for more information."
5645 (cond ((eq transient-mark-mode
'lambda
)
5646 (kill-local-variable 'transient-mark-mode
))
5647 ((eq (car-safe transient-mark-mode
) 'only
)
5650 ((and (consp arg
) (> (prefix-numeric-value arg
) 4))
5651 (push-mark-command nil
))
5652 ((not (eq this-command
'set-mark-command
))
5654 (pop-to-mark-command)
5655 (push-mark-command t
)))
5656 ((and set-mark-command-repeat-pop
5657 (eq last-command
'pop-global-mark
)
5659 (setq this-command
'pop-global-mark
)
5661 ((or (and set-mark-command-repeat-pop
5662 (eq last-command
'pop-to-mark-command
))
5664 (setq this-command
'pop-to-mark-command
)
5665 (pop-to-mark-command))
5666 ((eq last-command
'set-mark-command
)
5667 (if (region-active-p)
5670 (message "Mark deactivated"))
5672 (message "Mark activated")))
5674 (push-mark-command nil
))))
5676 (defun push-mark (&optional location nomsg activate
)
5677 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5678 If the last global mark pushed was not in the current buffer,
5679 also push LOCATION on the global mark ring.
5680 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5682 Novice Emacs Lisp programmers often try to use the mark for the wrong
5683 purposes. See the documentation of `set-mark' for more information.
5685 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5686 (unless (null (mark t
))
5687 (setq mark-ring
(cons (copy-marker (mark-marker)) mark-ring
))
5688 (when (> (length mark-ring
) mark-ring-max
)
5689 (move-marker (car (nthcdr mark-ring-max mark-ring
)) nil
)
5690 (setcdr (nthcdr (1- mark-ring-max
) mark-ring
) nil
)))
5691 (set-marker (mark-marker) (or location
(point)) (current-buffer))
5692 ;; Now push the mark on the global mark ring.
5693 (if (and global-mark-ring
5694 (eq (marker-buffer (car global-mark-ring
)) (current-buffer)))
5695 ;; The last global mark pushed was in this same buffer.
5696 ;; Don't push another one.
5698 (setq global-mark-ring
(cons (copy-marker (mark-marker)) global-mark-ring
))
5699 (when (> (length global-mark-ring
) global-mark-ring-max
)
5700 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring
)) nil
)
5701 (setcdr (nthcdr (1- global-mark-ring-max
) global-mark-ring
) nil
)))
5702 (or nomsg executing-kbd-macro
(> (minibuffer-depth) 0)
5703 (message "Mark set"))
5704 (if (or activate
(not transient-mark-mode
))
5705 (set-mark (mark t
)))
5709 "Pop off mark ring into the buffer's actual mark.
5710 Does not set point. Does nothing if mark ring is empty."
5712 (setq mark-ring
(nconc mark-ring
(list (copy-marker (mark-marker)))))
5713 (set-marker (mark-marker) (+ 0 (car mark-ring
)) (current-buffer))
5714 (move-marker (car mark-ring
) nil
)
5715 (if (null (mark t
)) (ding))
5716 (setq mark-ring
(cdr mark-ring
)))
5719 (define-obsolete-function-alias
5720 'exchange-dot-and-mark
'exchange-point-and-mark
"23.3")
5721 (defun exchange-point-and-mark (&optional arg
)
5722 "Put the mark where point is now, and point where the mark is now.
5723 This command works even when the mark is not active,
5724 and it reactivates the mark.
5726 If Transient Mark mode is on, a prefix ARG deactivates the mark
5727 if it is active, and otherwise avoids reactivating it. If
5728 Transient Mark mode is off, a prefix ARG enables Transient Mark
5731 (let ((omark (mark t
))
5732 (temp-highlight (eq (car-safe transient-mark-mode
) 'only
)))
5734 (user-error "No mark set in this buffer"))
5737 (cond (temp-highlight
5738 (setq-local transient-mark-mode
(cons 'only transient-mark-mode
)))
5739 ((or (and arg
(region-active-p)) ; (xor arg (not (region-active-p)))
5740 (not (or arg
(region-active-p))))
5742 (t (activate-mark)))
5745 (defcustom shift-select-mode t
5746 "When non-nil, shifted motion keys activate the mark momentarily.
5748 While the mark is activated in this way, any shift-translated point
5749 motion key extends the region, and if Transient Mark mode was off, it
5750 is temporarily turned on. Furthermore, the mark will be deactivated
5751 by any subsequent point motion key that was not shift-translated, or
5752 by any action that normally deactivates the mark in Transient Mark mode.
5754 See `this-command-keys-shift-translated' for the meaning of
5757 :group
'editing-basics
)
5759 (defun handle-shift-selection ()
5760 "Activate/deactivate mark depending on invocation thru shift translation.
5761 This function is called by `call-interactively' when a command
5762 with a `^' character in its `interactive' spec is invoked, before
5763 running the command itself.
5765 If `shift-select-mode' is enabled and the command was invoked
5766 through shift translation, set the mark and activate the region
5767 temporarily, unless it was already set in this way. See
5768 `this-command-keys-shift-translated' for the meaning of shift
5771 Otherwise, if the region has been activated temporarily,
5772 deactivate it, and restore the variable `transient-mark-mode' to
5774 (cond ((and shift-select-mode this-command-keys-shift-translated
)
5775 (unless (and mark-active
5776 (eq (car-safe transient-mark-mode
) 'only
))
5777 (setq-local transient-mark-mode
5779 (unless (eq transient-mark-mode
'lambda
)
5780 transient-mark-mode
)))
5781 (push-mark nil nil t
)))
5782 ((eq (car-safe transient-mark-mode
) 'only
)
5783 (setq transient-mark-mode
(cdr transient-mark-mode
))
5784 (if (eq transient-mark-mode
(default-value 'transient-mark-mode
))
5785 (kill-local-variable 'transient-mark-mode
))
5786 (deactivate-mark))))
5788 (define-minor-mode transient-mark-mode
5789 "Toggle Transient Mark mode.
5790 With a prefix argument ARG, enable Transient Mark mode if ARG is
5791 positive, and disable it otherwise. If called from Lisp, enable
5792 Transient Mark mode if ARG is omitted or nil.
5794 Transient Mark mode is a global minor mode. When enabled, the
5795 region is highlighted with the `region' face whenever the mark
5796 is active. The mark is \"deactivated\" by changing the buffer,
5797 and after certain other operations that set the mark but whose
5798 main purpose is something else--for example, incremental search,
5799 \\[beginning-of-buffer], and \\[end-of-buffer].
5801 You can also deactivate the mark by typing \\[keyboard-quit] or
5802 \\[keyboard-escape-quit].
5804 Many commands change their behavior when Transient Mark mode is
5805 in effect and the mark is active, by acting on the region instead
5806 of their usual default part of the buffer's text. Examples of
5807 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5808 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5809 To see the documentation of commands which are sensitive to the
5810 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5811 or \"mark.*active\" at the prompt."
5813 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5814 :variable
(default-value 'transient-mark-mode
))
5816 (defvar widen-automatically t
5817 "Non-nil means it is ok for commands to call `widen' when they want to.
5818 Some commands will do this in order to go to positions outside
5819 the current accessible part of the buffer.
5821 If `widen-automatically' is nil, these commands will do something else
5822 as a fallback, and won't change the buffer bounds.")
5824 (defvar non-essential nil
5825 "Whether the currently executing code is performing an essential task.
5826 This variable should be non-nil only when running code which should not
5827 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5828 user for a password when we are simply scanning a set of files in the
5829 background or displaying possible completions before the user even asked
5832 (defun pop-global-mark ()
5833 "Pop off global mark ring and jump to the top location."
5835 ;; Pop entries which refer to non-existent buffers.
5836 (while (and global-mark-ring
(not (marker-buffer (car global-mark-ring
))))
5837 (setq global-mark-ring
(cdr global-mark-ring
)))
5838 (or global-mark-ring
5839 (error "No global mark set"))
5840 (let* ((marker (car global-mark-ring
))
5841 (buffer (marker-buffer marker
))
5842 (position (marker-position marker
)))
5843 (setq global-mark-ring
(nconc (cdr global-mark-ring
)
5844 (list (car global-mark-ring
))))
5846 (or (and (>= position
(point-min))
5847 (<= position
(point-max)))
5848 (if widen-automatically
5850 (error "Global mark position is outside accessible part of buffer")))
5851 (goto-char position
)
5852 (switch-to-buffer buffer
)))
5854 (defcustom next-line-add-newlines nil
5855 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5858 :group
'editing-basics
)
5860 (defun next-line (&optional arg try-vscroll
)
5861 "Move cursor vertically down ARG lines.
5862 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5863 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5864 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5865 function will not vscroll.
5869 If there is no character in the target line exactly under the current column,
5870 the cursor is positioned after the character in that line which spans this
5871 column, or at the end of the line if it is not long enough.
5872 If there is no line in the buffer after this one, behavior depends on the
5873 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5874 to create a line, and moves the cursor to that line. Otherwise it moves the
5875 cursor to the end of the buffer.
5877 If the variable `line-move-visual' is non-nil, this command moves
5878 by display lines. Otherwise, it moves by buffer lines, without
5879 taking variable-width characters or continued lines into account.
5880 See \\[next-logical-line] for a command that always moves by buffer lines.
5882 The command \\[set-goal-column] can be used to create
5883 a semipermanent goal column for this command.
5884 Then instead of trying to move exactly vertically (or as close as possible),
5885 this command moves to the specified goal column (or as close as possible).
5886 The goal column is stored in the variable `goal-column', which is nil
5887 when there is no goal column. Note that setting `goal-column'
5888 overrides `line-move-visual' and causes this command to move by buffer
5889 lines rather than by display lines."
5890 (declare (interactive-only forward-line
))
5891 (interactive "^p\np")
5892 (or arg
(setq arg
1))
5893 (if (and next-line-add-newlines
(= arg
1))
5894 (if (save-excursion (end-of-line) (eobp))
5895 ;; When adding a newline, don't expand an abbrev.
5896 (let ((abbrev-mode nil
))
5898 (insert (if use-hard-newlines hard-newline
"\n")))
5899 (line-move arg nil nil try-vscroll
))
5900 (if (called-interactively-p 'interactive
)
5902 (line-move arg nil nil try-vscroll
)
5903 ((beginning-of-buffer end-of-buffer
)
5904 (signal (car err
) (cdr err
))))
5905 (line-move arg nil nil try-vscroll
)))
5908 (defun previous-line (&optional arg try-vscroll
)
5909 "Move cursor vertically up ARG lines.
5910 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5911 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5912 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5913 function will not vscroll.
5917 If there is no character in the target line exactly over the current column,
5918 the cursor is positioned after the character in that line which spans this
5919 column, or at the end of the line if it is not long enough.
5921 If the variable `line-move-visual' is non-nil, this command moves
5922 by display lines. Otherwise, it moves by buffer lines, without
5923 taking variable-width characters or continued lines into account.
5924 See \\[previous-logical-line] for a command that always moves by buffer lines.
5926 The command \\[set-goal-column] can be used to create
5927 a semipermanent goal column for this command.
5928 Then instead of trying to move exactly vertically (or as close as possible),
5929 this command moves to the specified goal column (or as close as possible).
5930 The goal column is stored in the variable `goal-column', which is nil
5931 when there is no goal column. Note that setting `goal-column'
5932 overrides `line-move-visual' and causes this command to move by buffer
5933 lines rather than by display lines."
5934 (declare (interactive-only
5935 "use `forward-line' with negative argument instead."))
5936 (interactive "^p\np")
5937 (or arg
(setq arg
1))
5938 (if (called-interactively-p 'interactive
)
5940 (line-move (- arg
) nil nil try-vscroll
)
5941 ((beginning-of-buffer end-of-buffer
)
5942 (signal (car err
) (cdr err
))))
5943 (line-move (- arg
) nil nil try-vscroll
))
5946 (defcustom track-eol nil
5947 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5948 This means moving to the end of each line moved onto.
5949 The beginning of a blank line does not count as the end of a line.
5950 This has no effect when the variable `line-move-visual' is non-nil."
5952 :group
'editing-basics
)
5954 (defcustom goal-column nil
5955 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5956 A non-nil setting overrides the variable `line-move-visual', which see."
5957 :type
'(choice integer
5958 (const :tag
"None" nil
))
5959 :group
'editing-basics
)
5960 (make-variable-buffer-local 'goal-column
)
5962 (defvar temporary-goal-column
0
5963 "Current goal column for vertical motion.
5964 It is the column where point was at the start of the current run
5965 of vertical motion commands.
5967 When moving by visual lines via the function `line-move-visual', it is a cons
5968 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5969 divided by the default column width, and HSCROLL is the number of
5970 columns by which window is scrolled from left margin.
5972 When the `track-eol' feature is doing its job, the value is
5973 `most-positive-fixnum'.")
5975 (defcustom line-move-ignore-invisible t
5976 "Non-nil means commands that move by lines ignore invisible newlines.
5977 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5978 as if newlines that are invisible didn't exist, and count
5979 only visible newlines. Thus, moving across 2 newlines
5980 one of which is invisible will be counted as a one-line move.
5981 Also, a non-nil value causes invisible text to be ignored when
5982 counting columns for the purposes of keeping point in the same
5983 column by \\[next-line] and \\[previous-line].
5985 Outline mode sets this."
5987 :group
'editing-basics
)
5989 (defcustom line-move-visual t
5990 "When non-nil, `line-move' moves point by visual lines.
5991 This movement is based on where the cursor is displayed on the
5992 screen, instead of relying on buffer contents alone. It takes
5993 into account variable-width characters and line continuation.
5994 If nil, `line-move' moves point by logical lines.
5995 A non-nil setting of `goal-column' overrides the value of this variable
5996 and forces movement by logical lines.
5997 A window that is horizontally scrolled also forces movement by logical
6000 :group
'editing-basics
6003 ;; Only used if display-graphic-p.
6004 (declare-function font-info
"font.c" (name &optional frame
))
6006 (defun default-font-height ()
6007 "Return the height in pixels of the current buffer's default face font.
6009 If the default font is remapped (see `face-remapping-alist'), the
6010 function returns the height of the remapped face."
6011 (let ((default-font (face-font 'default
)))
6013 ((and (display-multi-font-p)
6014 ;; Avoid calling font-info if the frame's default font was
6015 ;; not changed since the frame was created. That's because
6016 ;; font-info is expensive for some fonts, see bug #14838.
6017 (not (string= (frame-parameter nil
'font
) default-font
)))
6018 (aref (font-info default-font
) 3))
6019 (t (frame-char-height)))))
6021 (defun default-font-width ()
6022 "Return the width in pixels of the current buffer's default face font.
6024 If the default font is remapped (see `face-remapping-alist'), the
6025 function returns the width of the remapped face."
6026 (let ((default-font (face-font 'default
)))
6028 ((and (display-multi-font-p)
6029 ;; Avoid calling font-info if the frame's default font was
6030 ;; not changed since the frame was created. That's because
6031 ;; font-info is expensive for some fonts, see bug #14838.
6032 (not (string= (frame-parameter nil
'font
) default-font
)))
6033 (let* ((info (font-info (face-font 'default
)))
6034 (width (aref info
11)))
6038 (t (frame-char-width)))))
6040 (defun default-line-height ()
6041 "Return the pixel height of current buffer's default-face text line.
6043 The value includes `line-spacing', if any, defined for the buffer
6045 (let ((dfh (default-font-height))
6046 (lsp (if (display-graphic-p)
6048 (default-value 'line-spacing
)
6049 (frame-parameter nil
'line-spacing
)
6053 (setq lsp
(truncate (* (frame-char-height) lsp
))))
6056 (defun window-screen-lines ()
6057 "Return the number of screen lines in the text area of the selected window.
6059 This is different from `window-text-height' in that this function counts
6060 lines in units of the height of the font used by the default face displayed
6061 in the window, not in units of the frame's default font, and also accounts
6062 for `line-spacing', if any, defined for the window's buffer or frame.
6064 The value is a floating-point number."
6065 (let ((edges (window-inside-pixel-edges))
6066 (dlh (default-line-height)))
6067 (/ (float (- (nth 3 edges
) (nth 1 edges
))) dlh
)))
6069 ;; Returns non-nil if partial move was done.
6070 (defun line-move-partial (arg noerror
&optional _to-end
)
6072 ;; Move backward (up).
6073 ;; If already vscrolled, reduce vscroll
6074 (let ((vs (window-vscroll nil t
))
6075 (dlh (default-line-height)))
6077 (set-window-vscroll nil
(- vs dlh
) t
)))
6079 ;; Move forward (down).
6080 (let* ((lh (window-line-height -
1))
6085 (this-lh (window-line-height))
6086 (this-height (car this-lh
))
6087 (this-ypos (nth 2 this-lh
))
6088 (dlh (default-line-height))
6089 (wslines (window-screen-lines))
6090 (edges (window-inside-pixel-edges))
6091 (winh (- (nth 3 edges
) (nth 1 edges
) 1))
6093 (if (> (mod wslines
1.0) 0.0)
6094 (setq wslines
(round (+ wslines
0.5))))
6099 (<= this-ypos
(- dlh
)))
6101 (let ((wend (pos-visible-in-window-p t nil t
)))
6102 (setq rbot
(nth 3 wend
)
6104 vpos
(nth 5 wend
))))
6106 (let ((wstart (pos-visible-in-window-p nil nil t
)))
6107 (setq this-ypos
(nth 2 wstart
)
6108 this-height
(nth 4 wstart
))))
6111 (let ((ppos (posn-at-point))
6113 (setq col-row
(posn-actual-col-row ppos
))
6115 (- (cdr col-row
) (window-vscroll))
6116 (cdr (posn-col-row ppos
))))))
6117 ;; VPOS > 0 means the last line is only partially visible.
6118 ;; But if the part that is visible is at least as tall as the
6119 ;; default font, that means the line is actually fully
6120 ;; readable, and something like line-spacing is hidden. So in
6121 ;; that case we accept the last line in the window as still
6122 ;; visible, and consider the margin as starting one line
6124 (if (and vpos
(> vpos
0))
6126 (>= rowh
(default-font-height))
6128 (setq last-line
(min (- wslines scroll-margin
) vpos
))
6129 (setq last-line
(min (- wslines scroll-margin
1) (1- vpos
)))))
6131 ;; If last line of window is fully visible, and vscrolling
6132 ;; more would make this line invisible, move forward.
6133 ((and (or (< (setq vs
(window-vscroll nil t
)) dlh
)
6135 (<= this-height dlh
))
6136 (or (null rbot
) (= rbot
0)))
6138 ;; If cursor is not in the bottom scroll margin, and the
6139 ;; current line is not too tall, move forward.
6140 ((and (or (null this-height
) (<= this-height winh
))
6145 ;; When already vscrolled, we vscroll some more if we can,
6146 ;; or clear vscroll and move forward at end of tall image.
6148 (when (or (and rbot
(> rbot
0))
6149 (and this-height
(> this-height dlh
)))
6150 (set-window-vscroll nil
(+ vs dlh
) t
)))
6151 ;; If cursor just entered the bottom scroll margin, move forward,
6152 ;; but also optionally vscroll one line so redisplay won't recenter.
6156 ;; Don't vscroll if the partially-visible line at window
6157 ;; bottom is not too tall (a.k.a. "just one more text
6158 ;; line"): in that case, we do want redisplay to behave
6159 ;; normally, i.e. recenter or whatever.
6161 ;; Note: ROWH + RBOT from the value returned by
6162 ;; pos-visible-in-window-p give the total height of the
6163 ;; partially-visible glyph row at the end of the window. As
6164 ;; we are dealing with floats, we disregard sub-pixel
6165 ;; discrepancies between that and DLH.
6166 (if (and rowh rbot
(>= (- (+ rowh rbot
) winh
) 1))
6167 (set-window-vscroll nil dlh t
))
6168 (line-move-1 arg noerror
)
6170 ;; If there are lines above the last line, scroll-up one line.
6171 ((and vpos
(> vpos
0))
6174 ;; Finally, start vscroll.
6176 (set-window-vscroll nil dlh t
)))))))
6179 ;; This is like line-move-1 except that it also performs
6180 ;; vertical scrolling of tall images if appropriate.
6181 ;; That is not really a clean thing to do, since it mixes
6182 ;; scrolling with cursor motion. But so far we don't have
6183 ;; a cleaner solution to the problem of making C-n do something
6184 ;; useful given a tall image.
6185 (defun line-move (arg &optional noerror _to-end try-vscroll
)
6186 "Move forward ARG lines.
6187 If NOERROR, don't signal an error if we can't move ARG lines.
6189 TRY-VSCROLL controls whether to vscroll tall lines: if either
6190 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6193 (line-move-1 arg noerror
)
6194 (unless (and auto-window-vscroll try-vscroll
6195 ;; Only vscroll for single line moves
6197 ;; Under scroll-conservatively, the display engine
6198 ;; does this better.
6199 (zerop scroll-conservatively
)
6200 ;; But don't vscroll in a keyboard macro.
6201 (not defining-kbd-macro
)
6202 (not executing-kbd-macro
)
6203 (line-move-partial arg noerror
))
6204 (set-window-vscroll nil
0 t
)
6205 (if (and line-move-visual
6206 ;; Display-based column are incompatible with goal-column.
6208 ;; When the text in the window is scrolled to the left,
6209 ;; display-based motion doesn't make sense (because each
6210 ;; logical line occupies exactly one screen line).
6211 (not (> (window-hscroll) 0))
6212 ;; Likewise when the text _was_ scrolled to the left
6213 ;; when the current run of vertical motion commands
6215 (not (and (memq last-command
6216 `(next-line previous-line
,this-command
))
6218 (numberp temporary-goal-column
)
6219 (>= temporary-goal-column
6220 (- (window-width) hscroll-margin
)))))
6221 (prog1 (line-move-visual arg noerror
)
6222 ;; If we moved into a tall line, set vscroll to make
6223 ;; scrolling through tall images more smooth.
6224 (let ((lh (line-pixel-height))
6225 (edges (window-inside-pixel-edges))
6226 (dlh (default-line-height))
6228 (setq winh
(- (nth 3 edges
) (nth 1 edges
) 1))
6230 (< (point) (window-start))
6235 (line-move-1 arg noerror
)))))
6237 ;; Display-based alternative to line-move-1.
6238 ;; Arg says how many lines to move. The value is t if we can move the
6239 ;; specified number of lines.
6240 (defun line-move-visual (arg &optional noerror
)
6241 "Move ARG lines forward.
6242 If NOERROR, don't signal an error if we can't move that many lines."
6243 (let ((opoint (point))
6244 (hscroll (window-hscroll))
6245 (lnum-width (line-number-display-width t
))
6247 ;; Check if the previous command was a line-motion command, or if
6248 ;; we were called from some other command.
6249 (if (and (consp temporary-goal-column
)
6250 (memq last-command
`(next-line previous-line
,this-command
)))
6251 ;; If so, there's no need to reset `temporary-goal-column',
6252 ;; but we may need to hscroll.
6253 (if (or (/= (cdr temporary-goal-column
) hscroll
)
6254 (> (cdr temporary-goal-column
) 0))
6255 (setq target-hscroll
(cdr temporary-goal-column
)))
6256 ;; Otherwise, we should reset `temporary-goal-column'.
6257 (let ((posn (posn-at-point))
6260 ;; Handle the `overflow-newline-into-fringe' case
6261 ;; (left-fringe is for the R2L case):
6262 ((memq (nth 1 posn
) '(right-fringe left-fringe
))
6263 (setq temporary-goal-column
(cons (window-width) hscroll
)))
6264 ((car (posn-x-y posn
))
6265 (setq x-pos
(- (car (posn-x-y posn
)) lnum-width
))
6266 ;; In R2L lines, the X pixel coordinate is measured from the
6267 ;; left edge of the window, but columns are still counted
6268 ;; from the logical-order beginning of the line, i.e. from
6269 ;; the right edge in this case. We need to adjust for that.
6270 (if (eq (current-bidi-paragraph-direction) 'right-to-left
)
6271 (setq x-pos
(- (window-body-width nil t
) 1 x-pos
)))
6272 (setq temporary-goal-column
6273 (cons (/ (float x-pos
)
6276 (executing-kbd-macro
6277 ;; When we move beyond the first/last character visible in
6278 ;; the window, posn-at-point will return nil, so we need to
6279 ;; approximate the goal column as below.
6280 (setq temporary-goal-column
6281 (mod (current-column) (window-text-width)))))))
6283 (set-window-hscroll (selected-window) target-hscroll
))
6284 ;; vertical-motion can move more than it was asked to if it moves
6285 ;; across display strings with newlines. We don't want to ring
6286 ;; the bell and announce beginning/end of buffer in that case.
6287 (or (and (or (and (>= arg
0)
6288 (>= (vertical-motion
6289 (cons (or goal-column
6290 (if (consp temporary-goal-column
)
6291 (car temporary-goal-column
)
6292 temporary-goal-column
))
6296 (<= (vertical-motion
6297 (cons (or goal-column
6298 (if (consp temporary-goal-column
)
6299 (car temporary-goal-column
)
6300 temporary-goal-column
))
6305 ;; If the goal column lies on a display string,
6306 ;; `vertical-motion' advances the cursor to the end
6307 ;; of the string. For arg < 0, this can cause the
6308 ;; cursor to get stuck. (Bug#3020).
6309 (= (vertical-motion arg
) arg
)))
6311 (signal (if (< arg
0) 'beginning-of-buffer
'end-of-buffer
)
6314 ;; This is the guts of next-line and previous-line.
6315 ;; Arg says how many lines to move.
6316 ;; The value is t if we can move the specified number of lines.
6317 (defun line-move-1 (arg &optional noerror _to-end
)
6318 ;; Don't run any point-motion hooks, and disregard intangibility,
6319 ;; for intermediate positions.
6320 (let ((inhibit-point-motion-hooks t
)
6323 (if (consp temporary-goal-column
)
6324 (setq temporary-goal-column
(+ (car temporary-goal-column
)
6325 (cdr temporary-goal-column
))))
6328 (if (not (memq last-command
'(next-line previous-line
)))
6329 (setq temporary-goal-column
6330 (if (and track-eol
(eolp)
6331 ;; Don't count beg of empty line as end of line
6332 ;; unless we just did explicit end-of-line.
6333 (or (not (bolp)) (eq last-command
'move-end-of-line
)))
6334 most-positive-fixnum
6337 (if (not (or (integerp selective-display
)
6338 line-move-ignore-invisible
))
6339 ;; Use just newline characters.
6340 ;; Set ARG to 0 if we move as many lines as requested.
6342 (progn (if (> arg
1) (forward-line (1- arg
)))
6343 ;; This way of moving forward ARG lines
6344 ;; verifies that we have a newline after the last one.
6345 ;; It doesn't get confused by intangible text.
6347 (if (zerop (forward-line 1))
6349 (and (zerop (forward-line arg
))
6353 (signal (if (< arg
0)
6354 'beginning-of-buffer
6357 ;; Move by arg lines, but ignore invisible ones.
6359 (while (and (> arg
0) (not done
))
6360 ;; If the following character is currently invisible,
6361 ;; skip all characters with that same `invisible' property value.
6362 (while (and (not (eobp)) (invisible-p (point)))
6363 (goto-char (next-char-property-change (point))))
6365 ;; We don't use `end-of-line', since we want to escape
6366 ;; from field boundaries occurring exactly at point.
6367 (goto-char (constrain-to-field
6368 (let ((inhibit-field-text-motion t
))
6369 (line-end-position))
6371 'inhibit-line-move-field-capture
))
6372 ;; If there's no invisibility here, move over the newline.
6376 (signal 'end-of-buffer nil
)
6378 ((and (> arg
1) ;; Use vertical-motion for last move
6379 (not (integerp selective-display
))
6380 (not (invisible-p (point))))
6381 ;; We avoid vertical-motion when possible
6382 ;; because that has to fontify.
6384 ;; Otherwise move a more sophisticated way.
6385 ((zerop (vertical-motion 1))
6387 (signal 'end-of-buffer nil
)
6390 (setq arg
(1- arg
))))
6391 ;; The logic of this is the same as the loop above,
6392 ;; it just goes in the other direction.
6393 (while (and (< arg
0) (not done
))
6394 ;; For completely consistency with the forward-motion
6395 ;; case, we should call beginning-of-line here.
6396 ;; However, if point is inside a field and on a
6397 ;; continued line, the call to (vertical-motion -1)
6398 ;; below won't move us back far enough; then we return
6399 ;; to the same column in line-move-finish, and point
6400 ;; gets stuck -- cyd
6405 (signal 'beginning-of-buffer nil
)
6407 ((and (< arg -
1) ;; Use vertical-motion for last move
6408 (not (integerp selective-display
))
6409 (not (invisible-p (1- (point)))))
6411 ((zerop (vertical-motion -
1))
6413 (signal 'beginning-of-buffer nil
)
6417 (while (and ;; Don't move over previous invis lines
6418 ;; if our target is the middle of this line.
6419 (or (zerop (or goal-column temporary-goal-column
))
6421 (not (bobp)) (invisible-p (1- (point))))
6422 (goto-char (previous-char-property-change (point))))))))
6423 ;; This is the value the function returns.
6427 ;; If we did not move down as far as desired, at least go
6428 ;; to end of line. Be sure to call point-entered and
6429 ;; point-left-hooks.
6430 (let* ((npoint (prog1 (line-end-position)
6431 (goto-char opoint
)))
6432 (inhibit-point-motion-hooks nil
))
6433 (goto-char npoint
)))
6435 ;; If we did not move up as far as desired,
6436 ;; at least go to beginning of line.
6437 (let* ((npoint (prog1 (line-beginning-position)
6438 (goto-char opoint
)))
6439 (inhibit-point-motion-hooks nil
))
6440 (goto-char npoint
)))
6442 (line-move-finish (or goal-column temporary-goal-column
)
6443 opoint
(> orig-arg
0)))))))
6445 (defun line-move-finish (column opoint forward
)
6448 ;; Set REPEAT to t to repeat the whole thing.
6453 (line-beg (line-beginning-position))
6455 ;; Compute the end of the line
6456 ;; ignoring effectively invisible newlines.
6458 ;; Like end-of-line but ignores fields.
6459 (skip-chars-forward "^\n")
6460 (while (and (not (eobp)) (invisible-p (point)))
6461 (goto-char (next-char-property-change (point)))
6462 (skip-chars-forward "^\n"))
6465 ;; Move to the desired column.
6466 (if (and line-move-visual
6467 (not (or truncate-lines truncate-partial-width-windows
)))
6468 ;; Under line-move-visual, goal-column should be
6469 ;; interpreted in units of the frame's canonical character
6470 ;; width, which is exactly what vertical-motion does.
6471 (vertical-motion (cons column
0))
6472 (line-move-to-column (truncate column
)))
6474 ;; Corner case: suppose we start out in a field boundary in
6475 ;; the middle of a continued line. When we get to
6476 ;; line-move-finish, point is at the start of a new *screen*
6477 ;; line but the same text line; then line-move-to-column would
6478 ;; move us backwards. Test using C-n with point on the "x" in
6479 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6486 ;; Process intangibility within a line.
6487 ;; With inhibit-point-motion-hooks bound to nil, a call to
6488 ;; goto-char moves point past intangible text.
6490 ;; However, inhibit-point-motion-hooks controls both the
6491 ;; intangibility and the point-entered/point-left hooks. The
6492 ;; following hack avoids calling the point-* hooks
6493 ;; unnecessarily. Note that we move *forward* past intangible
6494 ;; text when the initial and final points are the same.
6496 (let ((inhibit-point-motion-hooks nil
))
6499 ;; If intangibility moves us to a different (later) place
6500 ;; in the same line, use that as the destination.
6501 (if (<= (point) line-end
)
6503 ;; If that position is "too late",
6504 ;; try the previous allowable position.
6508 ;; If going forward, don't accept the previous
6509 ;; allowable position if it is before the target line.
6510 (< line-beg
(point))
6511 ;; If going backward, don't accept the previous
6512 ;; allowable position if it is still after the target line.
6513 (<= (point) line-end
))
6515 ;; As a last resort, use the end of the line.
6516 (setq new line-end
))))
6518 ;; Now move to the updated destination, processing fields
6519 ;; as well as intangibility.
6521 (let ((inhibit-point-motion-hooks nil
))
6523 ;; Ignore field boundaries if the initial and final
6524 ;; positions have the same `field' property, even if the
6525 ;; fields are non-contiguous. This seems to be "nicer"
6526 ;; behavior in many situations.
6527 (if (eq (get-char-property new
'field
)
6528 (get-char-property opoint
'field
))
6530 (constrain-to-field new opoint t t
6531 'inhibit-line-move-field-capture
))))
6533 ;; If all this moved us to a different line,
6534 ;; retry everything within that new line.
6535 (when (or (< (point) line-beg
) (> (point) line-end
))
6536 ;; Repeat the intangibility and field processing.
6537 (setq repeat t
))))))
6539 (defun line-move-to-column (col)
6540 "Try to find column COL, considering invisibility.
6541 This function works only in certain cases,
6542 because what we really need is for `move-to-column'
6543 and `current-column' to be able to ignore invisible text."
6546 (move-to-column col
))
6548 (when (and line-move-ignore-invisible
6549 (not (bolp)) (invisible-p (1- (point))))
6550 (let ((normal-location (point))
6551 (normal-column (current-column)))
6552 ;; If the following character is currently invisible,
6553 ;; skip all characters with that same `invisible' property value.
6554 (while (and (not (eobp))
6555 (invisible-p (point)))
6556 (goto-char (next-char-property-change (point))))
6557 ;; Have we advanced to a larger column position?
6558 (if (> (current-column) normal-column
)
6559 ;; We have made some progress towards the desired column.
6560 ;; See if we can make any further progress.
6561 (line-move-to-column (+ (current-column) (- col normal-column
)))
6562 ;; Otherwise, go to the place we originally found
6563 ;; and move back over invisible text.
6564 ;; that will get us to the same place on the screen
6565 ;; but with a more reasonable buffer position.
6566 (goto-char normal-location
)
6568 ;; We want the real line beginning, so it's consistent
6569 ;; with bolp below, otherwise we might infloop.
6570 (let ((inhibit-field-text-motion t
))
6571 (line-beginning-position))))
6572 (while (and (not (bolp)) (invisible-p (1- (point))))
6573 (goto-char (previous-char-property-change (point) line-beg
))))))))
6575 (defun move-end-of-line (arg)
6576 "Move point to end of current line as displayed.
6577 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6578 If point reaches the beginning or end of buffer, it stops there.
6580 To ignore the effects of the `intangible' text or overlay
6581 property, bind `inhibit-point-motion-hooks' to t.
6582 If there is an image in the current line, this function
6583 disregards newlines that are part of the text on which the image
6586 (or arg
(setq arg
1))
6591 (let ((goal-column 0)
6592 (line-move-visual nil
))
6593 (and (line-move arg t
)
6594 ;; With bidi reordering, we may not be at bol,
6595 ;; so make sure we are.
6596 (skip-chars-backward "^\n")
6599 (while (and (not (bobp)) (invisible-p (1- (point))))
6600 (goto-char (previous-single-char-property-change
6601 (point) 'invisible
)))
6605 (if (and (> (point) newpos
)
6606 (eq (preceding-char) ?
\n))
6608 (if (and (> (point) newpos
) (not (eobp))
6609 (not (eq (following-char) ?
\n)))
6610 ;; If we skipped something intangible and now we're not
6611 ;; really at eol, keep going.
6615 (defun move-beginning-of-line (arg)
6616 "Move point to beginning of current line as displayed.
6617 \(If there's an image in the line, this disregards newlines
6618 which are part of the text that the image rests on.)
6620 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6621 If point reaches the beginning or end of buffer, it stops there.
6622 \(But if the buffer doesn't end in a newline, it stops at the
6623 beginning of the last line.)
6624 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6626 (or arg
(setq arg
1))
6628 (let ((orig (point))
6629 first-vis first-vis-field-value
)
6631 ;; Move by lines, if ARG is not 1 (the default).
6633 (let ((line-move-visual nil
))
6634 (line-move (1- arg
) t
)))
6636 ;; Move to beginning-of-line, ignoring fields and invisible text.
6637 (skip-chars-backward "^\n")
6638 (while (and (not (bobp)) (invisible-p (1- (point))))
6639 (goto-char (previous-char-property-change (point)))
6640 (skip-chars-backward "^\n"))
6642 ;; Now find first visible char in the line.
6643 (while (and (< (point) orig
) (invisible-p (point)))
6644 (goto-char (next-char-property-change (point) orig
)))
6645 (setq first-vis
(point))
6647 ;; See if fields would stop us from reaching FIRST-VIS.
6648 (setq first-vis-field-value
6649 (constrain-to-field first-vis orig
(/= arg
1) t nil
))
6651 (goto-char (if (/= first-vis-field-value first-vis
)
6652 ;; If yes, obey them.
6653 first-vis-field-value
6654 ;; Otherwise, move to START with attention to fields.
6655 ;; (It is possible that fields never matter in this case.)
6656 (constrain-to-field (point) orig
6657 (/= arg
1) t nil
)))))
6660 ;; Many people have said they rarely use this feature, and often type
6661 ;; it by accident. Maybe it shouldn't even be on a key.
6662 (put 'set-goal-column
'disabled t
)
6664 (defun set-goal-column (arg)
6665 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6666 Those commands will move to this position in the line moved to
6667 rather than trying to keep the same horizontal position.
6668 With a non-nil argument ARG, clears out the goal column
6669 so that \\[next-line] and \\[previous-line] resume vertical motion.
6670 The goal column is stored in the variable `goal-column'.
6671 This is a buffer-local setting."
6675 (setq goal-column nil
)
6676 (message "No goal column"))
6677 (setq goal-column
(current-column))
6678 ;; The older method below can be erroneous if `set-goal-column' is bound
6679 ;; to a sequence containing %
6680 ;;(message (substitute-command-keys
6681 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6685 (format "Goal column %d " goal-column
)
6686 (substitute-command-keys
6687 "(use \\[set-goal-column] with an arg to unset it)")))
6692 ;;; Editing based on visual lines, as opposed to logical lines.
6694 (defun end-of-visual-line (&optional n
)
6695 "Move point to end of current visual line.
6696 With argument N not nil or 1, move forward N - 1 visual lines first.
6697 If point reaches the beginning or end of buffer, it stops there.
6698 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6702 (let ((line-move-visual t
))
6703 (line-move (1- n
) t
)))
6704 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6705 ;; constrain to field boundaries, so we don't either.
6706 (vertical-motion (cons (window-width) 0)))
6708 (defun beginning-of-visual-line (&optional n
)
6709 "Move point to beginning of current visual line.
6710 With argument N not nil or 1, move forward N - 1 visual lines first.
6711 If point reaches the beginning or end of buffer, it stops there.
6712 \(But if the buffer doesn't end in a newline, it stops at the
6713 beginning of the last visual line.)
6714 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6717 (let ((opoint (point)))
6719 (let ((line-move-visual t
))
6720 (line-move (1- n
) t
)))
6722 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6723 (goto-char (constrain-to-field (point) opoint
(/= n
1)))))
6725 (defun kill-visual-line (&optional arg
)
6726 "Kill the rest of the visual line.
6727 With prefix argument ARG, kill that many visual lines from point.
6728 If ARG is negative, kill visual lines backward.
6729 If ARG is zero, kill the text before point on the current visual
6732 If you want to append the killed line to the last killed text,
6733 use \\[append-next-kill] before \\[kill-line].
6735 If the buffer is read-only, Emacs will beep and refrain from deleting
6736 the line, but put the line in the kill ring anyway. This means that
6737 you can use this command to copy text from a read-only buffer.
6738 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6741 ;; Like in `kill-line', it's better to move point to the other end
6742 ;; of the kill before killing.
6743 (let ((opoint (point))
6744 (kill-whole-line (and kill-whole-line
(bolp))))
6746 (vertical-motion (prefix-numeric-value arg
))
6747 (end-of-visual-line 1)
6748 (if (= (point) opoint
)
6750 ;; Skip any trailing whitespace at the end of the visual line.
6751 ;; We used to do this only if `show-trailing-whitespace' is
6752 ;; nil, but that's wrong; the correct thing would be to check
6753 ;; whether the trailing whitespace is highlighted. But, it's
6754 ;; OK to just do this unconditionally.
6755 (skip-chars-forward " \t")))
6756 (kill-region opoint
(if (and kill-whole-line
(= (following-char) ?
\n))
6760 (defun next-logical-line (&optional arg try-vscroll
)
6761 "Move cursor vertically down ARG lines.
6762 This is identical to `next-line', except that it always moves
6763 by logical lines instead of visual lines, ignoring the value of
6764 the variable `line-move-visual'."
6765 (interactive "^p\np")
6766 (let ((line-move-visual nil
))
6768 (next-line arg try-vscroll
))))
6770 (defun previous-logical-line (&optional arg try-vscroll
)
6771 "Move cursor vertically up ARG lines.
6772 This is identical to `previous-line', except that it always moves
6773 by logical lines instead of visual lines, ignoring the value of
6774 the variable `line-move-visual'."
6775 (interactive "^p\np")
6776 (let ((line-move-visual nil
))
6778 (previous-line arg try-vscroll
))))
6780 (defgroup visual-line nil
6781 "Editing based on visual lines."
6785 (defvar visual-line-mode-map
6786 (let ((map (make-sparse-keymap)))
6787 (define-key map
[remap kill-line
] 'kill-visual-line
)
6788 (define-key map
[remap move-beginning-of-line
] 'beginning-of-visual-line
)
6789 (define-key map
[remap move-end-of-line
] 'end-of-visual-line
)
6790 ;; These keybindings interfere with xterm function keys. Are
6791 ;; there any other suitable bindings?
6792 ;; (define-key map "\M-[" 'previous-logical-line)
6793 ;; (define-key map "\M-]" 'next-logical-line)
6796 (defcustom visual-line-fringe-indicators
'(nil nil
)
6797 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6798 The value should be a list of the form (LEFT RIGHT), where LEFT
6799 and RIGHT are symbols representing the bitmaps to display, to
6800 indicate wrapped lines, in the left and right fringes respectively.
6801 See also `fringe-indicator-alist'.
6802 The default is not to display fringe indicators for wrapped lines.
6803 This variable does not affect fringe indicators displayed for
6805 :type
'(list (choice (const :tag
"Hide left indicator" nil
)
6806 (const :tag
"Left curly arrow" left-curly-arrow
)
6807 (symbol :tag
"Other bitmap"))
6808 (choice (const :tag
"Hide right indicator" nil
)
6809 (const :tag
"Right curly arrow" right-curly-arrow
)
6810 (symbol :tag
"Other bitmap")))
6811 :set
(lambda (symbol value
)
6812 (dolist (buf (buffer-list))
6813 (with-current-buffer buf
6814 (when (and (boundp 'visual-line-mode
)
6815 (symbol-value 'visual-line-mode
))
6816 (setq fringe-indicator-alist
6817 (cons (cons 'continuation value
)
6820 (copy-tree fringe-indicator-alist
)))))))
6821 (set-default symbol value
)))
6823 (defvar visual-line--saved-state nil
)
6825 (define-minor-mode visual-line-mode
6826 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6827 Interactively, with a prefix argument, enable
6828 Visual Line mode if the prefix argument is positive,
6829 and disable it otherwise. If called from Lisp, toggle
6830 the mode if ARG is `toggle', disable the mode if ARG is
6831 a non-positive integer, and enable the mode otherwise
6832 \(including if ARG is omitted or nil or a positive integer).
6834 When Visual Line mode is enabled, `word-wrap' is turned on in
6835 this buffer, and simple editing commands are redefined to act on
6836 visual lines, not logical lines. See Info node `Visual Line
6838 :keymap visual-line-mode-map
6841 (if visual-line-mode
6843 (set (make-local-variable 'visual-line--saved-state
) nil
)
6844 ;; Save the local values of some variables, to be restored if
6845 ;; visual-line-mode is turned off.
6846 (dolist (var '(line-move-visual truncate-lines
6847 truncate-partial-width-windows
6848 word-wrap fringe-indicator-alist
))
6849 (if (local-variable-p var
)
6850 (push (cons var
(symbol-value var
))
6851 visual-line--saved-state
)))
6852 (set (make-local-variable 'line-move-visual
) t
)
6853 (set (make-local-variable 'truncate-partial-width-windows
) nil
)
6854 (setq truncate-lines nil
6856 fringe-indicator-alist
6857 (cons (cons 'continuation visual-line-fringe-indicators
)
6858 fringe-indicator-alist
)))
6859 (kill-local-variable 'line-move-visual
)
6860 (kill-local-variable 'word-wrap
)
6861 (kill-local-variable 'truncate-lines
)
6862 (kill-local-variable 'truncate-partial-width-windows
)
6863 (kill-local-variable 'fringe-indicator-alist
)
6864 (dolist (saved visual-line--saved-state
)
6865 (set (make-local-variable (car saved
)) (cdr saved
)))
6866 (kill-local-variable 'visual-line--saved-state
)))
6868 (defun turn-on-visual-line-mode ()
6869 (visual-line-mode 1))
6871 (define-globalized-minor-mode global-visual-line-mode
6872 visual-line-mode turn-on-visual-line-mode
)
6875 (defun transpose-chars (arg)
6876 "Interchange characters around point, moving forward one character.
6877 With prefix arg ARG, effect is to take character before point
6878 and drag it forward past ARG other characters (backward if ARG negative).
6879 If no argument and at end of line, the previous two chars are exchanged."
6881 (when (and (null arg
) (eolp) (not (bobp))
6882 (not (get-text-property (1- (point)) 'read-only
)))
6884 (transpose-subr 'forward-char
(prefix-numeric-value arg
)))
6886 (defun transpose-words (arg)
6887 "Interchange words around point, leaving point at end of them.
6888 With prefix arg ARG, effect is to take word before or around point
6889 and drag it forward past ARG other words (backward if ARG negative).
6890 If ARG is zero, the words around or after point and around or after mark
6892 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6894 (transpose-subr 'forward-word arg
))
6896 (defun transpose-sexps (arg)
6897 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6898 Unlike `transpose-words', point must be between the two sexps and not
6899 in the middle of a sexp to be transposed.
6900 With non-zero prefix arg ARG, effect is to take the sexp before point
6901 and drag it forward past ARG other sexps (backward if ARG is negative).
6902 If ARG is zero, the sexps ending at or after point and at or after mark
6907 ;; Here we should try to simulate the behavior of
6908 ;; (cons (progn (forward-sexp x) (point))
6909 ;; (progn (forward-sexp (- x)) (point)))
6910 ;; Except that we don't want to rely on the second forward-sexp
6911 ;; putting us back to where we want to be, since forward-sexp-function
6912 ;; might do funny things like infix-precedence.
6914 (looking-at "\\sw\\|\\s_")
6916 (save-excursion (forward-char -
1) (looking-at "\\sw\\|\\s_"))))
6917 ;; Jumping over a symbol. We might be inside it, mind you.
6918 (progn (funcall (if (> arg
0)
6919 'skip-syntax-backward
'skip-syntax-forward
)
6921 (cons (save-excursion (forward-sexp arg
) (point)) (point)))
6922 ;; Otherwise, we're between sexps. Take a step back before jumping
6923 ;; to make sure we'll obey the same precedence no matter which direction
6925 (funcall (if (> arg
0) 'skip-syntax-backward
'skip-syntax-forward
) " .")
6926 (cons (save-excursion (forward-sexp arg
) (point))
6927 (progn (while (or (forward-comment (if (> arg
0) 1 -
1))
6928 (not (zerop (funcall (if (> arg
0)
6929 'skip-syntax-forward
6930 'skip-syntax-backward
)
6935 (defun transpose-lines (arg)
6936 "Exchange current line and previous line, leaving point after both.
6937 With argument ARG, takes previous line and moves it past ARG lines.
6938 With argument 0, interchanges line point is in with line mark is in."
6940 (transpose-subr (function
6944 ;; Move forward over ARG lines,
6945 ;; but create newlines if necessary.
6946 (setq arg
(forward-line arg
))
6947 (if (/= (preceding-char) ?
\n)
6948 (setq arg
(1+ arg
)))
6951 (forward-line arg
))))
6954 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6955 ;; which seems inconsistent with the ARG /= 0 case.
6956 ;; FIXME document SPECIAL.
6957 (defun transpose-subr (mover arg
&optional special
)
6958 "Subroutine to do the work of transposing objects.
6959 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6960 moves forward by units of the given object (e.g. forward-sentence,
6961 forward-paragraph). If ARG is zero, exchanges the current object
6962 with the one containing mark. If ARG is an integer, moves the
6963 current object past ARG following (if ARG is positive) or
6964 preceding (if ARG is negative) objects, leaving point after the
6966 (let ((aux (if special mover
6968 (cons (progn (funcall mover x
) (point))
6969 (progn (funcall mover
(- x
)) (point))))))
6974 (setq pos1
(funcall aux
1))
6975 (goto-char (or (mark) (error "No mark set in this buffer")))
6976 (setq pos2
(funcall aux
1))
6977 (transpose-subr-1 pos1 pos2
))
6978 (exchange-point-and-mark))
6980 (setq pos1
(funcall aux -
1))
6981 (setq pos2
(funcall aux arg
))
6982 (transpose-subr-1 pos1 pos2
)
6983 (goto-char (car pos2
)))
6985 (setq pos1
(funcall aux -
1))
6986 (goto-char (car pos1
))
6987 (setq pos2
(funcall aux arg
))
6988 (transpose-subr-1 pos1 pos2
)
6989 (goto-char (+ (car pos2
) (- (cdr pos1
) (car pos1
))))))))
6991 (defun transpose-subr-1 (pos1 pos2
)
6992 (when (> (car pos1
) (cdr pos1
)) (setq pos1
(cons (cdr pos1
) (car pos1
))))
6993 (when (> (car pos2
) (cdr pos2
)) (setq pos2
(cons (cdr pos2
) (car pos2
))))
6994 (when (> (car pos1
) (car pos2
))
6996 (setq pos1 pos2 pos2 swap
)))
6997 (if (> (cdr pos1
) (car pos2
)) (error "Don't have two things to transpose"))
6998 (atomic-change-group
6999 ;; This sequence of insertions attempts to preserve marker
7000 ;; positions at the start and end of the transposed objects.
7001 (let* ((word (buffer-substring (car pos2
) (cdr pos2
)))
7002 (len1 (- (cdr pos1
) (car pos1
)))
7003 (len2 (length word
))
7004 (boundary (make-marker)))
7005 (set-marker boundary
(car pos2
))
7006 (goto-char (cdr pos1
))
7007 (insert-before-markers word
)
7008 (setq word
(delete-and-extract-region (car pos1
) (+ (car pos1
) len1
)))
7009 (goto-char boundary
)
7011 (goto-char (+ boundary len1
))
7012 (delete-region (point) (+ (point) len2
))
7013 (set-marker boundary nil
))))
7015 (defun backward-word (&optional arg
)
7016 "Move backward until encountering the beginning of a word.
7017 With argument ARG, do this that many times.
7018 If ARG is omitted or nil, move point backward one word.
7020 The word boundaries are normally determined by the buffer's
7021 syntax table and character script (according to
7022 `char-script-table'), but `find-word-boundary-function-table',
7023 such as set up by `subword-mode', can change that. If a Lisp
7024 program needs to move by words determined strictly by the syntax
7025 table, it should use `backward-word-strictly' instead. See Info
7026 node `(elisp) Word Motion' for details."
7028 (forward-word (- (or arg
1))))
7030 (defun mark-word (&optional arg allow-extend
)
7031 "Set mark ARG words away from point.
7032 The place mark goes is the same place \\[forward-word] would
7033 move to with the same argument.
7034 Interactively, if this command is repeated
7035 or (in Transient Mark mode) if the mark is active,
7036 it marks the next ARG words after the ones already marked."
7037 (interactive "P\np")
7038 (cond ((and allow-extend
7039 (or (and (eq last-command this-command
) (mark t
))
7041 (setq arg
(if arg
(prefix-numeric-value arg
)
7042 (if (< (mark) (point)) -
1 1)))
7051 (forward-word (prefix-numeric-value arg
))
7055 (defun kill-word (arg)
7056 "Kill characters forward until encountering the end of a word.
7057 With argument ARG, do this that many times."
7059 (kill-region (point) (progn (forward-word arg
) (point))))
7061 (defun backward-kill-word (arg)
7062 "Kill characters backward until encountering the beginning of a word.
7063 With argument ARG, do this that many times."
7065 (kill-word (- arg
)))
7067 (defun current-word (&optional strict really-word
)
7068 "Return the word at or near point, as a string.
7069 The return value includes no text properties.
7071 If optional arg STRICT is non-nil, return nil unless point is
7072 within or adjacent to a word, otherwise look for a word within
7073 point's line. If there is no word anywhere on point's line, the
7074 value is nil regardless of STRICT.
7076 By default, this function treats as a single word any sequence of
7077 characters that have either word or symbol syntax. If optional
7078 arg REALLY-WORD is non-nil, only characters of word syntax can
7081 (let* ((oldpoint (point)) (start (point)) (end (point))
7082 (syntaxes (if really-word
"w" "w_"))
7083 (not-syntaxes (concat "^" syntaxes
)))
7084 (skip-syntax-backward syntaxes
) (setq start
(point))
7085 (goto-char oldpoint
)
7086 (skip-syntax-forward syntaxes
) (setq end
(point))
7087 (when (and (eq start oldpoint
) (eq end oldpoint
)
7088 ;; Point is neither within nor adjacent to a word.
7090 ;; Look for preceding word in same line.
7091 (skip-syntax-backward not-syntaxes
(line-beginning-position))
7093 ;; No preceding word in same line.
7094 ;; Look for following word in same line.
7096 (skip-syntax-forward not-syntaxes
(line-end-position))
7097 (setq start
(point))
7098 (skip-syntax-forward syntaxes
)
7101 (skip-syntax-backward syntaxes
)
7102 (setq start
(point))))
7103 ;; If we found something nonempty, return it as a string.
7104 (unless (= start end
)
7105 (buffer-substring-no-properties start end
)))))
7107 (defcustom fill-prefix nil
7108 "String for filling to insert at front of new line, or nil for none."
7109 :type
'(choice (const :tag
"None" nil
)
7112 (make-variable-buffer-local 'fill-prefix
)
7113 (put 'fill-prefix
'safe-local-variable
'string-or-null-p
)
7115 (defcustom auto-fill-inhibit-regexp nil
7116 "Regexp to match lines which should not be auto-filled."
7117 :type
'(choice (const :tag
"None" nil
)
7121 (defun do-auto-fill ()
7122 "The default value for `normal-auto-fill-function'.
7123 This is the default auto-fill function, some major modes use a different one.
7124 Returns t if it really did any work."
7125 (let (fc justify give-up
7126 (fill-prefix fill-prefix
))
7127 (if (or (not (setq justify
(current-justification)))
7128 (null (setq fc
(current-fill-column)))
7129 (and (eq justify
'left
)
7130 (<= (current-column) fc
))
7131 (and auto-fill-inhibit-regexp
7132 (save-excursion (beginning-of-line)
7133 (looking-at auto-fill-inhibit-regexp
))))
7134 nil
;; Auto-filling not required
7135 (if (memq justify
'(full center right
))
7136 (save-excursion (unjustify-current-line)))
7138 ;; Choose a fill-prefix automatically.
7139 (when (and adaptive-fill-mode
7140 (or (null fill-prefix
) (string= fill-prefix
"")))
7142 (fill-context-prefix
7143 (save-excursion (fill-forward-paragraph -
1) (point))
7144 (save-excursion (fill-forward-paragraph 1) (point)))))
7145 (and prefix
(not (equal prefix
""))
7146 ;; Use auto-indentation rather than a guessed empty prefix.
7147 (not (and fill-indent-according-to-mode
7148 (string-match "\\`[ \t]*\\'" prefix
)))
7149 (setq fill-prefix prefix
))))
7151 (while (and (not give-up
) (> (current-column) fc
))
7152 ;; Determine where to split the line.
7156 ;; Don't split earlier in the line than the length of the
7157 ;; fill prefix, since the resulting line would be longer.
7159 (move-to-column (string-width fill-prefix
)))
7160 (let ((after-prefix (point)))
7161 (move-to-column (1+ fc
))
7162 (fill-move-to-break-point after-prefix
)
7165 ;; See whether the place we found is any good.
7167 (goto-char fill-point
)
7169 ;; There is no use breaking at end of line.
7170 (save-excursion (skip-chars-forward " ") (eolp))
7171 ;; Don't split right after a comment starter
7172 ;; since we would just make another comment starter.
7173 (and comment-start-skip
7174 (let ((limit (point)))
7176 (and (re-search-forward comment-start-skip
7178 (eq (point) limit
))))))
7179 ;; No good place to break => stop trying.
7181 ;; Ok, we have a useful place to break the line. Do it.
7182 (let ((prev-column (current-column)))
7183 ;; If point is at the fill-point, do not `save-excursion'.
7184 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7185 ;; point will end up before it rather than after it.
7187 (skip-chars-backward " \t")
7188 (= (point) fill-point
))
7189 (default-indent-new-line t
)
7191 (goto-char fill-point
)
7192 (default-indent-new-line t
)))
7193 ;; Now do justification, if required
7194 (if (not (eq justify
'left
))
7197 (justify-current-line justify nil t
)))
7198 ;; If making the new line didn't reduce the hpos of
7199 ;; the end of the line, then give up now;
7200 ;; trying again will not help.
7201 (if (>= (current-column) prev-column
)
7202 (setq give-up t
))))))
7203 ;; Justify last line.
7204 (justify-current-line justify t t
)
7207 (defvar comment-line-break-function
'comment-indent-new-line
7208 "Mode-specific function which line breaks and continues a comment.
7209 This function is called during auto-filling when a comment syntax
7211 The function should take a single optional argument, which is a flag
7212 indicating whether it should use soft newlines.")
7214 (defun default-indent-new-line (&optional soft
)
7215 "Break line at point and indent.
7216 If a comment syntax is defined, call `comment-indent-new-line'.
7218 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7219 unless optional argument SOFT is non-nil."
7222 (funcall comment-line-break-function soft
)
7223 ;; Insert the newline before removing empty space so that markers
7224 ;; get preserved better.
7225 (if soft
(insert-and-inherit ?
\n) (newline 1))
7226 (save-excursion (forward-char -
1) (delete-horizontal-space))
7227 (delete-horizontal-space)
7229 (if (and fill-prefix
(not adaptive-fill-mode
))
7230 ;; Blindly trust a non-adaptive fill-prefix.
7232 (indent-to-left-margin)
7233 (insert-before-markers-and-inherit fill-prefix
))
7236 ;; If there's an adaptive prefix, use it unless we're inside
7237 ;; a comment and the prefix is not a comment starter.
7239 (indent-to-left-margin)
7240 (insert-and-inherit fill-prefix
))
7241 ;; If we're not inside a comment, just try to indent.
7242 (t (indent-according-to-mode))))))
7244 (defun internal-auto-fill ()
7245 "The function called by `self-insert-command' to perform auto-filling."
7246 (when (or (not comment-start
)
7247 (not comment-auto-fill-only-comments
)
7248 (nth 4 (syntax-ppss)))
7249 (funcall auto-fill-function
)))
7251 (defvar normal-auto-fill-function
'do-auto-fill
7252 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7253 Some major modes set this.")
7255 (put 'auto-fill-function
:minor-mode-function
'auto-fill-mode
)
7256 ;; `functions' and `hooks' are usually unsafe to set, but setting
7257 ;; auto-fill-function to nil in a file-local setting is safe and
7258 ;; can be useful to prevent auto-filling.
7259 (put 'auto-fill-function
'safe-local-variable
'null
)
7261 (define-minor-mode auto-fill-mode
7262 "Toggle automatic line breaking (Auto Fill mode).
7263 Interactively, with a prefix argument, enable
7264 Auto Fill mode if the prefix argument is positive,
7265 and disable it otherwise. If called from Lisp, toggle
7266 the mode if ARG is `toggle', disable the mode if ARG is
7267 a non-positive integer, and enable the mode otherwise
7268 \(including if ARG is omitted or nil or a positive integer).
7270 When Auto Fill mode is enabled, inserting a space at a column
7271 beyond `current-fill-column' automatically breaks the line at a
7274 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7277 The value of `normal-auto-fill-function' specifies the function to use
7278 for `auto-fill-function' when turning Auto Fill mode on."
7279 :variable
(auto-fill-function
7280 .
(lambda (v) (setq auto-fill-function
7281 (if v normal-auto-fill-function
)))))
7283 ;; This holds a document string used to document auto-fill-mode.
7284 (defun auto-fill-function ()
7285 "Automatically break line at a previous space, in insertion of text."
7288 (defun turn-on-auto-fill ()
7289 "Unconditionally turn on Auto Fill mode."
7292 (defun turn-off-auto-fill ()
7293 "Unconditionally turn off Auto Fill mode."
7294 (auto-fill-mode -
1))
7296 (custom-add-option 'text-mode-hook
'turn-on-auto-fill
)
7298 (defun set-fill-column (arg)
7299 "Set `fill-column' to specified argument.
7300 Use \\[universal-argument] followed by a number to specify a column.
7301 Just \\[universal-argument] as argument means to use the current column."
7303 (list (or current-prefix-arg
7304 ;; We used to use current-column silently, but C-x f is too easily
7305 ;; typed as a typo for C-x C-f, so we turned it into an error and
7306 ;; now an interactive prompt.
7307 (read-number "Set fill-column to: " (current-column)))))
7309 (setq arg
(current-column)))
7310 (if (not (integerp arg
))
7311 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7312 (error "set-fill-column requires an explicit argument")
7313 (message "Fill column set to %d (was %d)" arg fill-column
)
7314 (setq fill-column arg
)))
7316 (defun set-selective-display (arg)
7317 "Set `selective-display' to ARG; clear it if no arg.
7318 When the value of `selective-display' is a number > 0,
7319 lines whose indentation is >= that value are not displayed.
7320 The variable `selective-display' has a separate value for each buffer."
7322 (if (eq selective-display t
)
7323 (error "selective-display already in use for marked lines"))
7326 (narrow-to-region (point-min) (point))
7327 (goto-char (window-start))
7328 (vertical-motion (window-height)))))
7329 (setq selective-display
7330 (and arg
(prefix-numeric-value arg
)))
7331 (recenter current-vpos
))
7332 (set-window-start (selected-window) (window-start))
7333 (princ "selective-display set to " t
)
7334 (prin1 selective-display t
)
7337 (defvaralias 'indicate-unused-lines
'indicate-empty-lines
)
7339 (defun toggle-truncate-lines (&optional arg
)
7340 "Toggle truncating of long lines for the current buffer.
7341 When truncating is off, long lines are folded.
7342 With prefix argument ARG, truncate long lines if ARG is positive,
7343 otherwise fold them. Note that in side-by-side windows, this
7344 command has no effect if `truncate-partial-width-windows' is
7347 (setq truncate-lines
7349 (not truncate-lines
)
7350 (> (prefix-numeric-value arg
) 0)))
7351 (force-mode-line-update)
7352 (unless truncate-lines
7353 (let ((buffer (current-buffer)))
7354 (walk-windows (lambda (window)
7355 (if (eq buffer
(window-buffer window
))
7356 (set-window-hscroll window
0)))
7358 (message "Truncate long lines %s"
7359 (if truncate-lines
"enabled" "disabled")))
7361 (defun toggle-word-wrap (&optional arg
)
7362 "Toggle whether to use word-wrapping for continuation lines.
7363 With prefix argument ARG, wrap continuation lines at word boundaries
7364 if ARG is positive, otherwise wrap them at the right screen edge.
7365 This command toggles the value of `word-wrap'. It has no effect
7366 if long lines are truncated."
7371 (> (prefix-numeric-value arg
) 0)))
7372 (force-mode-line-update)
7373 (message "Word wrapping %s"
7374 (if word-wrap
"enabled" "disabled")))
7376 (defvar overwrite-mode-textual
(purecopy " Ovwrt")
7377 "The string displayed in the mode line when in overwrite mode.")
7378 (defvar overwrite-mode-binary
(purecopy " Bin Ovwrt")
7379 "The string displayed in the mode line when in binary overwrite mode.")
7381 (define-minor-mode overwrite-mode
7382 "Toggle Overwrite mode.
7383 With a prefix argument ARG, enable Overwrite mode if ARG is
7384 positive, and disable it otherwise. If called from Lisp, enable
7385 the mode if ARG is omitted or nil.
7387 When Overwrite mode is enabled, printing characters typed in
7388 replace existing text on a one-for-one basis, rather than pushing
7389 it to the right. At the end of a line, such characters extend
7390 the line. Before a tab, such characters insert until the tab is
7391 filled in. \\[quoted-insert] still inserts characters in
7392 overwrite mode; this is supposed to make it easier to insert
7393 characters when necessary."
7394 :variable
(overwrite-mode
7395 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-textual
)))))
7397 (define-minor-mode binary-overwrite-mode
7398 "Toggle Binary Overwrite mode.
7399 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7400 is positive, and disable it otherwise. If called from Lisp,
7401 enable the mode if ARG is omitted or nil.
7403 When Binary Overwrite mode is enabled, printing characters typed
7404 in replace existing text. Newlines are not treated specially, so
7405 typing at the end of a line joins the line to the next, with the
7406 typed character between them. Typing before a tab character
7407 simply replaces the tab with the character typed.
7408 \\[quoted-insert] replaces the text at the cursor, just as
7409 ordinary typing characters do.
7411 Note that Binary Overwrite mode is not its own minor mode; it is
7412 a specialization of overwrite mode, entered by setting the
7413 `overwrite-mode' variable to `overwrite-mode-binary'."
7414 :variable
(overwrite-mode
7415 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-binary
)))))
7417 (define-minor-mode line-number-mode
7418 "Toggle line number display in the mode line (Line Number mode).
7419 With a prefix argument ARG, enable Line Number mode if ARG is
7420 positive, and disable it otherwise. If called from Lisp, enable
7421 the mode if ARG is omitted or nil.
7423 Line numbers do not appear for very large buffers and buffers
7424 with very long lines; see variables `line-number-display-limit'
7425 and `line-number-display-limit-width'."
7426 :init-value t
:global t
:group
'mode-line
)
7428 (define-minor-mode column-number-mode
7429 "Toggle column number display in the mode line (Column Number mode).
7430 With a prefix argument ARG, enable Column Number mode if ARG is
7431 positive, and disable it otherwise.
7433 If called from Lisp, enable the mode if ARG is omitted or nil."
7434 :global t
:group
'mode-line
)
7436 (define-minor-mode size-indication-mode
7437 "Toggle buffer size display in the mode line (Size Indication mode).
7438 With a prefix argument ARG, enable Size Indication mode if ARG is
7439 positive, and disable it otherwise.
7441 If called from Lisp, enable the mode if ARG is omitted or nil."
7442 :global t
:group
'mode-line
)
7444 (define-minor-mode auto-save-mode
7445 "Toggle auto-saving in the current buffer (Auto Save mode).
7446 With a prefix argument ARG, enable Auto Save mode if ARG is
7447 positive, and disable it otherwise.
7449 If called from Lisp, enable the mode if ARG is omitted or nil."
7450 :variable
((and buffer-auto-save-file-name
7451 ;; If auto-save is off because buffer has shrunk,
7452 ;; then toggling should turn it on.
7453 (>= buffer-saved-size
0))
7455 (setq buffer-auto-save-file-name
7458 ((and buffer-file-name auto-save-visited-file-name
7459 (not buffer-read-only
))
7461 (t (make-auto-save-file-name))))))
7462 ;; If -1 was stored here, to temporarily turn off saving,
7464 (and (< buffer-saved-size
0)
7465 (setq buffer-saved-size
0)))
7467 (defgroup paren-blinking nil
7468 "Blinking matching of parens and expressions."
7469 :prefix
"blink-matching-"
7470 :group
'paren-matching
)
7472 (defcustom blink-matching-paren t
7473 "Non-nil means show matching open-paren when close-paren is inserted.
7474 If t, highlight the paren. If `jump', briefly move cursor to its
7475 position. If `jump-offscreen', move cursor there even if the
7476 position is off screen. With any other non-nil value, the
7477 off-screen position of the opening paren will be shown in the
7480 (const :tag
"Disable" nil
)
7481 (const :tag
"Highlight" t
)
7482 (const :tag
"Move cursor" jump
)
7483 (const :tag
"Move cursor, even if off screen" jump-offscreen
))
7484 :group
'paren-blinking
)
7486 (defcustom blink-matching-paren-on-screen t
7487 "Non-nil means show matching open-paren when it is on screen.
7488 If nil, don't show it (but the open-paren can still be shown
7489 in the echo area when it is off screen).
7491 This variable has no effect if `blink-matching-paren' is nil.
7492 \(In that case, the open-paren is never shown.)
7493 It is also ignored if `show-paren-mode' is enabled."
7495 :group
'paren-blinking
)
7497 (defcustom blink-matching-paren-distance
(* 100 1024)
7498 "If non-nil, maximum distance to search backwards for matching open-paren.
7499 If nil, search stops at the beginning of the accessible portion of the buffer."
7500 :version
"23.2" ; 25->100k
7501 :type
'(choice (const nil
) integer
)
7502 :group
'paren-blinking
)
7504 (defcustom blink-matching-delay
1
7505 "Time in seconds to delay after showing a matching paren."
7507 :group
'paren-blinking
)
7509 (defcustom blink-matching-paren-dont-ignore-comments nil
7510 "If nil, `blink-matching-paren' ignores comments.
7511 More precisely, when looking for the matching parenthesis,
7512 it skips the contents of comments that end before point."
7514 :group
'paren-blinking
)
7516 (defun blink-matching-check-mismatch (start end
)
7517 "Return whether or not START...END are matching parens.
7518 END is the current point and START is the blink position.
7519 START might be nil if no matching starter was found.
7520 Returns non-nil if we find there is a mismatch."
7521 (let* ((end-syntax (syntax-after (1- end
)))
7522 (matching-paren (and (consp end-syntax
)
7523 (eq (syntax-class end-syntax
) 5)
7525 ;; For self-matched chars like " and $, we can't know when they're
7526 ;; mismatched or unmatched, so we can only do it for parens.
7527 (when matching-paren
7530 (eq (char-after start
) matching-paren
)
7531 ;; The cdr might hold a new paren-class info rather than
7532 ;; a matching-char info, in which case the two CDRs
7534 (eq matching-paren
(cdr-safe (syntax-after start
)))))))))
7536 (defvar blink-matching-check-function
#'blink-matching-check-mismatch
7537 "Function to check parentheses mismatches.
7538 The function takes two arguments (START and END) where START is the
7539 position just before the opening token and END is the position right after.
7540 START can be nil, if it was not found.
7541 The function should return non-nil if the two tokens do not match.")
7543 (defvar blink-matching--overlay
7544 (let ((ol (make-overlay (point) (point) nil t
)))
7545 (overlay-put ol
'face
'show-paren-match
)
7548 "Overlay used to highlight the matching paren.")
7550 (defun blink-matching-open ()
7551 "Momentarily highlight the beginning of the sexp before point."
7553 (when (and (not (bobp))
7554 blink-matching-paren
)
7555 (let* ((oldpos (point))
7556 (message-log-max nil
) ; Don't log messages about paren matching.
7560 (if blink-matching-paren-distance
7562 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7563 (- (point) blink-matching-paren-distance
))
7565 (let ((parse-sexp-ignore-comments
7566 (and parse-sexp-ignore-comments
7567 (not blink-matching-paren-dont-ignore-comments
))))
7570 (syntax-propertize (point))
7572 ;; backward-sexp skips backward over prefix chars,
7573 ;; so move back to the matching paren.
7574 (while (and (< (point) (1- oldpos
))
7575 (let ((code (syntax-after (point))))
7576 (or (eq (syntax-class code
) 6)
7577 (eq (logand 1048576 (car code
))
7582 (mismatch (funcall blink-matching-check-function blinkpos oldpos
)))
7587 (minibuffer-message "Mismatched parentheses")
7588 (message "Mismatched parentheses"))
7590 (minibuffer-message "No matching parenthesis found")
7591 (message "No matching parenthesis found"))))
7592 ((not blinkpos
) nil
)
7594 (eq blink-matching-paren
'jump-offscreen
)
7595 (pos-visible-in-window-p blinkpos
))
7596 ;; Matching open within window, temporarily move to or highlight
7597 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7599 (and blink-matching-paren-on-screen
7600 (not show-paren-mode
)
7601 (if (memq blink-matching-paren
'(jump jump-offscreen
))
7603 (goto-char blinkpos
)
7604 (sit-for blink-matching-delay
))
7607 (move-overlay blink-matching--overlay blinkpos
(1+ blinkpos
)
7609 (sit-for blink-matching-delay
))
7610 (delete-overlay blink-matching--overlay
)))))
7612 (let ((open-paren-line-string
7614 (goto-char blinkpos
)
7615 ;; Show what precedes the open in its line, if anything.
7617 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7618 (buffer-substring (line-beginning-position)
7620 ;; Show what follows the open in its line, if anything.
7623 (skip-chars-forward " \t")
7625 (buffer-substring blinkpos
7626 (line-end-position)))
7627 ;; Otherwise show the previous nonblank line,
7629 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7631 (buffer-substring (progn
7632 (skip-chars-backward "\n \t")
7633 (line-beginning-position))
7634 (progn (end-of-line)
7635 (skip-chars-backward " \t")
7637 ;; Replace the newline and other whitespace with `...'.
7639 (buffer-substring blinkpos
(1+ blinkpos
))))
7640 ;; There is nothing to show except the char itself.
7641 (t (buffer-substring blinkpos
(1+ blinkpos
)))))))
7644 (substring-no-properties open-paren-line-string
))))))))
7646 (defvar blink-paren-function
'blink-matching-open
7647 "Function called, if non-nil, whenever a close parenthesis is inserted.
7648 More precisely, a char with closeparen syntax is self-inserted.")
7650 (defun blink-paren-post-self-insert-function ()
7651 (when (and (eq (char-before) last-command-event
) ; Sanity check.
7652 (memq (char-syntax last-command-event
) '(?\
) ?\$
))
7653 blink-paren-function
7654 (not executing-kbd-macro
)
7655 (not noninteractive
)
7656 ;; Verify an even number of quoting characters precede the close.
7657 ;; FIXME: Also check if this parenthesis closes a comment as
7658 ;; can happen in Pascal and SML.
7659 (= 1 (logand 1 (- (point)
7662 (skip-syntax-backward "/\\")
7664 (funcall blink-paren-function
)))
7666 (put 'blink-paren-post-self-insert-function
'priority
100)
7668 (add-hook 'post-self-insert-hook
#'blink-paren-post-self-insert-function
7669 ;; Most likely, this hook is nil, so this arg doesn't matter,
7670 ;; but I use it as a reminder that this function usually
7671 ;; likes to be run after others since it does
7672 ;; `sit-for'. That's also the reason it get a `priority' prop
7676 ;; This executes C-g typed while Emacs is waiting for a command.
7677 ;; Quitting out of a program does not go through here;
7678 ;; that happens in the maybe_quit function at the C code level.
7679 (defun keyboard-quit ()
7680 "Signal a `quit' condition.
7681 During execution of Lisp code, this character causes a quit directly.
7682 At top-level, as an editor command, this simply beeps."
7684 ;; Avoid adding the region to the window selection.
7685 (setq saved-region-selection nil
)
7686 (let (select-active-regions)
7688 (if (fboundp 'kmacro-keyboard-quit
)
7689 (kmacro-keyboard-quit))
7690 (when completion-in-region-mode
7691 (completion-in-region-mode -
1))
7692 ;; Force the next redisplay cycle to remove the "Def" indicator from
7693 ;; all the mode lines.
7694 (if defining-kbd-macro
7695 (force-mode-line-update t
))
7696 (setq defining-kbd-macro nil
)
7697 (let ((debug-on-quit nil
))
7698 (signal 'quit nil
)))
7700 (defvar buffer-quit-function nil
7701 "Function to call to \"quit\" the current buffer, or nil if none.
7702 \\[keyboard-escape-quit] calls this function when its more local actions
7703 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7705 (defun keyboard-escape-quit ()
7706 "Exit the current \"mode\" (in a generalized sense of the word).
7707 This command can exit an interactive command such as `query-replace',
7708 can clear out a prefix argument or a region,
7709 can get out of the minibuffer or other recursive edit,
7710 cancel the use of the current buffer (for special-purpose buffers),
7711 or go back to just one window (by deleting all but the selected window)."
7713 (cond ((eq last-command
'mode-exited
) nil
)
7716 ((> (minibuffer-depth) 0)
7717 (abort-recursive-edit))
7720 ((> (recursion-depth) 0)
7721 (exit-recursive-edit))
7722 (buffer-quit-function
7723 (funcall buffer-quit-function
))
7724 ((not (one-window-p t
))
7725 (delete-other-windows))
7726 ((string-match "^ \\*" (buffer-name (current-buffer)))
7729 (defun play-sound-file (file &optional volume device
)
7730 "Play sound stored in FILE.
7731 VOLUME and DEVICE correspond to the keywords of the sound
7732 specification for `play-sound'."
7733 (interactive "fPlay sound file: ")
7734 (let ((sound (list :file file
)))
7736 (plist-put sound
:volume volume
))
7738 (plist-put sound
:device device
))
7740 (play-sound sound
)))
7743 (defcustom read-mail-command
'rmail
7744 "Your preference for a mail reading package.
7745 This is used by some keybindings which support reading mail.
7746 See also `mail-user-agent' concerning sending mail."
7747 :type
'(radio (function-item :tag
"Rmail" :format
"%t\n" rmail
)
7748 (function-item :tag
"Gnus" :format
"%t\n" gnus
)
7749 (function-item :tag
"Emacs interface to MH"
7750 :format
"%t\n" mh-rmail
)
7751 (function :tag
"Other"))
7755 (defcustom mail-user-agent
'message-user-agent
7756 "Your preference for a mail composition package.
7757 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7758 outgoing email message. This variable lets you specify which
7759 mail-sending package you prefer.
7761 Valid values include:
7763 `message-user-agent' -- use the Message package.
7764 See Info node `(message)'.
7765 `sendmail-user-agent' -- use the Mail package.
7766 See Info node `(emacs)Sending Mail'.
7767 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7768 See Info node `(mh-e)'.
7769 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7770 paraphernalia if Gnus is running, particularly
7771 the Gcc: header for archiving.
7773 Additional valid symbols may be available; check with the author of
7774 your package for details. The function should return non-nil if it
7777 See also `read-mail-command' concerning reading mail."
7778 :type
'(radio (function-item :tag
"Message package"
7781 (function-item :tag
"Mail package"
7783 sendmail-user-agent
)
7784 (function-item :tag
"Emacs interface to MH"
7787 (function-item :tag
"Message with full Gnus features"
7790 (function :tag
"Other"))
7791 :version
"23.2" ; sendmail->message
7794 (defcustom compose-mail-user-agent-warnings t
7795 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7796 If the value of `mail-user-agent' is the default, and the user
7797 appears to have customizations applying to the old default,
7798 `compose-mail' issues a warning."
7803 (defun rfc822-goto-eoh ()
7804 "If the buffer starts with a mail header, move point to the header's end.
7805 Otherwise, moves to `point-min'.
7806 The end of the header is the start of the next line, if there is one,
7807 else the end of the last line. This function obeys RFC822."
7808 (goto-char (point-min))
7809 (when (re-search-forward
7810 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil
'move
)
7811 (goto-char (match-beginning 0))))
7813 ;; Used by Rmail (e.g., rmail-forward).
7814 (defvar mail-encode-mml nil
7815 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7816 the outgoing message before sending it.")
7818 (defun compose-mail (&optional to subject other-headers continue
7819 switch-function yank-action send-actions
7821 "Start composing a mail message to send.
7822 This uses the user's chosen mail composition package
7823 as selected with the variable `mail-user-agent'.
7824 The optional arguments TO and SUBJECT specify recipients
7825 and the initial Subject field, respectively.
7827 OTHER-HEADERS is an alist specifying additional
7828 header fields. Elements look like (HEADER . VALUE) where both
7829 HEADER and VALUE are strings.
7831 CONTINUE, if non-nil, says to continue editing a message already
7832 being composed. Interactively, CONTINUE is the prefix argument.
7834 SWITCH-FUNCTION, if non-nil, is a function to use to
7835 switch to and display the buffer used for mail composition.
7837 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7838 to insert the raw text of the message being replied to.
7839 It has the form (FUNCTION . ARGS). The user agent will apply
7840 FUNCTION to ARGS, to insert the raw text of the original message.
7841 \(The user agent will also run `mail-citation-hook', *after* the
7842 original text has been inserted in this way.)
7844 SEND-ACTIONS is a list of actions to call when the message is sent.
7845 Each action has the form (FUNCTION . ARGS).
7847 RETURN-ACTION, if non-nil, is an action for returning to the
7848 caller. It has the form (FUNCTION . ARGS). The function is
7849 called after the mail has been sent or put aside, and the mail
7852 (list nil nil nil current-prefix-arg
))
7854 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7855 ;; from sendmail-user-agent to message-user-agent. Some users may
7856 ;; encounter incompatibilities. This hack tries to detect problems
7857 ;; and warn about them.
7858 (and compose-mail-user-agent-warnings
7859 (eq mail-user-agent
'message-user-agent
)
7861 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7862 mail-yank-hooks mail-archive-file-name
7863 mail-default-reply-to mail-mailing-lists
7867 (push var warn-vars
)))
7869 (display-warning 'mail
7871 The default mail mode is now Message mode.
7872 You have the following Mail mode variable%s customized:
7873 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7874 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7875 (if (> (length warn-vars
) 1) "s" "")
7876 (mapconcat 'symbol-name
7879 (let ((function (get mail-user-agent
'composefunc
)))
7880 (funcall function to subject other-headers continue switch-function
7881 yank-action send-actions return-action
)))
7883 (defun compose-mail-other-window (&optional to subject other-headers continue
7884 yank-action send-actions
7886 "Like \\[compose-mail], but edit the outgoing message in another window."
7887 (interactive (list nil nil nil current-prefix-arg
))
7888 (compose-mail to subject other-headers continue
7889 'switch-to-buffer-other-window yank-action send-actions
7892 (defun compose-mail-other-frame (&optional to subject other-headers continue
7893 yank-action send-actions
7895 "Like \\[compose-mail], but edit the outgoing message in another frame."
7896 (interactive (list nil nil nil current-prefix-arg
))
7897 (compose-mail to subject other-headers continue
7898 'switch-to-buffer-other-frame yank-action send-actions
7902 (defvar set-variable-value-history nil
7903 "History of values entered with `set-variable'.
7905 Maximum length of the history list is determined by the value
7906 of `history-length', which see.")
7908 (defun set-variable (variable value
&optional make-local
)
7909 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7910 VARIABLE should be a user option variable name, a Lisp variable
7911 meant to be customized by users. You should enter VALUE in Lisp syntax,
7912 so if you want VALUE to be a string, you must surround it with doublequotes.
7913 VALUE is used literally, not evaluated.
7915 If VARIABLE has a `variable-interactive' property, that is used as if
7916 it were the arg to `interactive' (which see) to interactively read VALUE.
7918 If VARIABLE has been defined with `defcustom', then the type information
7919 in the definition is used to check that VALUE is valid.
7921 Note that this function is at heart equivalent to the basic `set' function.
7922 For a variable defined with `defcustom', it does not pay attention to
7923 any :set property that the variable might have (if you want that, use
7924 \\[customize-set-variable] instead).
7926 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7928 (let* ((default-var (variable-at-point))
7929 (var (if (custom-variable-p default-var
)
7930 (read-variable (format "Set variable (default %s): " default-var
)
7932 (read-variable "Set variable: ")))
7933 (minibuffer-help-form '(describe-variable var
))
7934 (prop (get var
'variable-interactive
))
7935 (obsolete (car (get var
'byte-obsolete-variable
)))
7936 (prompt (format "Set %s %s to value: " var
7937 (cond ((local-variable-p var
)
7939 ((or current-prefix-arg
7940 (local-variable-if-set-p var
))
7945 (message (concat "`%S' is obsolete; "
7946 (if (symbolp obsolete
) "use `%S' instead" "%s"))
7950 ;; Use VAR's `variable-interactive' property
7951 ;; as an interactive spec for prompting.
7952 (call-interactively `(lambda (arg)
7955 (read-from-minibuffer prompt nil
7956 read-expression-map t
7957 'set-variable-value-history
7958 (format "%S" (symbol-value var
)))))))
7959 (list var val current-prefix-arg
)))
7961 (and (custom-variable-p variable
)
7962 (not (get variable
'custom-type
))
7963 (custom-load-symbol variable
))
7964 (let ((type (get variable
'custom-type
)))
7966 ;; Match with custom type.
7968 (setq type
(widget-convert type
))
7969 (unless (widget-apply type
:match value
)
7970 (user-error "Value `%S' does not match type %S of %S"
7971 value
(car type
) variable
))))
7974 (make-local-variable variable
))
7976 (set variable value
)
7978 ;; Force a thorough redisplay for the case that the variable
7979 ;; has an effect on the display, like `tab-width' has.
7980 (force-mode-line-update))
7982 ;; Define the major mode for lists of completions.
7984 (defvar completion-list-mode-map
7985 (let ((map (make-sparse-keymap)))
7986 (define-key map
[mouse-2
] 'choose-completion
)
7987 (define-key map
[follow-link
] 'mouse-face
)
7988 (define-key map
[down-mouse-2
] nil
)
7989 (define-key map
"\C-m" 'choose-completion
)
7990 (define-key map
"\e\e\e" 'delete-completion-window
)
7991 (define-key map
[left] 'previous-completion)
7992 (define-key map [right] 'next-completion)
7993 (define-key map [?\t] 'next-completion)
7994 (define-key map [backtab] 'previous-completion)
7995 (define-key map "q" 'quit-window)
7996 (define-key map "z" 'kill-current-buffer)
7998 "Local map for completion list buffers.")
8000 ;; Completion mode is suitable only for specially formatted data.
8001 (put 'completion-list-mode 'mode-class 'special)
8003 (defvar completion-reference-buffer nil
8004 "Record the buffer that was current when the completion list was requested.
8005 This is a local variable in the completion list buffer.
8006 Initial value is nil to avoid some compiler warnings.")
8008 (defvar completion-no-auto-exit nil
8009 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8010 This also applies to other functions such as `choose-completion'.")
8012 (defvar completion-base-position nil
8013 "Position of the base of the text corresponding to the shown completions.
8014 This variable is used in the *Completions* buffers.
8015 Its value is a list of the form (START END) where START is the place
8016 where the completion should be inserted and END (if non-nil) is the end
8017 of the text to replace. If END is nil, point is used instead.")
8019 (defvar completion-list-insert-choice-function #'completion--replace
8020 "Function to use to insert the text chosen in *Completions*.
8021 Called with three arguments (BEG END TEXT), it should replace the text
8022 between BEG and END with TEXT. Expected to be set buffer-locally
8023 in the *Completions* buffer.")
8025 (defvar completion-base-size nil
8026 "Number of chars before point not involved in completion.
8027 This is a local variable in the completion list buffer.
8028 It refers to the chars in the minibuffer if completing in the
8029 minibuffer, or in `completion-reference-buffer' otherwise.
8030 Only characters in the field at point are included.
8032 If nil, Emacs determines which part of the tail end of the
8033 buffer's text is involved in completion by comparing the text
8035 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8037 (defun delete-completion-window ()
8038 "Delete the completion list window.
8039 Go to the window from which completion was requested."
8041 (let ((buf completion-reference-buffer))
8042 (if (one-window-p t)
8043 (if (window-dedicated-p) (delete-frame))
8044 (delete-window (selected-window))
8045 (if (get-buffer-window buf)
8046 (select-window (get-buffer-window buf))))))
8048 (defun previous-completion (n)
8049 "Move to the previous item in the completion list."
8051 (next-completion (- n)))
8053 (defun next-completion (n)
8054 "Move to the next item in the completion list.
8055 With prefix argument N, move N items (negative N means move backward)."
8057 (let ((beg (point-min)) (end (point-max)))
8058 (while (and (> n 0) (not (eobp)))
8059 ;; If in a completion, move to the end of it.
8060 (when (get-text-property (point) 'mouse-face)
8061 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8062 ;; Move to start of next one.
8063 (unless (get-text-property (point) 'mouse-face)
8064 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8066 (while (and (< n 0) (not (bobp)))
8067 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8068 ;; If in a completion, move to the start of it.
8069 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8070 (goto-char (previous-single-property-change
8071 (point) 'mouse-face nil beg)))
8072 ;; Move to end of the previous completion.
8073 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8074 (goto-char (previous-single-property-change
8075 (point) 'mouse-face nil beg)))
8076 ;; Move to the start of that one.
8077 (goto-char (previous-single-property-change
8078 (point) 'mouse-face nil beg))
8081 (defun choose-completion (&optional event)
8082 "Choose the completion at point.
8083 If EVENT, use EVENT's position to determine the starting position."
8084 (interactive (list last-nonmenu-event))
8085 ;; In case this is run via the mouse, give temporary modes such as
8086 ;; isearch a chance to turn off.
8087 (run-hooks 'mouse-leave-buffer-hook)
8088 (with-current-buffer (window-buffer (posn-window (event-start event)))
8089 (let ((buffer completion-reference-buffer)
8090 (base-size completion-base-size)
8091 (base-position completion-base-position)
8092 (insert-function completion-list-insert-choice-function)
8095 (goto-char (posn-point (event-start event)))
8098 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8099 (setq end (point) beg (1+ (point))))
8101 (get-text-property (1- (point)) 'mouse-face))
8102 (setq end (1- (point)) beg (point)))
8103 (t (error "No completion here")))
8104 (setq beg (previous-single-property-change beg 'mouse-face))
8105 (setq end (or (next-single-property-change end 'mouse-face)
8107 (buffer-substring-no-properties beg end)))))
8109 (unless (buffer-live-p buffer)
8110 (error "Destination buffer is dead"))
8111 (quit-window nil (posn-window (event-start event)))
8113 (with-current-buffer buffer
8114 (choose-completion-string
8118 ;; Someone's using old completion code that doesn't know
8119 ;; about base-position yet.
8120 (list (+ base-size (field-beginning))))
8121 ;; If all else fails, just guess.
8122 (list (choose-completion-guess-base-position choice)))
8123 insert-function)))))
8125 ;; Delete the longest partial match for STRING
8126 ;; that can be found before POINT.
8127 (defun choose-completion-guess-base-position (string)
8129 (let ((opoint (point))
8131 ;; Try moving back by the length of the string.
8132 (goto-char (max (- (point) (length string))
8133 (minibuffer-prompt-end)))
8134 ;; See how far back we were actually able to move. That is the
8135 ;; upper bound on how much we can match and delete.
8136 (setq len (- opoint (point)))
8137 (if completion-ignore-case
8138 (setq string (downcase string)))
8139 (while (and (> len 0)
8140 (let ((tail (buffer-substring (point) opoint)))
8141 (if completion-ignore-case
8142 (setq tail (downcase tail)))
8143 (not (string= tail (substring string 0 len)))))
8148 (defun choose-completion-delete-max-match (string)
8149 (declare (obsolete choose-completion-guess-base-position "23.2"))
8150 (delete-region (choose-completion-guess-base-position string) (point)))
8152 (defvar choose-completion-string-functions nil
8153 "Functions that may override the normal insertion of a completion choice.
8154 These functions are called in order with three arguments:
8155 CHOICE - the string to insert in the buffer,
8156 BUFFER - the buffer in which the choice should be inserted,
8157 BASE-POSITION - where to insert the completion.
8159 If a function in the list returns non-nil, that function is supposed
8160 to have inserted the CHOICE in the BUFFER, and possibly exited
8161 the minibuffer; no further functions will be called.
8163 If all functions in the list return nil, that means to use
8164 the default method of inserting the completion in BUFFER.")
8166 (defun choose-completion-string (choice &optional
8167 buffer base-position insert-function)
8168 "Switch to BUFFER and insert the completion choice CHOICE.
8169 BASE-POSITION says where to insert the completion.
8170 INSERT-FUNCTION says how to insert the completion and falls
8171 back on `completion-list-insert-choice-function' when nil."
8173 ;; If BUFFER is the minibuffer, exit the minibuffer
8174 ;; unless it is reading a file name and CHOICE is a directory,
8175 ;; or completion-no-auto-exit is non-nil.
8177 ;; Some older code may call us passing `base-size' instead of
8178 ;; `base-position'. It's difficult to make any use of `base-size',
8179 ;; so we just ignore it.
8180 (unless (consp base-position)
8181 (message "Obsolete `base-size' passed to choose-completion-string")
8182 (setq base-position nil))
8184 (let* ((buffer (or buffer completion-reference-buffer))
8185 (mini-p (minibufferp buffer)))
8186 ;; If BUFFER is a minibuffer, barf unless it's the currently
8187 ;; active minibuffer.
8189 (not (and (active-minibuffer-window)
8191 (window-buffer (active-minibuffer-window))))))
8192 (error "Minibuffer is not active for completion")
8193 ;; Set buffer so buffer-local choose-completion-string-functions works.
8195 (unless (run-hook-with-args-until-success
8196 'choose-completion-string-functions
8197 ;; The fourth arg used to be `mini-p' but was useless
8198 ;; (since minibufferp can be used on the `buffer' arg)
8199 ;; and indeed unused. The last used to be `base-size', so we
8200 ;; keep it to try and avoid breaking old code.
8201 choice buffer base-position nil)
8202 ;; This remove-text-properties should be unnecessary since `choice'
8203 ;; comes from buffer-substring-no-properties.
8204 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8205 ;; Insert the completion into the buffer where it was requested.
8206 (funcall (or insert-function completion-list-insert-choice-function)
8207 (or (car base-position) (point))
8208 (or (cadr base-position) (point))
8210 ;; Update point in the window that BUFFER is showing in.
8211 (let ((window (get-buffer-window buffer t)))
8212 (set-window-point window (point)))
8213 ;; If completing for the minibuffer, exit it with this choice.
8214 (and (not completion-no-auto-exit)
8215 (minibufferp buffer)
8216 minibuffer-completion-table
8217 ;; If this is reading a file name, and the file name chosen
8218 ;; is a directory, don't exit the minibuffer.
8219 (let* ((result (buffer-substring (field-beginning) (point)))
8221 (completion-boundaries result minibuffer-completion-table
8222 minibuffer-completion-predicate
8224 (if (eq (car bounds) (length result))
8225 ;; The completion chosen leads to a new set of completions
8226 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8227 (let ((mini (active-minibuffer-window)))
8228 (select-window mini)
8229 (when minibuffer-auto-raise
8230 (raise-frame (window-frame mini))))
8231 (exit-minibuffer))))))))
8233 (define-derived-mode completion-list-mode nil "Completion List"
8234 "Major mode for buffers showing lists of possible completions.
8235 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8236 to select the completion near point.
8237 Or click to select one with the mouse.
8239 \\{completion-list-mode-map}"
8240 (set (make-local-variable 'completion-base-size) nil))
8242 (defun completion-list-mode-finish ()
8243 "Finish setup of the completions buffer.
8244 Called from `temp-buffer-show-hook'."
8245 (when (eq major-mode 'completion-list-mode)
8246 (setq buffer-read-only t)))
8248 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8251 ;; Variables and faces used in `completion-setup-function'.
8253 (defcustom completion-show-help t
8254 "Non-nil means show help message in *Completions* buffer."
8259 ;; This function goes in completion-setup-hook, so that it is called
8260 ;; after the text of the completion list buffer is written.
8261 (defun completion-setup-function ()
8262 (let* ((mainbuf (current-buffer))
8264 ;; FIXME: This is a bad hack. We try to set the default-directory
8265 ;; in the *Completions* buffer so that the relative file names
8266 ;; displayed there can be treated as valid file names, independently
8267 ;; from the completion context. But this suffers from many problems:
8268 ;; - It's not clear when the completions are file names. With some
8269 ;; completion tables (e.g. bzr revision specs), the listed
8270 ;; completions can mix file names and other things.
8271 ;; - It doesn't pay attention to possible quoting.
8272 ;; - With fancy completion styles, the code below will not always
8273 ;; find the right base directory.
8274 (if minibuffer-completing-file-name
8275 (file-name-as-directory
8277 (buffer-substring (minibuffer-prompt-end)
8278 (- (point) (or completion-base-size 0))))))))
8279 (with-current-buffer standard-output
8280 (let ((base-size completion-base-size) ;Read before killing localvars.
8281 (base-position completion-base-position)
8282 (insert-fun completion-list-insert-choice-function))
8283 (completion-list-mode)
8284 (set (make-local-variable 'completion-base-size) base-size)
8285 (set (make-local-variable 'completion-base-position) base-position)
8286 (set (make-local-variable 'completion-list-insert-choice-function)
8288 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8289 (if base-dir (setq default-directory base-dir))
8290 ;; Maybe insert help string.
8291 (when completion-show-help
8292 (goto-char (point-min))
8293 (if (display-mouse-p)
8294 (insert "Click on a completion to select it.\n"))
8295 (insert (substitute-command-keys
8296 "In this buffer, type \\[choose-completion] to \
8297 select the completion near point.\n\n"))))))
8299 (add-hook 'completion-setup-hook 'completion-setup-function)
8301 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8302 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8304 (defun switch-to-completions ()
8305 "Select the completion list window."
8307 (let ((window (or (get-buffer-window "*Completions*" 0)
8308 ;; Make sure we have a completions window.
8309 (progn (minibuffer-completion-help)
8310 (get-buffer-window "*Completions*" 0)))))
8312 (select-window window)
8313 ;; In the new buffer, go to the first completion.
8314 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8316 (next-completion 1)))))
8318 ;;; Support keyboard commands to turn on various modifiers.
8320 ;; These functions -- which are not commands -- each add one modifier
8321 ;; to the following event.
8323 (defun event-apply-alt-modifier (_ignore-prompt)
8324 "\\<function-key-map>Add the Alt modifier to the following event.
8325 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8326 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8327 (defun event-apply-super-modifier (_ignore-prompt)
8328 "\\<function-key-map>Add the Super modifier to the following event.
8329 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8330 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8331 (defun event-apply-hyper-modifier (_ignore-prompt)
8332 "\\<function-key-map>Add the Hyper modifier to the following event.
8333 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8334 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8335 (defun event-apply-shift-modifier (_ignore-prompt)
8336 "\\<function-key-map>Add the Shift modifier to the following event.
8337 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8338 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8339 (defun event-apply-control-modifier (_ignore-prompt)
8340 "\\<function-key-map>Add the Ctrl modifier to the following event.
8341 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8342 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8343 (defun event-apply-meta-modifier (_ignore-prompt)
8344 "\\<function-key-map>Add the Meta modifier to the following event.
8345 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8346 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8348 (defun event-apply-modifier (event symbol lshiftby prefix)
8349 "Apply a modifier flag to event EVENT.
8350 SYMBOL is the name of this modifier, as a symbol.
8351 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8352 PREFIX is the string that represents this modifier in an event type symbol."
8354 (cond ((eq symbol 'control)
8355 (if (and (<= (downcase event) ?z)
8356 (>= (downcase event) ?a))
8357 (- (downcase event) ?a -1)
8358 (if (and (<= (downcase event) ?Z)
8359 (>= (downcase event) ?A))
8360 (- (downcase event) ?A -1)
8361 (logior (lsh 1 lshiftby) event))))
8363 (if (and (<= (downcase event) ?z)
8364 (>= (downcase event) ?a))
8366 (logior (lsh 1 lshiftby) event)))
8368 (logior (lsh 1 lshiftby) event)))
8369 (if (memq symbol (event-modifiers event))
8371 (let ((event-type (if (symbolp event) event (car event))))
8372 (setq event-type (intern (concat prefix (symbol-name event-type))))
8375 (cons event-type (cdr event)))))))
8377 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8378 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8379 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8380 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8381 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8382 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8384 ;;;; Keypad support.
8386 ;; Make the keypad keys act like ordinary typing keys. If people add
8387 ;; bindings for the function key symbols, then those bindings will
8388 ;; override these, so this shouldn't interfere with any existing
8391 ;; Also tell read-char how to handle these keys.
8393 (lambda (keypad-normal)
8394 (let ((keypad (nth 0 keypad-normal))
8395 (normal (nth 1 keypad-normal)))
8396 (put keypad 'ascii-character normal)
8397 (define-key function-key-map (vector keypad) (vector normal))))
8398 ;; See also kp-keys bound in bindings.el.
8404 ;; Do the same for various keys that are represented as symbols under
8405 ;; GUIs but naturally correspond to characters.
8416 ;;;; forking a twin copy of a buffer.
8419 (defvar clone-buffer-hook nil
8420 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8422 (defvar clone-indirect-buffer-hook nil
8423 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8425 (defun clone-process (process &optional newname)
8426 "Create a twin copy of PROCESS.
8427 If NEWNAME is nil, it defaults to PROCESS' name;
8428 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8429 If PROCESS is associated with a buffer, the new process will be associated
8430 with the current buffer instead.
8431 Returns nil if PROCESS has already terminated."
8432 (setq newname (or newname (process-name process)))
8433 (if (string-match "<[0-9]+>\\'" newname)
8434 (setq newname (substring newname 0 (match-beginning 0))))
8435 (when (memq (process-status process) '(run stop open))
8436 (let* ((process-connection-type (process-tty-name process))
8438 (if (memq (process-status process) '(open))
8439 (let ((args (process-contact process t)))
8440 (setq args (plist-put args :name newname))
8441 (setq args (plist-put args :buffer
8442 (if (process-buffer process)
8444 (apply 'make-network-process args))
8445 (apply 'start-process newname
8446 (if (process-buffer process) (current-buffer))
8447 (process-command process)))))
8448 (set-process-query-on-exit-flag
8449 new-process (process-query-on-exit-flag process))
8450 (set-process-inherit-coding-system-flag
8451 new-process (process-inherit-coding-system-flag process))
8452 (set-process-filter new-process (process-filter process))
8453 (set-process-sentinel new-process (process-sentinel process))
8454 (set-process-plist new-process (copy-sequence (process-plist process)))
8457 ;; things to maybe add (currently partly covered by `funcall mode'):
8460 (defun clone-buffer (&optional newname display-flag)
8461 "Create and return a twin copy of the current buffer.
8462 Unlike an indirect buffer, the new buffer can be edited
8463 independently of the old one (if it is not read-only).
8464 NEWNAME is the name of the new buffer. It may be modified by
8465 adding or incrementing <N> at the end as necessary to create a
8466 unique buffer name. If nil, it defaults to the name of the
8467 current buffer, with the proper suffix. If DISPLAY-FLAG is
8468 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8469 clone a file-visiting buffer, or a buffer whose major mode symbol
8470 has a non-nil `no-clone' property, results in an error.
8472 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8473 current buffer with appropriate suffix. However, if a prefix
8474 argument is given, then the command prompts for NEWNAME in the
8477 This runs the normal hook `clone-buffer-hook' in the new buffer
8478 after it has been set up properly in other respects."
8481 (if buffer-file-name
8482 (error "Cannot clone a file-visiting buffer"))
8483 (if (get major-mode 'no-clone)
8484 (error "Cannot clone a buffer in %s mode" mode-name))
8485 (list (if current-prefix-arg
8486 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8488 (if buffer-file-name
8489 (error "Cannot clone a file-visiting buffer"))
8490 (if (get major-mode 'no-clone)
8491 (error "Cannot clone a buffer in %s mode" mode-name))
8492 (setq newname (or newname (buffer-name)))
8493 (if (string-match "<[0-9]+>\\'" newname)
8494 (setq newname (substring newname 0 (match-beginning 0))))
8495 (let ((buf (current-buffer))
8499 (mk (if mark-active (mark t)))
8500 (modified (buffer-modified-p))
8502 (lvars (buffer-local-variables))
8503 (process (get-buffer-process (current-buffer)))
8504 (new (generate-new-buffer (or newname (buffer-name)))))
8507 (with-current-buffer new
8508 (insert-buffer-substring buf)))
8509 (with-current-buffer new
8510 (narrow-to-region ptmin ptmax)
8512 (if mk (set-mark mk))
8513 (set-buffer-modified-p modified)
8515 ;; Clone the old buffer's process, if any.
8516 (when process (clone-process process))
8518 ;; Now set up the major mode.
8521 ;; Set up other local variables.
8523 (condition-case () ;in case var is read-only
8526 (set (make-local-variable (car v)) (cdr v)))
8530 ;; Run any hooks (typically set up by the major mode
8531 ;; for cloning to work properly).
8532 (run-hooks 'clone-buffer-hook))
8534 ;; Presumably the current buffer is shown in the selected frame, so
8535 ;; we want to display the clone elsewhere.
8536 (let ((same-window-regexps nil)
8537 (same-window-buffer-names))
8538 (pop-to-buffer new)))
8542 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8543 "Create an indirect buffer that is a twin copy of the current buffer.
8545 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8546 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8547 or if not called with a prefix arg, NEWNAME defaults to the current
8548 buffer's name. The name is modified by adding a `<N>' suffix to it
8549 or by incrementing the N in an existing suffix. Trying to clone a
8550 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8551 property results in an error.
8553 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8554 This is always done when called interactively.
8556 Optional third arg NORECORD non-nil means do not put this buffer at the
8557 front of the list of recently selected ones.
8559 Returns the newly created indirect buffer."
8562 (if (get major-mode 'no-clone-indirect)
8563 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8564 (list (if current-prefix-arg
8565 (read-buffer "Name of indirect buffer: " (current-buffer)))
8567 (if (get major-mode 'no-clone-indirect)
8568 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8569 (setq newname (or newname (buffer-name)))
8570 (if (string-match "<[0-9]+>\\'" newname)
8571 (setq newname (substring newname 0 (match-beginning 0))))
8572 (let* ((name (generate-new-buffer-name newname))
8573 (buffer (make-indirect-buffer (current-buffer) name t)))
8574 (with-current-buffer buffer
8575 (run-hooks 'clone-indirect-buffer-hook))
8577 (pop-to-buffer buffer nil norecord))
8581 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8582 "Like `clone-indirect-buffer' but display in another window."
8585 (if (get major-mode 'no-clone-indirect)
8586 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8587 (list (if current-prefix-arg
8588 (read-buffer "Name of indirect buffer: " (current-buffer)))
8590 (let ((pop-up-windows t))
8591 (clone-indirect-buffer newname display-flag norecord)))
8594 ;;; Handling of Backspace and Delete keys.
8596 (defcustom normal-erase-is-backspace 'maybe
8597 "Set the default behavior of the Delete and Backspace keys.
8599 If set to t, Delete key deletes forward and Backspace key deletes
8602 If set to nil, both Delete and Backspace keys delete backward.
8604 If set to `maybe' (which is the default), Emacs automatically
8605 selects a behavior. On window systems, the behavior depends on
8606 the keyboard used. If the keyboard has both a Backspace key and
8607 a Delete key, and both are mapped to their usual meanings, the
8608 option's default value is set to t, so that Backspace can be used
8609 to delete backward, and Delete can be used to delete forward.
8611 If not running under a window system, customizing this option
8612 accomplishes a similar effect by mapping C-h, which is usually
8613 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8614 via `keyboard-translate'. The former functionality of C-h is
8615 available on the F1 key. You should probably not use this
8616 setting if you don't have both Backspace, Delete and F1 keys.
8618 Setting this variable with setq doesn't take effect. Programmatically,
8619 call `normal-erase-is-backspace-mode' (which see) instead."
8620 :type '(choice (const :tag "Off" nil)
8621 (const :tag "Maybe" maybe)
8622 (other :tag "On" t))
8623 :group 'editing-basics
8625 :set (lambda (symbol value)
8626 ;; The fboundp is because of a problem with :set when
8627 ;; dumping Emacs. It doesn't really matter.
8628 (if (fboundp 'normal-erase-is-backspace-mode)
8629 (normal-erase-is-backspace-mode (or value 0))
8630 (set-default symbol value))))
8632 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8633 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8634 (unless frame (setq frame (selected-frame)))
8635 (with-selected-frame frame
8636 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8637 (normal-erase-is-backspace-mode
8638 (if (if (eq normal-erase-is-backspace 'maybe)
8639 (and (not noninteractive)
8640 (or (memq system-type '(ms-dos windows-nt))
8641 (memq window-system '(w32 ns))
8642 (and (memq window-system '(x))
8643 (fboundp 'x-backspace-delete-keys-p)
8644 (x-backspace-delete-keys-p))
8645 ;; If the terminal Emacs is running on has erase char
8646 ;; set to ^H, use the Backspace key for deleting
8647 ;; backward, and the Delete key for deleting forward.
8648 (and (null window-system)
8649 (eq tty-erase-char ?\^H))))
8650 normal-erase-is-backspace)
8653 (define-minor-mode normal-erase-is-backspace-mode
8654 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8655 With a prefix argument ARG, enable this feature if ARG is
8656 positive, and disable it otherwise. If called from Lisp, enable
8657 the mode if ARG is omitted or nil.
8659 On window systems, when this mode is on, Delete is mapped to C-d
8660 and Backspace is mapped to DEL; when this mode is off, both
8661 Delete and Backspace are mapped to DEL. (The remapping goes via
8662 `local-function-key-map', so binding Delete or Backspace in the
8663 global or local keymap will override that.)
8665 In addition, on window systems, the bindings of C-Delete, M-Delete,
8666 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8667 the global keymap in accordance with the functionality of Delete and
8668 Backspace. For example, if Delete is remapped to C-d, which deletes
8669 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8670 to DEL, which deletes backward, C-Delete is bound to
8671 `backward-kill-word'.
8673 If not running on a window system, a similar effect is accomplished by
8674 remapping C-h (normally produced by the Backspace key) and DEL via
8675 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8676 to C-d; if it's off, the keys are not remapped.
8678 When not running on a window system, and this mode is turned on, the
8679 former functionality of C-h is available on the F1 key. You should
8680 probably not turn on this mode on a text-only terminal if you don't
8681 have both Backspace, Delete and F1 keys.
8683 See also `normal-erase-is-backspace'."
8684 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8686 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8688 (let ((enabled (eq 1 (terminal-parameter
8689 nil 'normal-erase-is-backspace))))
8691 (cond ((or (memq window-system '(x w32 ns pc))
8692 (memq system-type '(ms-dos windows-nt)))
8694 `(([M-delete] [M-backspace])
8695 ([C-M-delete] [C-M-backspace])
8696 ([?\e C-delete] [?\e C-backspace]))))
8700 (define-key local-function-key-map [delete] [deletechar])
8701 (define-key local-function-key-map [kp-delete] [deletechar])
8702 (define-key local-function-key-map [backspace] [?\C-?])
8703 (dolist (b bindings)
8704 ;; Not sure if input-decode-map is really right, but
8705 ;; keyboard-translate-table (used below) only works
8706 ;; for integer events, and key-translation-table is
8707 ;; global (like the global-map, used earlier).
8708 (define-key input-decode-map (car b) nil)
8709 (define-key input-decode-map (cadr b) nil)))
8710 (define-key local-function-key-map [delete] [?\C-?])
8711 (define-key local-function-key-map [kp-delete] [?\C-?])
8712 (define-key local-function-key-map [backspace] [?\C-?])
8713 (dolist (b bindings)
8714 (define-key input-decode-map (car b) (cadr b))
8715 (define-key input-decode-map (cadr b) (car b))))))
8719 (keyboard-translate ?\C-h ?\C-?)
8720 (keyboard-translate ?\C-? ?\C-d))
8721 (keyboard-translate ?\C-h ?\C-h)
8722 (keyboard-translate ?\C-? ?\C-?))))
8724 (if (called-interactively-p 'interactive)
8725 (message "Delete key deletes %s"
8726 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8727 "forward" "backward")))))
8729 (defvar vis-mode-saved-buffer-invisibility-spec nil
8730 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8732 (define-minor-mode read-only-mode
8733 "Change whether the current buffer is read-only.
8734 With prefix argument ARG, make the buffer read-only if ARG is
8735 positive, otherwise make it writable. If buffer is read-only
8736 and `view-read-only' is non-nil, enter view mode.
8738 Do not call this from a Lisp program unless you really intend to
8739 do the same thing as the \\[read-only-mode] command, including
8740 possibly enabling or disabling View mode. Also, note that this
8741 command works by setting the variable `buffer-read-only', which
8742 does not affect read-only regions caused by text properties. To
8743 ignore read-only status in a Lisp program (whether due to text
8744 properties or buffer state), bind `inhibit-read-only' temporarily
8745 to a non-nil value."
8746 :variable buffer-read-only
8748 ((and (not buffer-read-only) view-mode)
8749 (View-exit-and-edit)
8750 (make-local-variable 'view-read-only)
8751 (setq view-read-only t)) ; Must leave view mode.
8752 ((and buffer-read-only view-read-only
8753 ;; If view-mode is already active, `view-mode-enter' is a nop.
8755 (not (eq (get major-mode 'mode-class) 'special)))
8756 (view-mode-enter))))
8758 (define-minor-mode visible-mode
8759 "Toggle making all invisible text temporarily visible (Visible mode).
8760 With a prefix argument ARG, enable Visible mode if ARG is
8761 positive, and disable it otherwise. If called from Lisp, enable
8762 the mode if ARG is omitted or nil.
8764 This mode works by saving the value of `buffer-invisibility-spec'
8765 and setting it to nil."
8767 :group 'editing-basics
8768 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8769 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8770 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8772 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8773 buffer-invisibility-spec)
8774 (setq buffer-invisibility-spec nil)))
8776 (defvar messages-buffer-mode-map
8777 (let ((map (make-sparse-keymap)))
8778 (set-keymap-parent map special-mode-map)
8779 (define-key map "g" nil) ; nothing to revert
8782 (define-derived-mode messages-buffer-mode special-mode "Messages"
8783 "Major mode used in the \"*Messages*\" buffer.")
8785 (defun messages-buffer ()
8786 "Return the \"*Messages*\" buffer.
8787 If it does not exist, create and it switch it to `messages-buffer-mode'."
8788 (or (get-buffer "*Messages*")
8789 (with-current-buffer (get-buffer-create "*Messages*")
8790 (messages-buffer-mode)
8794 ;; Minibuffer prompt stuff.
8796 ;;(defun minibuffer-prompt-modification (start end)
8797 ;; (error "You cannot modify the prompt"))
8800 ;;(defun minibuffer-prompt-insertion (start end)
8801 ;; (let ((inhibit-modification-hooks t))
8802 ;; (delete-region start end)
8803 ;; ;; Discard undo information for the text insertion itself
8804 ;; ;; and for the text deletion.above.
8805 ;; (when (consp buffer-undo-list)
8806 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8807 ;; (message "You cannot modify the prompt")))
8810 ;;(setq minibuffer-prompt-properties
8811 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8812 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8815 ;;;; Problematic external packages.
8817 ;; rms says this should be done by specifying symbols that define
8818 ;; versions together with bad values. This is therefore not as
8819 ;; flexible as it could be. See the thread:
8820 ;; https://lists.gnu.org/r/emacs-devel/2007-08/msg00300.html
8821 (defconst bad-packages-alist
8822 ;; Not sure exactly which semantic versions have problems.
8823 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8824 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8825 "The version of `semantic' loaded does not work in Emacs 22.
8826 It can cause constant high CPU load.
8827 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8828 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8829 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8830 ;; provided the `CUA-mode' feature. Since this is no longer true,
8831 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8833 "CUA-mode is now part of the standard GNU Emacs distribution,
8834 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8836 You have loaded an older version of CUA-mode which does not work
8837 correctly with this version of Emacs. You should remove the old
8838 version and use the one distributed with Emacs."))
8839 "Alist of packages known to cause problems in this version of Emacs.
8840 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8841 PACKAGE is either a regular expression to match file names, or a
8842 symbol (a feature name), like for `with-eval-after-load'.
8843 SYMBOL is either the name of a string variable, or t. Upon
8844 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8845 warning using STRING as the message.")
8847 (defun bad-package-check (package)
8848 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8850 (let* ((list (assoc package bad-packages-alist))
8851 (symbol (nth 1 list)))
8855 (and (stringp (setq symbol (eval symbol)))
8856 (string-match-p (nth 2 list) symbol)))
8857 (display-warning package (nth 3 list) :warning)))
8860 (dolist (elem bad-packages-alist)
8861 (let ((pkg (car elem)))
8862 (with-eval-after-load pkg
8863 (bad-package-check pkg))))
8866 ;;; Generic dispatcher commands
8868 ;; Macro `define-alternatives' is used to create generic commands.
8869 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8870 ;; that can have different alternative implementations where choosing
8871 ;; among them is exclusively a matter of user preference.
8873 ;; (define-alternatives COMMAND) creates a new interactive command
8874 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8875 ;; Typically, the user will not need to customize this variable; packages
8876 ;; wanting to add alternative implementations should use
8878 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8880 (defmacro define-alternatives (command &rest customizations)
8881 "Define the new command `COMMAND'.
8883 The argument `COMMAND' should be a symbol.
8885 Running `M-x COMMAND RET' for the first time prompts for which
8886 alternative to use and records the selected command as a custom
8889 Running `C-u M-x COMMAND RET' prompts again for an alternative
8890 and overwrites the previous choice.
8892 The variable `COMMAND-alternatives' contains an alist with
8893 alternative implementations of COMMAND. `define-alternatives'
8894 does not have any effect until this variable is set.
8896 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8897 `defcustom' keywords and values to add to the declaration of
8898 `COMMAND-alternatives' (typically :group and :version)."
8899 (let* ((command-name (symbol-name command))
8900 (varalt-name (concat command-name "-alternatives"))
8901 (varalt-sym (intern varalt-name))
8902 (varimp-sym (intern (concat command-name "--implementation"))))
8905 (defcustom ,varalt-sym nil
8906 ,(format "Alist of alternative implementations for the `%s' command.
8908 Each entry must be a pair (ALTNAME . ALTFUN), where:
8909 ALTNAME - The name shown at user to describe the alternative implementation.
8910 ALTFUN - The function called to implement this alternative."
8912 :type '(alist :key-type string :value-type function)
8915 (put ',varalt-sym 'definition-name ',command)
8916 (defvar ,varimp-sym nil "Internal use only.")
8918 (defun ,command (&optional arg)
8919 ,(format "Run generic command `%s'.
8920 If used for the first time, or with interactive ARG, ask the user which
8921 implementation to use for `%s'. The variable `%s'
8922 contains the list of implementations currently supported for this command."
8923 command-name command-name varalt-name)
8925 (when (or arg (null ,varimp-sym))
8926 (let ((val (completing-read
8928 "Select implementation for command `%s': "
8930 ,varalt-sym nil t)))
8931 (unless (string-equal val "")
8932 (when (null ,varimp-sym)
8934 "Use C-u M-x %s RET`to select another implementation"
8937 (customize-save-variable ',varimp-sym
8938 (cdr (assoc-string val ,varalt-sym))))))
8940 (call-interactively ,varimp-sym)
8941 (message "%s" ,(format-message
8942 "No implementation selected for command `%s'"
8946 ;;; Functions for changing capitalization that Do What I Mean
8947 (defun upcase-dwim (arg)
8948 "Upcase words in the region, if active; if not, upcase word at point.
8949 If the region is active, this function calls `upcase-region'.
8950 Otherwise, it calls `upcase-word', with prefix argument passed to it
8951 to upcase ARG words."
8954 (upcase-region (region-beginning) (region-end))
8957 (defun downcase-dwim (arg)
8958 "Downcase words in the region, if active; if not, downcase word at point.
8959 If the region is active, this function calls `downcase-region'.
8960 Otherwise, it calls `downcase-word', with prefix argument passed to it
8961 to downcase ARG words."
8964 (downcase-region (region-beginning) (region-end))
8965 (downcase-word arg)))
8967 (defun capitalize-dwim (arg)
8968 "Capitalize words in the region, if active; if not, capitalize word at point.
8969 If the region is active, this function calls `capitalize-region'.
8970 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8971 to capitalize ARG words."
8974 (capitalize-region (region-beginning) (region-end))
8975 (capitalize-word arg)))
8981 ;;; simple.el ends here