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 (let ((buffer (next-error-find-buffer)))
284 ;; We know here that next-error-function is a valid symbol we can funcall
285 (with-current-buffer buffer
286 (funcall next-error-function
(prefix-numeric-value arg
) reset
)
287 ;; Override possible change of next-error-last-buffer in next-error-function
288 (setq next-error-last-buffer buffer
)
289 (when next-error-recenter
290 (recenter next-error-recenter
))
291 (run-hooks 'next-error-hook
)))))
293 (defun next-error-internal ()
294 "Visit the source code corresponding to the `next-error' message at point."
295 (let ((buffer (current-buffer)))
296 ;; We know here that next-error-function is a valid symbol we can funcall
297 (with-current-buffer buffer
298 (funcall next-error-function
0 nil
)
299 ;; Override possible change of next-error-last-buffer in next-error-function
300 (setq next-error-last-buffer buffer
)
301 (when next-error-recenter
302 (recenter next-error-recenter
))
303 (run-hooks 'next-error-hook
))))
305 (defalias 'goto-next-locus
'next-error
)
306 (defalias 'next-match
'next-error
)
308 (defun previous-error (&optional n
)
309 "Visit previous `next-error' message and corresponding source code.
311 Prefix arg N says how many error messages to move backwards (or
312 forwards, if negative).
314 This operates on the output from the \\[compile] and \\[grep] commands."
316 (next-error (- (or n
1))))
318 (defun first-error (&optional n
)
319 "Restart at the first error.
320 Visit corresponding source code.
321 With prefix arg N, visit the source code of the Nth error.
322 This operates on the output from the \\[compile] command, for instance."
326 (defun next-error-no-select (&optional n
)
327 "Move point to the next error in the `next-error' buffer and highlight match.
328 Prefix arg N says how many error messages to move forwards (or
329 backwards, if negative).
330 Finds and highlights the source line like \\[next-error], but does not
331 select the source buffer."
333 (let ((next-error-highlight next-error-highlight-no-select
))
335 (pop-to-buffer next-error-last-buffer
))
337 (defun previous-error-no-select (&optional n
)
338 "Move point to the previous error in the `next-error' buffer and highlight match.
339 Prefix arg N says how many error messages to move backwards (or
340 forwards, if negative).
341 Finds and highlights the source line like \\[previous-error], but does not
342 select the source buffer."
344 (next-error-no-select (- (or n
1))))
346 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
347 (defvar next-error-follow-last-line nil
)
349 (define-minor-mode next-error-follow-minor-mode
350 "Minor mode for compilation, occur and diff modes.
351 With a prefix argument ARG, enable mode if ARG is positive, and
352 disable it otherwise. If called from Lisp, enable mode if ARG is
354 When turned on, cursor motion in the compilation, grep, occur or diff
355 buffer causes automatic display of the corresponding source code location."
356 :group
'next-error
:init-value nil
:lighter
" Fol"
357 (if (not next-error-follow-minor-mode
)
358 (remove-hook 'post-command-hook
'next-error-follow-mode-post-command-hook t
)
359 (add-hook 'post-command-hook
'next-error-follow-mode-post-command-hook nil t
)
360 (make-local-variable 'next-error-follow-last-line
)))
362 ;; Used as a `post-command-hook' by `next-error-follow-mode'
363 ;; for the *Compilation* *grep* and *Occur* buffers.
364 (defun next-error-follow-mode-post-command-hook ()
365 (unless (equal next-error-follow-last-line
(line-number-at-pos))
366 (setq next-error-follow-last-line
(line-number-at-pos))
368 (let ((compilation-context-lines nil
))
369 (setq compilation-current-error
(point))
370 (next-error-no-select 0))
376 (defun fundamental-mode ()
377 "Major mode not specialized for anything in particular.
378 Other major modes are defined by comparison with this one."
380 (kill-all-local-variables)
383 ;; Special major modes to view specially formatted data rather than files.
385 (defvar special-mode-map
386 (let ((map (make-sparse-keymap)))
387 (suppress-keymap map
)
388 (define-key map
"q" 'quit-window
)
389 (define-key map
" " 'scroll-up-command
)
390 (define-key map
[?\S-\
] 'scroll-down-command
)
391 (define-key map
"\C-?" 'scroll-down-command
)
392 (define-key map
"?" 'describe-mode
)
393 (define-key map
"h" 'describe-mode
)
394 (define-key map
">" 'end-of-buffer
)
395 (define-key map
"<" 'beginning-of-buffer
)
396 (define-key map
"g" 'revert-buffer
)
399 (put 'special-mode
'mode-class
'special
)
400 (define-derived-mode special-mode nil
"Special"
401 "Parent major mode from which special major modes should inherit."
402 (setq buffer-read-only t
))
404 ;; Making and deleting lines.
406 (defvar self-insert-uses-region-functions nil
407 "Special hook to tell if `self-insert-command' will use the region.
408 It must be called via `run-hook-with-args-until-success' with no arguments.
410 If any function on this hook returns a non-nil value, `delete-selection-mode'
411 will act on that value (see `delete-selection-helper'), and will
412 usually delete the region. If all the functions on this hook return
413 nil, it is an indiction that `self-insert-command' needs the region
414 untouched by `delete-selection-mode', and will itself do whatever is
415 appropriate with the region.
416 Any function on `post-self-insert-hook' which act on the region should
417 add a function to this hook so that `delete-selection-mode' could
418 refrain from deleting the region before `post-self-insert-hook'
419 functions are called.
420 This hook is run by `delete-selection-uses-region-p', which see.")
422 (defvar hard-newline
(propertize "\n" 'hard t
'rear-nonsticky
'(hard))
423 "Propertized string representing a hard newline character.")
425 (defun newline (&optional arg interactive
)
426 "Insert a newline, and move to left margin of the new line if it's blank.
427 If option `use-hard-newlines' is non-nil, the newline is marked with the
428 text-property `hard'.
429 With ARG, insert that many newlines.
431 If `electric-indent-mode' is enabled, this indents the final new line
432 that it adds, and reindents the preceding line. To just insert
433 a newline, use \\[electric-indent-just-newline].
435 Calls `auto-fill-function' if the current column number is greater
436 than the value of `fill-column' and ARG is nil.
437 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
438 (interactive "*P\np")
439 (barf-if-buffer-read-only)
440 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
441 ;; Set last-command-event to tell self-insert what to insert.
442 (let* ((was-page-start (and (bolp) (looking-at page-delimiter
)))
444 (last-command-event ?
\n)
445 ;; Don't auto-fill if we have a numeric argument.
446 (auto-fill-function (if arg nil auto-fill-function
))
447 (arg (prefix-numeric-value arg
))
449 ;; Do the rest in post-self-insert-hook, because we want to do it
450 ;; *before* other functions on that hook.
452 ;; Mark the newline(s) `hard'.
453 (if use-hard-newlines
454 (set-hard-newline-properties
455 (- (point) arg
) (point)))
456 ;; If the newline leaves the previous line blank, and we
457 ;; have a left margin, delete that from the blank line.
459 (goto-char beforepos
)
461 (and (looking-at "[ \t]$")
462 (> (current-left-margin) 0)
463 (delete-region (point)
464 (line-end-position))))
465 ;; Indent the line after the newline, except in one case:
466 ;; when we added the newline at the beginning of a line which
469 (move-to-left-margin nil t
)))))
470 (if (not interactive
)
471 ;; FIXME: For non-interactive uses, many calls actually
472 ;; just want (insert "\n"), so maybe we should do just
473 ;; that, so as to avoid the risk of filling or running
474 ;; abbrevs unexpectedly.
475 (let ((post-self-insert-hook (list postproc
)))
476 (self-insert-command arg
))
479 (add-hook 'post-self-insert-hook postproc nil t
)
480 (self-insert-command arg
))
481 ;; We first used let-binding to protect the hook, but that
482 ;; was naive since add-hook affects the symbol-default
483 ;; value of the variable, whereas the let-binding might
484 ;; only protect the buffer-local value.
485 (remove-hook 'post-self-insert-hook postproc t
))))
488 (defun set-hard-newline-properties (from to
)
489 (let ((sticky (get-text-property from
'rear-nonsticky
)))
490 (put-text-property from to
'hard
't
)
491 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
492 (if (and (listp sticky
) (not (memq 'hard sticky
)))
493 (put-text-property from
(point) 'rear-nonsticky
494 (cons 'hard sticky
)))))
497 "Insert a newline and leave point before it.
498 If there is a fill prefix and/or a `left-margin', insert them on
499 the new line if the line would have been blank.
500 With arg N, insert N newlines."
502 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
503 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
505 ;; Don't expand an abbrev before point.
511 (if do-left-margin
(indent-to (current-left-margin)))
512 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
516 ;; Necessary in case a margin or prefix was inserted.
519 (defun split-line (&optional arg
)
520 "Split current line, moving portion beyond point vertically down.
521 If the current line starts with `fill-prefix', insert it on the new
522 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
524 When called from Lisp code, ARG may be a prefix string to copy."
526 (skip-chars-forward " \t")
527 (let* ((col (current-column))
529 ;; What prefix should we check for (nil means don't).
530 (prefix (cond ((stringp arg
) arg
)
533 ;; Does this line start with it?
534 (have-prfx (and prefix
537 (looking-at (regexp-quote prefix
))))))
539 (if have-prfx
(insert-and-inherit prefix
))
543 (defun delete-indentation (&optional arg
)
544 "Join this line to previous and fix up whitespace at join.
545 If there is a fill prefix, delete it from the beginning of this line.
546 With argument, join this line to following line."
549 (if arg
(forward-line 1))
550 (if (eq (preceding-char) ?
\n)
552 (delete-region (point) (1- (point)))
553 ;; If the second line started with the fill prefix,
554 ;; delete the prefix.
556 (<= (+ (point) (length fill-prefix
)) (point-max))
558 (buffer-substring (point)
559 (+ (point) (length fill-prefix
)))))
560 (delete-region (point) (+ (point) (length fill-prefix
))))
561 (fixup-whitespace))))
563 (defalias 'join-line
#'delete-indentation
) ; easier to find
565 (defun delete-blank-lines ()
566 "On blank line, delete all surrounding blank lines, leaving just one.
567 On isolated blank line, delete that one.
568 On nonblank line, delete any immediately following blank lines."
570 (let (thisblank singleblank
)
573 (setq thisblank
(looking-at "[ \t]*$"))
574 ;; Set singleblank if there is just one blank line here.
577 (not (looking-at "[ \t]*\n[ \t]*$"))
579 (progn (forward-line -
1)
580 (not (looking-at "[ \t]*$")))))))
581 ;; Delete preceding blank lines, and this one too if it's the only one.
585 (if singleblank
(forward-line 1))
586 (delete-region (point)
587 (if (re-search-backward "[^ \t\n]" nil t
)
588 (progn (forward-line 1) (point))
590 ;; Delete following blank lines, unless the current line is blank
591 ;; and there are no following blank lines.
592 (if (not (and thisblank singleblank
))
596 (delete-region (point)
597 (if (re-search-forward "[^ \t\n]" nil t
)
598 (progn (beginning-of-line) (point))
600 ;; Handle the special case where point is followed by newline and eob.
601 ;; Delete the line, leaving point at eob.
602 (if (looking-at "^[ \t]*\n\\'")
603 (delete-region (point) (point-max)))))
605 (defcustom delete-trailing-lines t
606 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
607 Trailing lines are deleted only if `delete-trailing-whitespace'
608 is called on the entire buffer (rather than an active region)."
613 (defun region-modifiable-p (start end
)
614 "Return non-nil if the region contains no read-only text."
615 (and (not (get-text-property start
'read-only
))
616 (eq end
(next-single-property-change start
'read-only nil end
))))
618 (defun delete-trailing-whitespace (&optional start end
)
619 "Delete trailing whitespace between START and END.
620 If called interactively, START and END are the start/end of the
621 region if the mark is active, or of the buffer's accessible
622 portion if the mark is inactive.
624 This command deletes whitespace characters after the last
625 non-whitespace character in each line between START and END. It
626 does not consider formfeed characters to be whitespace.
628 If this command acts on the entire buffer (i.e. if called
629 interactively with the mark inactive, or called from Lisp with
630 END nil), it also deletes all trailing lines at the end of the
631 buffer if the variable `delete-trailing-lines' is non-nil."
633 (barf-if-buffer-read-only)
635 (list (region-beginning) (region-end))
639 (let ((end-marker (and end
(copy-marker end
))))
640 (goto-char (or start
(point-min)))
641 (with-syntax-table (make-syntax-table (syntax-table))
642 ;; Don't delete formfeeds, even if they are considered whitespace.
643 (modify-syntax-entry ?
\f "_")
644 (while (re-search-forward "\\s-$" end-marker t
)
645 (skip-syntax-backward "-" (line-beginning-position))
646 (let ((b (point)) (e (match-end 0)))
647 (when (region-modifiable-p b e
)
648 (delete-region b e
)))))
650 (set-marker end-marker nil
)
651 ;; Delete trailing empty lines.
652 (and delete-trailing-lines
653 ;; Really the end of buffer.
654 (= (goto-char (point-max)) (1+ (buffer-size)))
655 (<= (skip-chars-backward "\n") -
2)
656 (region-modifiable-p (1+ (point)) (point-max))
657 (delete-region (1+ (point)) (point-max)))))))
658 ;; Return nil for the benefit of `write-file-functions'.
661 (defun newline-and-indent ()
662 "Insert a newline, then indent according to major mode.
663 Indentation is done using the value of `indent-line-function'.
664 In programming language modes, this is the same as TAB.
665 In some text modes, where TAB inserts a tab, this command indents to the
666 column specified by the function `current-left-margin'."
668 (delete-horizontal-space t
)
670 (indent-according-to-mode))
672 (defun reindent-then-newline-and-indent ()
673 "Reindent current line, insert newline, then indent the new line.
674 Indentation of both lines is done according to the current major mode,
675 which means calling the current value of `indent-line-function'.
676 In programming language modes, this is the same as TAB.
677 In some text modes, where TAB inserts a tab, this indents to the
678 column specified by the function `current-left-margin'."
681 ;; Be careful to insert the newline before indenting the line.
682 ;; Otherwise, the indentation might be wrong.
686 ;; We are at EOL before the call to indent-according-to-mode, and
687 ;; after it we usually are as well, but not always. We tried to
688 ;; address it with `save-excursion' but that uses a normal marker
689 ;; whereas we need `move after insertion', so we do the save/restore
691 (setq pos
(copy-marker pos t
))
692 (indent-according-to-mode)
694 ;; Remove the trailing white-space after indentation because
695 ;; indentation may introduce the whitespace.
696 (delete-horizontal-space t
))
697 (indent-according-to-mode)))
699 (defcustom read-quoted-char-radix
8
700 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
701 Legitimate radix values are 8, 10 and 16."
702 :type
'(choice (const 8) (const 10) (const 16))
703 :group
'editing-basics
)
705 (defun read-quoted-char (&optional prompt
)
706 "Like `read-char', but do not allow quitting.
707 Also, if the first character read is an octal digit,
708 we read any number of octal digits and return the
709 specified character code. Any nondigit terminates the sequence.
710 If the terminator is RET, it is discarded;
711 any other terminator is used itself as input.
713 The optional argument PROMPT specifies a string to use to prompt the user.
714 The variable `read-quoted-char-radix' controls which radix to use
716 (let ((message-log-max nil
)
717 (help-events (delq nil
(mapcar (lambda (c) (unless (characterp c
) c
))
719 done
(first t
) (code 0) char translated
)
721 (let ((inhibit-quit first
)
722 ;; Don't let C-h or other help chars get the help
723 ;; message--only help function keys. See bug#16617.
725 (help-event-list help-events
)
727 "Type the special character you want to use,
728 or the octal character code.
729 RET terminates the character code and is discarded;
730 any other non-digit terminates the character code and is then used as input."))
731 (setq char
(read-event (and prompt
(format "%s-" prompt
)) t
))
732 (if inhibit-quit
(setq quit-flag nil
)))
733 ;; Translate TAB key into control-I ASCII character, and so on.
734 ;; Note: `read-char' does it using the `ascii-character' property.
735 ;; We tried using read-key instead, but that disables the keystroke
736 ;; echo produced by 'C-q', see bug#24635.
737 (let ((translation (lookup-key local-function-key-map
(vector char
))))
738 (setq translated
(if (arrayp translation
)
741 (if (integerp translated
)
742 (setq translated
(char-resolve-modifiers translated
)))
743 (cond ((null translated
))
744 ((not (integerp translated
))
745 (setq unread-command-events
(list char
)
747 ((/= (logand translated ?\M-\^
@) 0)
748 ;; Turn a meta-character into a character with the 0200 bit set.
749 (setq code
(logior (logand translated
(lognot ?\M-\^
@)) 128)
751 ((and (<= ?
0 translated
)
752 (< translated
(+ ?
0 (min 10 read-quoted-char-radix
))))
753 (setq code
(+ (* code read-quoted-char-radix
) (- translated ?
0)))
754 (and prompt
(setq prompt
(message "%s %c" prompt translated
))))
755 ((and (<= ?a
(downcase translated
))
756 (< (downcase translated
)
757 (+ ?a -
10 (min 36 read-quoted-char-radix
))))
758 (setq code
(+ (* code read-quoted-char-radix
)
759 (+ 10 (- (downcase translated
) ?a
))))
760 (and prompt
(setq prompt
(message "%s %c" prompt translated
))))
761 ((and (not first
) (eq translated ?\C-m
))
764 (setq unread-command-events
(list char
)
766 (t (setq code translated
771 (defun quoted-insert (arg)
772 "Read next input character and insert it.
773 This is useful for inserting control characters.
774 With argument, insert ARG copies of the character.
776 If the first character you type after this command is an octal digit,
777 you should type a sequence of octal digits which specify a character code.
778 Any nondigit terminates the sequence. If the terminator is a RET,
779 it is discarded; any other terminator is used itself as input.
780 The variable `read-quoted-char-radix' specifies the radix for this feature;
781 set it to 10 or 16 to use decimal or hex instead of octal.
783 In overwrite mode, this function inserts the character anyway, and
784 does not handle octal digits specially. This means that if you use
785 overwrite as your normal editing mode, you can use this function to
786 insert characters when necessary.
788 In binary overwrite mode, this function does overwrite, and octal
789 digits are interpreted as a character code. This is intended to be
790 useful for editing binary files."
793 ;; Avoid "obsolete" warnings for translation-table-for-input.
795 (let (translation-table-for-input input-method-function
)
796 (if (or (not overwrite-mode
)
797 (eq overwrite-mode
'overwrite-mode-binary
))
800 ;; This used to assume character codes 0240 - 0377 stand for
801 ;; characters in some single-byte character set, and converted them
802 ;; to Emacs characters. But in 23.1 this feature is deprecated
803 ;; in favor of inserting the corresponding Unicode characters.
804 ;; (if (and enable-multibyte-characters
807 ;; (setq char (unibyte-char-to-multibyte char)))
808 (unless (characterp char
)
809 (user-error "%s is not a valid character"
810 (key-description (vector char
))))
812 (if (eq overwrite-mode
'overwrite-mode-binary
)
815 (insert-and-inherit char
)
816 (setq arg
(1- arg
)))))
818 (defun forward-to-indentation (&optional arg
)
819 "Move forward ARG lines and position at first nonblank character."
821 (forward-line (or arg
1))
822 (skip-chars-forward " \t"))
824 (defun backward-to-indentation (&optional arg
)
825 "Move backward ARG lines and position at first nonblank character."
827 (forward-line (- (or arg
1)))
828 (skip-chars-forward " \t"))
830 (defun back-to-indentation ()
831 "Move point to the first non-whitespace character on this line."
833 (beginning-of-line 1)
834 (skip-syntax-forward " " (line-end-position))
835 ;; Move back over chars that have whitespace syntax but have the p flag.
836 (backward-prefix-chars))
838 (defun fixup-whitespace ()
839 "Fixup white space between objects around point.
840 Leave one space or none, according to the context."
843 (delete-horizontal-space)
844 (if (or (looking-at "^\\|$\\|\\s)")
845 (save-excursion (forward-char -
1)
846 (looking-at "$\\|\\s(\\|\\s'")))
850 (defun delete-horizontal-space (&optional backward-only
)
851 "Delete all spaces and tabs around point.
852 If BACKWARD-ONLY is non-nil, only delete them before point."
854 (let ((orig-pos (point)))
859 (skip-chars-forward " \t")
860 (constrain-to-field nil orig-pos t
)))
862 (skip-chars-backward " \t")
863 (constrain-to-field nil orig-pos
)))))
865 (defun just-one-space (&optional n
)
866 "Delete all spaces and tabs around point, leaving one space (or N spaces).
867 If N is negative, delete newlines as well, leaving -N spaces.
868 See also `cycle-spacing'."
870 (cycle-spacing n nil
'single-shot
))
872 (defvar cycle-spacing--context nil
873 "Store context used in consecutive calls to `cycle-spacing' command.
874 The first time `cycle-spacing' runs, it saves in this variable:
875 its N argument, the original point position, and the original spacing
878 (defun cycle-spacing (&optional n preserve-nl-back mode
)
879 "Manipulate whitespace around point in a smart way.
880 In interactive use, this function behaves differently in successive
883 The first call in a sequence acts like `just-one-space'.
884 It deletes all spaces and tabs around point, leaving one space
885 \(or N spaces). N is the prefix argument. If N is negative,
886 it deletes newlines as well, leaving -N spaces.
887 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
889 The second call in a sequence deletes all spaces.
891 The third call in a sequence restores the original whitespace (and point).
893 If MODE is `single-shot', it only performs the first step in the sequence.
894 If MODE is `fast' and the first step would not result in any change
895 \(i.e., there are exactly (abs N) spaces around point),
896 the function goes straight to the second step.
898 Repeatedly calling the function with different values of N starts a
899 new sequence each time."
901 (let ((orig-pos (point))
902 (skip-characters (if (and n
(< n
0)) " \t\n\r" " \t"))
903 (num (abs (or n
1))))
904 (skip-chars-backward (if preserve-nl-back
" \t" skip-characters
))
905 (constrain-to-field nil orig-pos
)
907 ;; Command run for the first time, single-shot mode or different argument
908 ((or (eq 'single-shot mode
)
909 (not (equal last-command this-command
))
910 (not cycle-spacing--context
)
911 (not (eq (car cycle-spacing--context
) n
)))
912 (let* ((start (point))
913 (num (- num
(skip-chars-forward " " (+ num
(point)))))
916 (skip-chars-forward skip-characters
)
917 (constrain-to-field nil orig-pos t
))))
918 (setq cycle-spacing--context
;; Save for later.
919 ;; Special handling for case where there was no space at all.
920 (unless (= start end
)
921 (cons n
(cons orig-pos
(buffer-substring start
(point))))))
922 ;; If this run causes no change in buffer content, delete all spaces,
923 ;; otherwise delete all excess spaces.
924 (delete-region (if (and (eq mode
'fast
) (zerop num
) (= mid end
))
926 (insert (make-string num ?\s
))))
928 ;; Command run for the second time.
929 ((not (equal orig-pos
(point)))
930 (delete-region (point) orig-pos
))
932 ;; Command run for the third time.
934 (insert (cddr cycle-spacing--context
))
935 (goto-char (cadr cycle-spacing--context
))
936 (setq cycle-spacing--context nil
)))))
938 (defun beginning-of-buffer (&optional arg
)
939 "Move point to the beginning of the buffer.
940 With numeric arg N, put point N/10 of the way from the beginning.
941 If the buffer is narrowed, this command uses the beginning of the
942 accessible part of the buffer.
944 Push mark at previous position, unless either a \\[universal-argument] prefix
945 is supplied, or Transient Mark mode is enabled and the mark is active."
946 (declare (interactive-only "use `(goto-char (point-min))' instead."))
951 (let ((size (- (point-max) (point-min))))
952 (goto-char (if (and arg
(not (consp arg
)))
955 ;; Avoid overflow for large buffer sizes!
956 (* (prefix-numeric-value arg
)
958 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
960 (if (and arg
(not (consp arg
))) (forward-line 1)))
962 (defun end-of-buffer (&optional arg
)
963 "Move point to the end of the buffer.
964 With numeric arg N, put point N/10 of the way from the end.
965 If the buffer is narrowed, this command uses the end of the
966 accessible part of the buffer.
968 Push mark at previous position, unless either a \\[universal-argument] prefix
969 is supplied, or Transient Mark mode is enabled and the mark is active."
970 (declare (interactive-only "use `(goto-char (point-max))' instead."))
972 (or (consp arg
) (region-active-p) (push-mark))
973 (let ((size (- (point-max) (point-min))))
974 (goto-char (if (and arg
(not (consp arg
)))
977 ;; Avoid overflow for large buffer sizes!
978 (* (prefix-numeric-value arg
)
980 (/ (* size
(prefix-numeric-value arg
)) 10)))
982 ;; If we went to a place in the middle of the buffer,
983 ;; adjust it to the beginning of a line.
984 (cond ((and arg
(not (consp arg
))) (forward-line 1))
985 ((and (eq (current-buffer) (window-buffer))
986 (> (point) (window-end nil t
)))
987 ;; If the end of the buffer is not already on the screen,
988 ;; then scroll specially to put it near, but not at, the bottom.
989 (overlay-recenter (point))
992 (defcustom delete-active-region t
993 "Whether single-char deletion commands delete an active region.
994 This has an effect only if Transient Mark mode is enabled, and
995 affects `delete-forward-char' and `delete-backward-char', though
998 If the value is the symbol `kill', the active region is killed
1000 :type
'(choice (const :tag
"Delete active region" t
)
1001 (const :tag
"Kill active region" kill
)
1002 (const :tag
"Do ordinary deletion" nil
))
1006 (defvar region-extract-function
1008 (when (region-beginning)
1010 ((eq method
'bounds
)
1011 (list (cons (region-beginning) (region-end))))
1012 ((eq method
'delete-only
)
1013 (delete-region (region-beginning) (region-end)))
1015 (filter-buffer-substring (region-beginning) (region-end) method
)))))
1016 "Function to get the region's content.
1017 Called with one argument METHOD.
1018 If METHOD is `delete-only', then delete the region; the return value
1019 is undefined. If METHOD is nil, then return the content as a string.
1020 If METHOD is `bounds', then return the boundaries of the region
1021 as a list of cons cells of the form (START . END).
1022 If METHOD is anything else, delete the region and return its content
1023 as a string, after filtering it with `filter-buffer-substring', which
1024 is called with METHOD as its 3rd argument.")
1026 (defvar region-insert-function
1032 (insert-for-yank (car lines
))
1033 (setq lines
(cdr lines
)
1035 "Function to insert the region's content.
1036 Called with one argument LINES.
1037 Insert the region as a list of lines.")
1039 (defun delete-backward-char (n &optional killflag
)
1040 "Delete the previous N characters (following if N is negative).
1041 If Transient Mark mode is enabled, the mark is active, and N is 1,
1042 delete the text in the region and deactivate the mark instead.
1043 To disable this, set option `delete-active-region' to nil.
1045 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1046 kill ring) instead of delete. Interactively, N is the prefix
1047 arg, and KILLFLAG is set if N is explicitly specified.
1049 When killing, the killed text is filtered by
1050 `filter-buffer-substring' before it is saved in the kill ring, so
1051 the actual saved text might be different from what was killed.
1053 In Overwrite mode, single character backward deletion may replace
1054 tabs with spaces so as to back over columns, unless point is at
1055 the end of the line."
1056 (declare (interactive-only delete-char
))
1057 (interactive "p\nP")
1058 (unless (integerp n
)
1059 (signal 'wrong-type-argument
(list 'integerp n
)))
1060 (cond ((and (use-region-p)
1061 delete-active-region
1063 ;; If a region is active, kill or delete it.
1064 (if (eq delete-active-region
'kill
)
1065 (kill-region (region-beginning) (region-end) 'region
)
1066 (funcall region-extract-function
'delete-only
)))
1067 ;; In Overwrite mode, maybe untabify while deleting
1068 ((null (or (null overwrite-mode
)
1070 (memq (char-before) '(?
\t ?
\n))
1072 (eq (char-after) ?
\n)))
1073 (let ((ocol (current-column)))
1074 (delete-char (- n
) killflag
)
1076 (insert-char ?\s
(- ocol
(current-column)) nil
))))
1077 ;; Otherwise, do simple deletion.
1078 (t (delete-char (- n
) killflag
))))
1080 (defun delete-forward-char (n &optional killflag
)
1081 "Delete the following N characters (previous if N is negative).
1082 If Transient Mark mode is enabled, the mark is active, and N is 1,
1083 delete the text in the region and deactivate the mark instead.
1084 To disable this, set variable `delete-active-region' to nil.
1086 Optional second arg KILLFLAG non-nil means to kill (save in kill
1087 ring) instead of delete. Interactively, N is the prefix arg, and
1088 KILLFLAG is set if N was explicitly specified.
1090 When killing, the killed text is filtered by
1091 `filter-buffer-substring' before it is saved in the kill ring, so
1092 the actual saved text might be different from what was killed."
1093 (declare (interactive-only delete-char
))
1094 (interactive "p\nP")
1095 (unless (integerp n
)
1096 (signal 'wrong-type-argument
(list 'integerp n
)))
1097 (cond ((and (use-region-p)
1098 delete-active-region
1100 ;; If a region is active, kill or delete it.
1101 (if (eq delete-active-region
'kill
)
1102 (kill-region (region-beginning) (region-end) 'region
)
1103 (funcall region-extract-function
'delete-only
)))
1105 ;; Otherwise, do simple deletion.
1106 (t (delete-char n killflag
))))
1108 (defun mark-whole-buffer ()
1109 "Put point at beginning and mark at end of buffer.
1110 If narrowing is in effect, only uses the accessible part of the buffer.
1111 You probably should not use this function in Lisp programs;
1112 it is usually a mistake for a Lisp function to use any subroutine
1113 that uses or sets the mark."
1114 (declare (interactive-only t
))
1117 (push-mark (point-max) nil t
)
1118 ;; This is really `point-min' in most cases, but if we're in the
1119 ;; minibuffer, this is at the end of the prompt.
1120 (goto-char (minibuffer-prompt-end)))
1123 ;; Counting lines, one way or another.
1125 (defun goto-line (line &optional buffer
)
1126 "Go to LINE, counting from line 1 at beginning of buffer.
1127 If called interactively, a numeric prefix argument specifies
1128 LINE; without a numeric prefix argument, read LINE from the
1131 If optional argument BUFFER is non-nil, switch to that buffer and
1132 move to line LINE there. If called interactively with \\[universal-argument]
1133 as argument, BUFFER is the most recently selected other buffer.
1135 Prior to moving point, this function sets the mark (without
1136 activating it), unless Transient Mark mode is enabled and the
1137 mark is already active.
1139 This function is usually the wrong thing to use in a Lisp program.
1140 What you probably want instead is something like:
1141 (goto-char (point-min))
1142 (forward-line (1- N))
1143 If at all possible, an even better solution is to use char counts
1144 rather than line counts."
1145 (declare (interactive-only forward-line
))
1147 (if (and current-prefix-arg
(not (consp current-prefix-arg
)))
1148 (list (prefix-numeric-value current-prefix-arg
))
1149 ;; Look for a default, a number in the buffer at point.
1152 (skip-chars-backward "0-9")
1153 (if (looking-at "[0-9]")
1155 (buffer-substring-no-properties
1157 (progn (skip-chars-forward "0-9")
1159 ;; Decide if we're switching buffers.
1161 (if (consp current-prefix-arg
)
1162 (other-buffer (current-buffer) t
)))
1165 (concat " in " (buffer-name buffer
))
1167 ;; Read the argument, offering that number (if any) as default.
1168 (list (read-number (format "Goto line%s: " buffer-prompt
)
1169 (list default
(line-number-at-pos)))
1171 ;; Switch to the desired buffer, one way or another.
1173 (let ((window (get-buffer-window buffer
)))
1174 (if window
(select-window window
)
1175 (switch-to-buffer-other-window buffer
))))
1176 ;; Leave mark at previous position
1177 (or (region-active-p) (push-mark))
1178 ;; Move to the specified line number in that buffer.
1181 (goto-char (point-min))
1182 (if (eq selective-display t
)
1183 (re-search-forward "[\n\C-m]" nil
'end
(1- line
))
1184 (forward-line (1- line
)))))
1186 (defun count-words-region (start end
&optional arg
)
1187 "Count the number of words in the region.
1188 If called interactively, print a message reporting the number of
1189 lines, words, and characters in the region (whether or not the
1190 region is active); with prefix ARG, report for the entire buffer
1191 rather than the region.
1193 If called from Lisp, return the number of words between positions
1195 (interactive (if current-prefix-arg
1196 (list nil nil current-prefix-arg
)
1197 (list (region-beginning) (region-end) nil
)))
1198 (cond ((not (called-interactively-p 'any
))
1199 (count-words start end
))
1201 (count-words--buffer-message))
1203 (count-words--message "Region" start end
))))
1205 (defun count-words (start end
)
1206 "Count words between START and END.
1207 If called interactively, START and END are normally the start and
1208 end of the buffer; but if the region is active, START and END are
1209 the start and end of the region. Print a message reporting the
1210 number of lines, words, and chars.
1212 If called from Lisp, return the number of words between START and
1213 END, without printing any message."
1214 (interactive (list nil nil
))
1215 (cond ((not (called-interactively-p 'any
))
1219 (narrow-to-region start end
)
1220 (goto-char (point-min))
1221 (while (forward-word-strictly 1)
1222 (setq words
(1+ words
)))))
1225 (call-interactively 'count-words-region
))
1227 (count-words--buffer-message))))
1229 (defun count-words--buffer-message ()
1230 (count-words--message
1231 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1232 (point-min) (point-max)))
1234 (defun count-words--message (str start end
)
1235 (let ((lines (count-lines start end
))
1236 (words (count-words start end
))
1237 (chars (- end start
)))
1238 (message "%s has %d line%s, %d word%s, and %d character%s."
1240 lines
(if (= lines
1) "" "s")
1241 words
(if (= words
1) "" "s")
1242 chars
(if (= chars
1) "" "s"))))
1244 (define-obsolete-function-alias 'count-lines-region
'count-words-region
"24.1")
1247 "Print the current buffer line number and narrowed line number of point."
1249 (let ((start (point-min))
1250 (n (line-number-at-pos)))
1252 (message "Line %d" n
)
1256 (message "line %d (narrowed line %d)"
1257 (+ n
(line-number-at-pos start
) -
1) n
))))))
1259 (defun count-lines (start end
)
1260 "Return number of lines between START and END.
1261 This is usually the number of newlines between them,
1262 but can be one more if START is not equal to END
1263 and the greater of them is not at the start of a line."
1266 (narrow-to-region start end
)
1267 (goto-char (point-min))
1268 (if (eq selective-display t
)
1271 (while (re-search-forward "[\n\C-m]" nil t
40)
1272 (setq done
(+ 40 done
)))
1273 (while (re-search-forward "[\n\C-m]" nil t
1)
1274 (setq done
(+ 1 done
)))
1275 (goto-char (point-max))
1276 (if (and (/= start end
)
1280 (- (buffer-size) (forward-line (buffer-size)))))))
1282 (defun line-number-at-pos (&optional pos absolute
)
1283 "Return buffer line number at position POS.
1284 If POS is nil, use current buffer location.
1286 If ABSOLUTE is nil, the default, counting starts
1287 at (point-min), so the value refers to the contents of the
1288 accessible portion of the (potentially narrowed) buffer. If
1289 ABSOLUTE is non-nil, ignore any narrowing and return the
1290 absolute line number."
1294 (let ((opoint (or pos
(point))) start
)
1296 (goto-char (point-min))
1297 (setq start
(point))
1300 (1+ (count-lines start
(point)))))))
1302 (defun what-cursor-position (&optional detail
)
1303 "Print info on cursor position (on screen and within buffer).
1304 Also describe the character after point, and give its character code
1305 in octal, decimal and hex.
1307 For a non-ASCII multibyte character, also give its encoding in the
1308 buffer's selected coding system if the coding system encodes the
1309 character safely. If the character is encoded into one byte, that
1310 code is shown in hex. If the character is encoded into more than one
1311 byte, just \"...\" is shown.
1313 In addition, with prefix argument, show details about that character
1314 in *Help* buffer. See also the command `describe-char'."
1316 (let* ((char (following-char))
1318 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1319 ;; start a directional embedding, which could completely
1320 ;; disrupt the rest of the line (e.g., RLO will display the
1321 ;; rest of the line right-to-left). So we put an invisible
1322 ;; PDF character after these characters, to end the
1323 ;; embedding, which eliminates any effects on the rest of
1324 ;; the line. For RLE and RLO we also append an invisible
1325 ;; LRM, to avoid reordering the following numerical
1326 ;; characters. For LRI/RLI/FSI we append a PDI.
1327 (cond ((memq char
'(?
\x202a ?
\x202d
))
1328 (propertize (string ?
\x202c
) 'invisible t
))
1329 ((memq char
'(?
\x202b ?
\x202e
))
1330 (propertize (string ?
\x202c ?
\x200e
) 'invisible t
))
1331 ((memq char
'(?
\x2066 ?
\x2067 ?
\x2068
))
1332 (propertize (string ?
\x2069
) 'invisible t
))
1333 ;; Strong right-to-left characters cause reordering of
1334 ;; the following numerical characters which show the
1335 ;; codepoint, so append LRM to countermand that.
1336 ((memq (get-char-code-property char
'bidi-class
) '(R AL
))
1337 (propertize (string ?
\x200e
) 'invisible t
))
1343 (total (buffer-size))
1344 (percent (round (* 100.0 (1- pos
)) (max 1 total
)))
1345 (hscroll (if (= (window-hscroll) 0)
1347 (format " Hscroll=%d" (window-hscroll))))
1348 (col (current-column)))
1350 (if (or (/= beg
1) (/= end
(1+ total
)))
1351 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1352 pos total percent beg end col hscroll
)
1353 (message "point=%d of %d (EOB) column=%d%s"
1354 pos total col hscroll
))
1355 (let ((coding buffer-file-coding-system
)
1356 encoded encoding-msg display-prop under-display
)
1357 (if (or (not coding
)
1358 (eq (coding-system-type coding
) t
))
1359 (setq coding
(default-value 'buffer-file-coding-system
)))
1360 (if (eq (char-charset char
) 'eight-bit
)
1362 (format "(%d, #o%o, #x%x, raw-byte)" char char char
))
1363 ;; Check if the character is displayed with some `display'
1364 ;; text property. In that case, set under-display to the
1365 ;; buffer substring covered by that property.
1366 (setq display-prop
(get-char-property pos
'display
))
1368 (let ((to (or (next-single-char-property-change pos
'display
)
1370 (if (< to
(+ pos
4))
1371 (setq under-display
"")
1372 (setq under-display
"..."
1375 (concat (buffer-substring-no-properties pos to
)
1377 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
1380 (if (not (stringp display-prop
))
1381 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1382 char char char under-display
)
1383 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1384 char char char under-display display-prop
))
1386 (format "(%d, #o%o, #x%x, file %s)"
1388 (if (> (length encoded
) 1)
1390 (encoded-string-description encoded coding
)))
1391 (format "(%d, #o%o, #x%x)" char char char
)))))
1393 ;; We show the detailed information about CHAR.
1394 (describe-char (point)))
1395 (if (or (/= beg
1) (/= end
(1+ total
)))
1396 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1398 (single-key-description char
)
1399 (buffer-substring-no-properties (point) (1+ (point))))
1401 encoding-msg pos total percent beg end col hscroll
)
1402 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1403 (if enable-multibyte-characters
1405 (single-key-description char
)
1406 (buffer-substring-no-properties (point) (1+ (point))))
1407 (single-key-description char
))
1408 bidi-fixer encoding-msg pos total percent col hscroll
))))))
1410 ;; Initialize read-expression-map. It is defined at C level.
1411 (defvar read-expression-map
1412 (let ((m (make-sparse-keymap)))
1413 (define-key m
"\M-\t" 'completion-at-point
)
1414 ;; Might as well bind TAB to completion, since inserting a TAB char is
1415 ;; much too rarely useful.
1416 (define-key m
"\t" 'completion-at-point
)
1417 (set-keymap-parent m minibuffer-local-map
)
1420 (defun read-minibuffer (prompt &optional initial-contents
)
1421 "Return a Lisp object read using the minibuffer, unevaluated.
1422 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1423 is a string to insert in the minibuffer before reading.
1424 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1425 Such arguments are used as in `read-from-minibuffer'.)"
1426 ;; Used for interactive spec `x'.
1427 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1428 t
'minibuffer-history
))
1430 (defun eval-minibuffer (prompt &optional initial-contents
)
1431 "Return value of Lisp expression read using the minibuffer.
1432 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1433 is a string to insert in the minibuffer before reading.
1434 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1435 Such arguments are used as in `read-from-minibuffer'.)"
1436 ;; Used for interactive spec `X'.
1437 (eval (read--expression prompt initial-contents
)))
1439 (defvar minibuffer-completing-symbol nil
1440 "Non-nil means completing a Lisp symbol in the minibuffer.")
1441 (make-obsolete-variable 'minibuffer-completing-symbol nil
"24.1" 'get
)
1443 (defvar minibuffer-default nil
1444 "The current default value or list of default values in the minibuffer.
1445 The functions `read-from-minibuffer' and `completing-read' bind
1446 this variable locally.")
1448 (defcustom eval-expression-print-level
4
1449 "Value for `print-level' while printing value in `eval-expression'.
1450 A value of nil means no limit."
1452 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1455 (defcustom eval-expression-print-length
12
1456 "Value for `print-length' while printing value in `eval-expression'.
1457 A value of nil means no limit."
1459 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1462 (defcustom eval-expression-debug-on-error t
1463 "If non-nil set `debug-on-error' to t in `eval-expression'.
1464 If nil, don't change the value of `debug-on-error'."
1469 (defcustom eval-expression-print-maximum-character
127
1470 "The largest integer that will be displayed as a character.
1471 This affects printing by `eval-expression' (via
1472 `eval-expression-print-format')."
1477 (defun eval-expression-print-format (value)
1478 "If VALUE in an integer, return a specially formatted string.
1479 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1480 If VALUE is not an integer, nil is returned.
1481 This function is used by commands like `eval-expression' that
1482 display the result of expression evaluation."
1483 (when (integerp value
)
1485 (and (characterp value
)
1486 (<= value eval-expression-print-maximum-character
)
1487 (char-displayable-p value
)
1488 (prin1-char value
))))
1490 (format " (#o%o, #x%x, %s)" value value char-string
)
1491 (format " (#o%o, #x%x)" value value
)))))
1493 (defvar eval-expression-minibuffer-setup-hook nil
1494 "Hook run by `eval-expression' when entering the minibuffer.")
1496 (defun read--expression (prompt &optional initial-contents
)
1497 (let ((minibuffer-completing-symbol t
))
1498 (minibuffer-with-setup-hook
1500 ;; FIXME: call emacs-lisp-mode?
1501 (add-function :before-until
(local 'eldoc-documentation-function
)
1502 #'elisp-eldoc-documentation-function
)
1504 (add-hook 'completion-at-point-functions
1505 #'elisp-completion-at-point nil t
)
1506 (run-hooks 'eval-expression-minibuffer-setup-hook
))
1507 (read-from-minibuffer prompt initial-contents
1508 read-expression-map t
1509 'read-expression-history
))))
1511 (defun eval-expression-get-print-arguments (prefix-argument)
1512 "Get arguments for commands that print an expression result.
1513 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1514 based on PREFIX-ARG. This function determines the interpretation
1515 of the prefix argument for `eval-expression' and
1517 (let ((num (prefix-numeric-value prefix-argument
)))
1518 (list (not (memq prefix-argument
'(- nil
)))
1520 (cond ((not (memq prefix-argument
'(0 -
1 - nil
))) nil
)
1521 ((= num -
1) most-positive-fixnum
)
1522 (t eval-expression-print-maximum-character
)))))
1524 ;; We define this, rather than making `eval' interactive,
1525 ;; for the sake of completion of names like eval-region, eval-buffer.
1526 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit
)
1527 "Evaluate EXP and print value in the echo area.
1528 When called interactively, read an Emacs Lisp expression and
1529 evaluate it. Value is also consed on to front of the variable
1530 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1531 with a non `-' prefix argument) means insert the result into the
1532 current buffer instead of printing it in the echo area.
1534 Normally, this function truncates long output according to the
1535 value of the variables `eval-expression-print-length' and
1536 `eval-expression-print-level'. When NO-TRUNCATE is
1537 non-nil (interactively, with a prefix argument of zero), however,
1538 there is no such truncation.
1540 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1541 non-nil (interactively, unless given a positive prefix argument)
1542 it will be printed in several additional formats (octal,
1543 hexadecimal, and character). The character format is only used
1544 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1545 prefix argument is -1 or the value is below
1546 `eval-expression-print-maximum-character').
1548 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1551 If `eval-expression-debug-on-error' is non-nil, which is the default,
1552 this command arranges for all errors to enter the debugger."
1554 (cons (read--expression "Eval: ")
1555 (eval-expression-get-print-arguments current-prefix-arg
)))
1557 (if (null eval-expression-debug-on-error
)
1558 (push (eval exp lexical-binding
) values
)
1559 (let ((old-value (make-symbol "t")) new-value
)
1560 ;; Bind debug-on-error to something unique so that we can
1561 ;; detect when evalled code changes it.
1562 (let ((debug-on-error old-value
))
1563 (push (eval (macroexpand-all exp
) lexical-binding
) values
)
1564 (setq new-value debug-on-error
))
1565 ;; If evalled code has changed the value of debug-on-error,
1566 ;; propagate that change to the global binding.
1567 (unless (eq old-value new-value
)
1568 (setq debug-on-error new-value
))))
1570 (let ((print-length (unless no-truncate eval-expression-print-length
))
1571 (print-level (unless no-truncate eval-expression-print-level
))
1572 (eval-expression-print-maximum-character char-print-limit
)
1574 (let ((out (if insert-value
(current-buffer) t
)))
1576 (prin1 (car values
) out
)
1577 (let ((str (and char-print-limit
1578 (eval-expression-print-format (car values
)))))
1579 (when str
(princ str out
)))))))
1581 (defun edit-and-eval-command (prompt command
)
1582 "Prompting with PROMPT, let user edit COMMAND and eval result.
1583 COMMAND is a Lisp expression. Let user edit that expression in
1584 the minibuffer, then read and evaluate the result."
1586 (let ((print-level nil
)
1587 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1589 (read-from-minibuffer prompt
1590 (prin1-to-string command
)
1591 read-expression-map t
1593 ;; If command was added to command-history as a string,
1594 ;; get rid of that. We want only evaluable expressions there.
1595 (if (stringp (car command-history
))
1596 (setq command-history
(cdr command-history
)))))))
1598 ;; If command to be redone does not match front of history,
1599 ;; add it to the history.
1600 (or (equal command
(car command-history
))
1601 (setq command-history
(cons command command-history
)))
1604 (defun repeat-complex-command (arg)
1605 "Edit and re-evaluate last complex command, or ARGth from last.
1606 A complex command is one which used the minibuffer.
1607 The command is placed in the minibuffer as a Lisp form for editing.
1608 The result is executed, repeating the command as changed.
1609 If the command has been changed or is not the most recent previous
1610 command it is added to the front of the command history.
1611 You can use the minibuffer history commands \
1612 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1613 to get different commands to edit and resubmit."
1615 (let ((elt (nth (1- arg
) command-history
))
1620 (let ((print-level nil
)
1621 (minibuffer-history-position arg
)
1622 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1624 (read-from-minibuffer
1625 "Redo: " (prin1-to-string elt
) read-expression-map t
1626 (cons 'command-history arg
))
1628 ;; If command was added to command-history as a
1629 ;; string, get rid of that. We want only
1630 ;; evaluable expressions there.
1631 (if (stringp (car command-history
))
1632 (setq command-history
(cdr command-history
))))))
1634 ;; If command to be redone does not match front of history,
1635 ;; add it to the history.
1636 (or (equal newcmd
(car command-history
))
1637 (setq command-history
(cons newcmd command-history
)))
1638 (apply #'funcall-interactively
1640 (mapcar (lambda (e) (eval e t
)) (cdr newcmd
))))
1642 (error "Argument %d is beyond length of command history" arg
)
1643 (error "There are no previous complex commands to repeat")))))
1646 (defvar extended-command-history nil
)
1647 (defvar execute-extended-command--last-typed nil
)
1649 (defun read-extended-command ()
1650 "Read command name to invoke in `execute-extended-command'."
1651 (minibuffer-with-setup-hook
1653 (add-hook 'post-self-insert-hook
1655 (setq execute-extended-command--last-typed
1656 (minibuffer-contents)))
1658 (set (make-local-variable 'minibuffer-default-add-function
)
1660 ;; Get a command name at point in the original buffer
1661 ;; to propose it after M-n.
1662 (with-current-buffer (window-buffer (minibuffer-selected-window))
1663 (and (commandp (function-called-at-point))
1664 (format "%S" (function-called-at-point)))))))
1665 ;; Read a string, completing from and restricting to the set of
1666 ;; all defined commands. Don't provide any initial input.
1667 ;; Save the command read on the extended-command history list.
1670 ((eq current-prefix-arg
'-
) "- ")
1671 ((and (consp current-prefix-arg
)
1672 (eq (car current-prefix-arg
) 4)) "C-u ")
1673 ((and (consp current-prefix-arg
)
1674 (integerp (car current-prefix-arg
)))
1675 (format "%d " (car current-prefix-arg
)))
1676 ((integerp current-prefix-arg
)
1677 (format "%d " current-prefix-arg
)))
1678 ;; This isn't strictly correct if `execute-extended-command'
1679 ;; is bound to anything else (e.g. [menu]).
1680 ;; It could use (key-description (this-single-command-keys)),
1681 ;; but actually a prompt other than "M-x" would be confusing,
1682 ;; because "M-x" is a well-known prompt to read a command
1683 ;; and it serves as a shorthand for "Extended command: ".
1685 (lambda (string pred action
)
1687 (if (memq action
'(nil t
))
1688 ;; Exclude obsolete commands from completions.
1690 (and (funcall pred sym
)
1691 (or (equal string
(symbol-name sym
))
1692 (not (get sym
'byte-obsolete-info
)))))
1694 (complete-with-action action obarray string pred
)))
1695 #'commandp t nil
'extended-command-history
)))
1697 (defcustom suggest-key-bindings t
1698 "Non-nil means show the equivalent key-binding when M-x command has one.
1699 The value can be a length of time to show the message for.
1700 If the value is non-nil and not a number, we wait 2 seconds."
1702 :type
'(choice (const :tag
"off" nil
)
1703 (integer :tag
"time" 2)
1706 (defcustom extended-command-suggest-shorter t
1707 "If non-nil, show a shorter M-x invocation when there is one."
1712 (defun execute-extended-command--shorter-1 (name length
)
1714 ((zerop length
) (list ""))
1715 ((equal name
"") nil
)
1717 (nconc (mapcar (lambda (s) (concat (substring name
0 1) s
))
1718 (execute-extended-command--shorter-1
1719 (substring name
1) (1- length
)))
1720 (when (string-match "\\`\\(-\\)?[^-]*" name
)
1721 (execute-extended-command--shorter-1
1722 (substring name
(match-end 0)) length
))))))
1724 (defun execute-extended-command--shorter (name typed
)
1725 (let ((candidates '())
1726 (max (length typed
))
1729 (while (and (not binding
)
1733 (setq candidates
(execute-extended-command--shorter-1
1735 ;; Don't show the help message if the binding isn't
1736 ;; significantly shorter than the M-x command the user typed.
1738 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1739 (let ((candidate (pop candidates
)))
1741 (car-safe (completion-try-completion
1742 candidate obarray
'commandp len
)))
1743 (setq binding candidate
))))
1746 (defun execute-extended-command (prefixarg &optional command-name typed
)
1747 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1748 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1749 "Read a command name, then read the arguments and call the command.
1750 To pass a prefix argument to the command you are
1751 invoking, give a prefix argument to `execute-extended-command'."
1752 (declare (interactive-only command-execute
))
1753 ;; FIXME: Remember the actual text typed by the user before completion,
1754 ;; so that we don't later on suggest the same shortening.
1756 (let ((execute-extended-command--last-typed nil
))
1757 (list current-prefix-arg
1758 (read-extended-command)
1759 execute-extended-command--last-typed
)))
1760 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1761 (unless command-name
1762 (let ((current-prefix-arg prefixarg
) ; for prompt
1763 (execute-extended-command--last-typed nil
))
1764 (setq command-name
(read-extended-command))
1765 (setq typed execute-extended-command--last-typed
)))
1766 (let* ((function (and (stringp command-name
) (intern-soft command-name
)))
1767 (binding (and suggest-key-bindings
1768 (not executing-kbd-macro
)
1769 (where-is-internal function overriding-local-map t
))))
1770 (unless (commandp function
)
1771 (error "`%s' is not a valid command name" command-name
))
1772 ;; Some features, such as novice.el, rely on this-command-keys
1773 ;; including M-x COMMAND-NAME RET.
1774 (set--this-command-keys (concat "\M-x" (symbol-name function
) "\r"))
1775 (setq this-command function
)
1776 ;; Normally `real-this-command' should never be changed, but here we really
1777 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1778 ;; binding" for <cmd>, so the command the user really wanted to run is
1779 ;; `function' and not `execute-extended-command'. The difference is
1780 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1781 (setq real-this-command function
)
1782 (let ((prefix-arg prefixarg
))
1783 (command-execute function
'record
))
1784 ;; If enabled, show which key runs this command.
1785 ;; But first wait, and skip the message if there is input.
1787 ;; If this command displayed something in the echo area;
1788 ;; wait a few seconds, then display our suggestion message.
1789 ;; FIXME: Wait *after* running post-command-hook!
1790 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1791 ;; find a better answer anyway!
1792 (when suggest-key-bindings
1794 ((zerop (length (current-message))) 0)
1795 ((numberp suggest-key-bindings
) suggest-key-bindings
)
1797 (when (and waited
(not (consp unread-command-events
)))
1798 (unless (or (not extended-command-suggest-shorter
)
1799 binding executing-kbd-macro
(not (symbolp function
))
1800 (<= (length (symbol-name function
)) 2))
1801 ;; There's no binding for CMD. Let's try and find the shortest
1802 ;; string to use in M-x.
1803 ;; FIXME: Can be slow. Cache it maybe?
1805 (setq binding
(execute-extended-command--shorter
1806 (symbol-name function
) typed
))))
1809 (format-message "You can run the command `%s' with %s"
1811 (if (stringp binding
)
1812 (concat "M-x " binding
" RET")
1813 (key-description binding
)))
1814 (sit-for (if (numberp suggest-key-bindings
)
1815 suggest-key-bindings
1818 (defun command-execute (cmd &optional record-flag keys special
)
1819 ;; BEWARE: Called directly from the C code.
1820 "Execute CMD as an editor command.
1821 CMD must be a symbol that satisfies the `commandp' predicate.
1822 Optional second arg RECORD-FLAG non-nil
1823 means unconditionally put this command in the variable `command-history'.
1824 Otherwise, that is done only if an arg is read using the minibuffer.
1825 The argument KEYS specifies the value to use instead of (this-command-keys)
1826 when reading the arguments; if it is nil, (this-command-keys) is used.
1827 The argument SPECIAL, if non-nil, means that this command is executing
1828 a special event, so ignore the prefix argument and don't clear it."
1829 (setq debug-on-next-call nil
)
1830 (let ((prefixarg (unless special
1831 ;; FIXME: This should probably be done around
1832 ;; pre-command-hook rather than here!
1834 (setq current-prefix-arg prefix-arg
)
1835 (setq prefix-arg nil
)
1836 (when current-prefix-arg
1837 (prefix-command-update))))))
1838 (if (and (symbolp cmd
)
1840 disabled-command-function
)
1841 ;; FIXME: Weird calling convention!
1842 (run-hooks 'disabled-command-function
)
1846 (setq final
(indirect-function final
))
1847 (if (autoloadp final
)
1848 (setq final
(autoload-do-load final cmd
)))))
1851 ;; If requested, place the macro in the command history. For
1852 ;; other sorts of commands, call-interactively takes care of this.
1854 (push `(execute-kbd-macro ,final
,prefixarg
) command-history
)
1855 ;; Don't keep command history around forever.
1856 (when (and (numberp history-length
) (> history-length
0))
1857 (let ((cell (nthcdr history-length command-history
)))
1858 (if (consp cell
) (setcdr cell nil
)))))
1859 (execute-kbd-macro final prefixarg
))
1861 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1862 (prog1 (call-interactively cmd record-flag keys
)
1863 (when (and (symbolp cmd
)
1864 (get cmd
'byte-obsolete-info
)
1865 (not (get cmd
'command-execute-obsolete-warned
)))
1866 (put cmd
'command-execute-obsolete-warned t
)
1867 (message "%s" (macroexp--obsolete-warning
1868 cmd
(get cmd
'byte-obsolete-info
) "command"))))))))))
1870 (defvar minibuffer-history nil
1871 "Default minibuffer history list.
1872 This is used for all minibuffer input
1873 except when an alternate history list is specified.
1875 Maximum length of the history list is determined by the value
1876 of `history-length', which see.")
1877 (defvar minibuffer-history-sexp-flag nil
1878 "Control whether history list elements are expressions or strings.
1879 If the value of this variable equals current minibuffer depth,
1880 they are expressions; otherwise they are strings.
1881 \(That convention is designed to do the right thing for
1882 recursive uses of the minibuffer.)")
1883 (setq minibuffer-history-variable
'minibuffer-history
)
1884 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1885 (defvar minibuffer-history-search-history nil
)
1887 (defvar minibuffer-text-before-history nil
1888 "Text that was in this minibuffer before any history commands.
1889 This is nil if there have not yet been any history commands
1890 in this use of the minibuffer.")
1892 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1894 (defun minibuffer-history-initialize ()
1895 (setq minibuffer-text-before-history nil
))
1897 (defun minibuffer-avoid-prompt (_new _old
)
1898 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1899 (declare (obsolete cursor-intangible-mode
"25.1"))
1900 (constrain-to-field nil
(point-max)))
1902 (defcustom minibuffer-history-case-insensitive-variables nil
1903 "Minibuffer history variables for which matching should ignore case.
1904 If a history variable is a member of this list, then the
1905 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1906 commands ignore case when searching it, regardless of `case-fold-search'."
1907 :type
'(repeat variable
)
1910 (defun previous-matching-history-element (regexp n
)
1911 "Find the previous history element that matches REGEXP.
1912 \(Previous history elements refer to earlier actions.)
1913 With prefix argument N, search for Nth previous match.
1914 If N is negative, find the next or Nth next match.
1915 Normally, history elements are matched case-insensitively if
1916 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1917 makes the search case-sensitive.
1918 See also `minibuffer-history-case-insensitive-variables'."
1920 (let* ((enable-recursive-minibuffers t
)
1921 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1923 minibuffer-local-map
1925 'minibuffer-history-search-history
1926 (car minibuffer-history-search-history
))))
1927 ;; Use the last regexp specified, by default, if input is empty.
1928 (list (if (string= regexp
"")
1929 (if minibuffer-history-search-history
1930 (car minibuffer-history-search-history
)
1931 (user-error "No previous history search regexp"))
1933 (prefix-numeric-value current-prefix-arg
))))
1935 (if (and (zerop minibuffer-history-position
)
1936 (null minibuffer-text-before-history
))
1937 (setq minibuffer-text-before-history
1938 (minibuffer-contents-no-properties)))
1939 (let ((history (symbol-value minibuffer-history-variable
))
1941 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1942 ;; On some systems, ignore case for file names.
1943 (if (memq minibuffer-history-variable
1944 minibuffer-history-case-insensitive-variables
)
1946 ;; Respect the user's setting for case-fold-search:
1952 (pos minibuffer-history-position
))
1955 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1956 (when (= pos prevpos
)
1957 (user-error (if (= pos
1)
1958 "No later matching history item"
1959 "No earlier matching history item")))
1961 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1962 (let ((print-level nil
))
1963 (prin1-to-string (nth (1- pos
) history
)))
1964 (nth (1- pos
) history
)))
1967 (and (string-match regexp match-string
)
1969 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1970 (match-beginning 1))))
1972 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1973 (setq minibuffer-history-position pos
)
1974 (goto-char (point-max))
1975 (delete-minibuffer-contents)
1976 (insert match-string
)
1977 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1978 (if (memq (car (car command-history
)) '(previous-matching-history-element
1979 next-matching-history-element
))
1980 (setq command-history
(cdr command-history
))))
1982 (defun next-matching-history-element (regexp n
)
1983 "Find the next history element that matches REGEXP.
1984 \(The next history element refers to a more recent action.)
1985 With prefix argument N, search for Nth next match.
1986 If N is negative, find the previous or Nth previous match.
1987 Normally, history elements are matched case-insensitively if
1988 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1989 makes the search case-sensitive."
1991 (let* ((enable-recursive-minibuffers t
)
1992 (regexp (read-from-minibuffer "Next element matching (regexp): "
1994 minibuffer-local-map
1996 'minibuffer-history-search-history
1997 (car minibuffer-history-search-history
))))
1998 ;; Use the last regexp specified, by default, if input is empty.
1999 (list (if (string= regexp
"")
2000 (if minibuffer-history-search-history
2001 (car minibuffer-history-search-history
)
2002 (user-error "No previous history search regexp"))
2004 (prefix-numeric-value current-prefix-arg
))))
2005 (previous-matching-history-element regexp
(- n
)))
2007 (defvar minibuffer-temporary-goal-position nil
)
2009 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
2010 "Function run by `goto-history-element' before consuming default values.
2011 This is useful to dynamically add more elements to the list of default values
2012 when `goto-history-element' reaches the end of this list.
2013 Before calling this function `goto-history-element' sets the variable
2014 `minibuffer-default-add-done' to t, so it will call this function only
2015 once. In special cases, when this function needs to be called more
2016 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2017 overriding the setting of this variable to t in `goto-history-element'.")
2019 (defvar minibuffer-default-add-done nil
2020 "When nil, add more elements to the end of the list of default values.
2021 The value nil causes `goto-history-element' to add more elements to
2022 the list of defaults when it reaches the end of this list. It does
2023 this by calling a function defined by `minibuffer-default-add-function'.")
2025 (make-variable-buffer-local 'minibuffer-default-add-done
)
2027 (defun minibuffer-default-add-completions ()
2028 "Return a list of all completions without the default value.
2029 This function is used to add all elements of the completion table to
2030 the end of the list of defaults just after the default value."
2031 (let ((def minibuffer-default
)
2032 (all (all-completions ""
2033 minibuffer-completion-table
2034 minibuffer-completion-predicate
)))
2037 (cons def
(delete def all
)))))
2039 (defun goto-history-element (nabs)
2040 "Puts element of the minibuffer history in the minibuffer.
2041 The argument NABS specifies the absolute history position."
2043 (when (and (not minibuffer-default-add-done
)
2044 (functionp minibuffer-default-add-function
)
2045 (< nabs
(- (if (listp minibuffer-default
)
2046 (length minibuffer-default
)
2048 (setq minibuffer-default-add-done t
2049 minibuffer-default
(funcall minibuffer-default-add-function
)))
2050 (let ((minimum (if minibuffer-default
2051 (- (if (listp minibuffer-default
)
2052 (length minibuffer-default
)
2055 elt minibuffer-returned-to-present
)
2056 (if (and (zerop minibuffer-history-position
)
2057 (null minibuffer-text-before-history
))
2058 (setq minibuffer-text-before-history
2059 (minibuffer-contents-no-properties)))
2060 (if (< nabs minimum
)
2061 (user-error (if minibuffer-default
2062 "End of defaults; no next item"
2063 "End of history; no default available")))
2064 (if (> nabs
(if (listp (symbol-value minibuffer-history-variable
))
2065 (length (symbol-value minibuffer-history-variable
))
2067 (user-error "Beginning of history; no preceding item"))
2068 (unless (memq last-command
'(next-history-element
2069 previous-history-element
))
2070 (let ((prompt-end (minibuffer-prompt-end)))
2071 (set (make-local-variable 'minibuffer-temporary-goal-position
)
2072 (cond ((<= (point) prompt-end
) prompt-end
)
2075 (goto-char (point-max))
2076 (delete-minibuffer-contents)
2077 (setq minibuffer-history-position nabs
)
2079 (setq elt
(if (listp minibuffer-default
)
2080 (nth (1- (abs nabs
)) minibuffer-default
)
2081 minibuffer-default
)))
2083 (setq elt
(or minibuffer-text-before-history
""))
2084 (setq minibuffer-returned-to-present t
)
2085 (setq minibuffer-text-before-history nil
))
2086 (t (setq elt
(nth (1- minibuffer-history-position
)
2087 (symbol-value minibuffer-history-variable
)))))
2089 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
2090 (not minibuffer-returned-to-present
))
2091 (let ((print-level nil
))
2092 (prin1-to-string elt
))
2094 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
2096 (defun next-history-element (n)
2097 "Puts next element of the minibuffer history in the minibuffer.
2098 With argument N, it uses the Nth following element."
2101 (goto-history-element (- minibuffer-history-position n
))))
2103 (defun previous-history-element (n)
2104 "Puts previous element of the minibuffer history in the minibuffer.
2105 With argument N, it uses the Nth previous element."
2108 (goto-history-element (+ minibuffer-history-position n
))))
2110 (defun next-line-or-history-element (&optional arg
)
2111 "Move cursor vertically down ARG lines, or to the next history element.
2112 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2113 next element of the minibuffer history in the minibuffer."
2115 (or arg
(setq arg
1))
2116 (let* ((old-point (point))
2117 ;; Don't add newlines if they have the mode enabled globally.
2118 (next-line-add-newlines nil
)
2119 ;; Remember the original goal column of possibly multi-line input
2120 ;; excluding the length of the prompt on the first line.
2121 (prompt-end (minibuffer-prompt-end))
2122 (old-column (unless (and (eolp) (> (point) prompt-end
))
2123 (if (= (line-number-at-pos) 1)
2124 (max (- (current-column) (1- prompt-end
)) 0)
2125 (current-column)))))
2130 ;; Restore old position since `line-move-visual' moves point to
2131 ;; the end of the line when it fails to go to the next line.
2132 (goto-char old-point
)
2133 (next-history-element arg
)
2134 ;; Reset `temporary-goal-column' because a correct value is not
2135 ;; calculated when `next-line' above fails by bumping against
2136 ;; the bottom of the minibuffer (bug#22544).
2137 (setq temporary-goal-column
0)
2138 ;; Restore the original goal column on the last line
2139 ;; of possibly multi-line input.
2140 (goto-char (point-max))
2142 (if (= (line-number-at-pos) 1)
2143 (move-to-column (+ old-column
(1- (minibuffer-prompt-end))))
2144 (move-to-column old-column
)))))))
2146 (defun previous-line-or-history-element (&optional arg
)
2147 "Move cursor vertically up ARG lines, or to the previous history element.
2148 When point moves over the top line of multi-line minibuffer, puts ARGth
2149 previous element of the minibuffer history in the minibuffer."
2151 (or arg
(setq arg
1))
2152 (let* ((old-point (point))
2153 ;; Remember the original goal column of possibly multi-line input
2154 ;; excluding the length of the prompt on the first line.
2155 (prompt-end (minibuffer-prompt-end))
2156 (old-column (unless (and (eolp) (> (point) prompt-end
))
2157 (if (= (line-number-at-pos) 1)
2158 (max (- (current-column) (1- prompt-end
)) 0)
2159 (current-column)))))
2162 (previous-line arg
))
2163 (beginning-of-buffer
2164 ;; Restore old position since `line-move-visual' moves point to
2165 ;; the beginning of the line when it fails to go to the previous line.
2166 (goto-char old-point
)
2167 (previous-history-element arg
)
2168 ;; Reset `temporary-goal-column' because a correct value is not
2169 ;; calculated when `previous-line' above fails by bumping against
2170 ;; the top of the minibuffer (bug#22544).
2171 (setq temporary-goal-column
0)
2172 ;; Restore the original goal column on the first line
2173 ;; of possibly multi-line input.
2174 (goto-char (minibuffer-prompt-end))
2176 (if (= (line-number-at-pos) 1)
2177 (move-to-column (+ old-column
(1- (minibuffer-prompt-end))))
2178 (move-to-column old-column
))
2179 ;; Put the cursor at the end of the visual line instead of the
2180 ;; logical line, so the next `previous-line-or-history-element'
2181 ;; would move to the previous history element, not to a possible upper
2182 ;; visual line from the end of logical line in `line-move-visual' mode.
2183 (end-of-visual-line)
2184 ;; Since `end-of-visual-line' puts the cursor at the beginning
2185 ;; of the next visual line, move it one char back to the end
2186 ;; of the first visual line (bug#22544).
2187 (unless (eolp) (backward-char 1)))))))
2189 (defun next-complete-history-element (n)
2190 "Get next history element which completes the minibuffer before the point.
2191 The contents of the minibuffer after the point are deleted, and replaced
2192 by the new completion."
2194 (let ((point-at-start (point)))
2195 (next-matching-history-element
2197 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2199 ;; next-matching-history-element always puts us at (point-min).
2200 ;; Move to the position we were at before changing the buffer contents.
2201 ;; This is still sensible, because the text before point has not changed.
2202 (goto-char point-at-start
)))
2204 (defun previous-complete-history-element (n)
2206 Get previous history element which completes the minibuffer before the point.
2207 The contents of the minibuffer after the point are deleted, and replaced
2208 by the new completion."
2210 (next-complete-history-element (- n
)))
2212 ;; For compatibility with the old subr of the same name.
2213 (defun minibuffer-prompt-width ()
2214 "Return the display width of the minibuffer prompt.
2215 Return 0 if current buffer is not a minibuffer."
2216 ;; Return the width of everything before the field at the end of
2217 ;; the buffer; this should be 0 for normal buffers.
2218 (1- (minibuffer-prompt-end)))
2220 ;; isearch minibuffer history
2221 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
2223 (defvar minibuffer-history-isearch-message-overlay
)
2224 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
2226 (defun minibuffer-history-isearch-setup ()
2227 "Set up a minibuffer for using isearch to search the minibuffer history.
2228 Intended to be added to `minibuffer-setup-hook'."
2229 (set (make-local-variable 'isearch-search-fun-function
)
2230 'minibuffer-history-isearch-search
)
2231 (set (make-local-variable 'isearch-message-function
)
2232 'minibuffer-history-isearch-message
)
2233 (set (make-local-variable 'isearch-wrap-function
)
2234 'minibuffer-history-isearch-wrap
)
2235 (set (make-local-variable 'isearch-push-state-function
)
2236 'minibuffer-history-isearch-push-state
)
2237 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
2239 (defun minibuffer-history-isearch-end ()
2240 "Clean up the minibuffer after terminating isearch in the minibuffer."
2241 (if minibuffer-history-isearch-message-overlay
2242 (delete-overlay minibuffer-history-isearch-message-overlay
)))
2244 (defun minibuffer-history-isearch-search ()
2245 "Return the proper search function, for isearch in minibuffer history."
2246 (lambda (string bound noerror
)
2248 ;; Use standard functions to search within minibuffer text
2249 (isearch-search-fun-default))
2251 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2252 ;; searching forward. Lazy-highlight calls this lambda with the
2253 ;; bound arg, so skip the minibuffer prompt.
2254 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
2255 (goto-char (minibuffer-prompt-end)))
2257 ;; 1. First try searching in the initial minibuffer text
2258 (funcall search-fun string
2259 (if isearch-forward bound
(minibuffer-prompt-end))
2261 ;; 2. If the above search fails, start putting next/prev history
2262 ;; elements in the minibuffer successively, and search the string
2263 ;; in them. Do this only when bound is nil (i.e. not while
2264 ;; lazy-highlighting search strings in the current minibuffer text).
2269 (cond (isearch-forward
2270 (next-history-element 1)
2271 (goto-char (minibuffer-prompt-end)))
2273 (previous-history-element 1)
2274 (goto-char (point-max))))
2275 (setq isearch-barrier
(point) isearch-opoint
(point))
2276 ;; After putting the next/prev history element, search
2277 ;; the string in them again, until next-history-element
2278 ;; or previous-history-element raises an error at the
2279 ;; beginning/end of history.
2280 (setq found
(funcall search-fun string
2281 (unless isearch-forward
2282 ;; For backward search, don't search
2283 ;; in the minibuffer prompt
2284 (minibuffer-prompt-end))
2286 ;; Return point of the new search result
2288 ;; Return nil when next(prev)-history-element fails
2291 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
2292 "Display the minibuffer history search prompt.
2293 If there are no search errors, this function displays an overlay with
2294 the isearch prompt which replaces the original minibuffer prompt.
2295 Otherwise, it displays the standard isearch message returned from
2296 the function `isearch-message'."
2297 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
2298 ;; Use standard function `isearch-message' when not in the minibuffer,
2299 ;; or search fails, or has an error (like incomplete regexp).
2300 ;; This function overwrites minibuffer text with isearch message,
2301 ;; so it's possible to see what is wrong in the search string.
2302 (isearch-message c-q-hack ellipsis
)
2303 ;; Otherwise, put the overlay with the standard isearch prompt over
2304 ;; the initial minibuffer prompt.
2305 (if (overlayp minibuffer-history-isearch-message-overlay
)
2306 (move-overlay minibuffer-history-isearch-message-overlay
2307 (point-min) (minibuffer-prompt-end))
2308 (setq minibuffer-history-isearch-message-overlay
2309 (make-overlay (point-min) (minibuffer-prompt-end)))
2310 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
2311 (overlay-put minibuffer-history-isearch-message-overlay
2312 'display
(isearch-message-prefix c-q-hack ellipsis
))
2313 ;; And clear any previous isearch message.
2316 (defun minibuffer-history-isearch-wrap ()
2317 "Wrap the minibuffer history search when search fails.
2318 Move point to the first history element for a forward search,
2319 or to the last history element for a backward search."
2320 ;; When `minibuffer-history-isearch-search' fails on reaching the
2321 ;; beginning/end of the history, wrap the search to the first/last
2322 ;; minibuffer history element.
2324 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
2325 (goto-history-element 0))
2326 (setq isearch-success t
)
2327 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
2329 (defun minibuffer-history-isearch-push-state ()
2330 "Save a function restoring the state of minibuffer history search.
2331 Save `minibuffer-history-position' to the additional state parameter
2332 in the search status stack."
2333 (let ((pos minibuffer-history-position
))
2335 (minibuffer-history-isearch-pop-state cmd pos
))))
2337 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos
)
2338 "Restore the minibuffer history search state.
2339 Go to the history element by the absolute history position HIST-POS."
2340 (goto-history-element hist-pos
))
2343 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2344 (define-obsolete-function-alias 'advertised-undo
'undo
"23.2")
2346 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
2347 "Table mapping redo records to the corresponding undo one.
2348 A redo record for undo-in-region maps to t.
2349 A redo record for ordinary undo maps to the following (earlier) undo.")
2351 (defvar undo-in-region nil
2352 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2354 (defvar undo-no-redo nil
2355 "If t, `undo' doesn't go through redo entries.")
2357 (defvar pending-undo-list nil
2358 "Within a run of consecutive undo commands, list remaining to be undone.
2359 If t, we undid all the way to the end of it.")
2361 (defun undo (&optional arg
)
2362 "Undo some previous changes.
2363 Repeat this command to undo more changes.
2364 A numeric ARG serves as a repeat count.
2366 In Transient Mark mode when the mark is active, only undo changes within
2367 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2368 as an argument limits undo to changes within the current region."
2370 ;; Make last-command indicate for the next command that this was an undo.
2371 ;; That way, another undo will undo more.
2372 ;; If we get to the end of the undo history and get an error,
2373 ;; another undo command will find the undo history empty
2374 ;; and will get another error. To begin undoing the undos,
2375 ;; you must type some other command.
2376 (let* ((modified (buffer-modified-p))
2377 ;; For an indirect buffer, look in the base buffer for the
2379 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2380 (recent-save (with-current-buffer base-buffer
2381 (recent-auto-save-p)))
2383 ;; If we get an error in undo-start,
2384 ;; the next command should not be a "consecutive undo".
2385 ;; So set `this-command' to something other than `undo'.
2386 (setq this-command
'undo-start
)
2388 (unless (and (eq last-command
'undo
)
2389 (or (eq pending-undo-list t
)
2390 ;; If something (a timer or filter?) changed the buffer
2391 ;; since the previous command, don't continue the undo seq.
2392 (let ((list buffer-undo-list
))
2393 (while (eq (car list
) nil
)
2394 (setq list
(cdr list
)))
2395 ;; If the last undo record made was made by undo
2396 ;; it shows nothing else happened in between.
2397 (gethash list undo-equiv-table
))))
2398 (setq undo-in-region
2399 (or (region-active-p) (and arg
(not (numberp arg
)))))
2401 (undo-start (region-beginning) (region-end))
2403 ;; get rid of initial undo boundary
2405 ;; If we got this far, the next command should be a consecutive undo.
2406 (setq this-command
'undo
)
2407 ;; Check to see whether we're hitting a redo record, and if
2408 ;; so, ask the user whether she wants to skip the redo/undo pair.
2409 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
2410 (or (eq (selected-window) (minibuffer-window))
2411 (setq message
(format "%s%s!"
2412 (if (or undo-no-redo
(not equiv
))
2414 (if undo-in-region
" in region" ""))))
2415 (when (and (consp equiv
) undo-no-redo
)
2416 ;; The equiv entry might point to another redo record if we have done
2417 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2418 (while (let ((next (gethash equiv undo-equiv-table
)))
2419 (if next
(setq equiv next
))))
2420 (setq pending-undo-list equiv
)))
2423 (prefix-numeric-value arg
)
2425 ;; Record the fact that the just-generated undo records come from an
2426 ;; undo operation--that is, they are redo records.
2427 ;; In the ordinary case (not within a region), map the redo
2428 ;; record to the following undos.
2429 ;; I don't know how to do that in the undo-in-region case.
2430 (let ((list buffer-undo-list
))
2431 ;; Strip any leading undo boundaries there might be, like we do
2432 ;; above when checking.
2433 (while (eq (car list
) nil
)
2434 (setq list
(cdr list
)))
2436 ;; Prevent identity mapping. This can happen if
2437 ;; consecutive nils are erroneously in undo list.
2438 (if (or undo-in-region
(eq list pending-undo-list
))
2442 ;; Don't specify a position in the undo record for the undo command.
2443 ;; Instead, undoing this should move point to where the change is.
2444 (let ((tail buffer-undo-list
)
2447 (when (integerp (car tail
))
2448 (let ((pos (car tail
)))
2450 (setcdr prev
(cdr tail
))
2451 (setq buffer-undo-list
(cdr tail
)))
2452 (setq tail
(cdr tail
))
2454 (if (eq pos
(car tail
))
2456 (setcdr prev
(cdr tail
))
2457 (setq buffer-undo-list
(cdr tail
)))
2459 (setq tail
(cdr tail
)))
2461 (setq prev tail tail
(cdr tail
))))
2462 ;; Record what the current undo list says,
2463 ;; so the next command can tell if the buffer was modified in between.
2464 (and modified
(not (buffer-modified-p))
2465 (with-current-buffer base-buffer
2466 (delete-auto-save-file-if-necessary recent-save
)))
2467 ;; Display a message announcing success.
2469 (message "%s" message
))))
2471 (defun buffer-disable-undo (&optional buffer
)
2472 "Make BUFFER stop keeping undo information.
2473 No argument or nil as argument means do this for the current buffer."
2475 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
2476 (setq buffer-undo-list t
)))
2478 (defun undo-only (&optional arg
)
2479 "Undo some previous changes.
2480 Repeat this command to undo more changes.
2481 A numeric ARG serves as a repeat count.
2482 Contrary to `undo', this will not redo a previous undo."
2484 (let ((undo-no-redo t
)) (undo arg
)))
2486 (defvar undo-in-progress nil
2487 "Non-nil while performing an undo.
2488 Some change-hooks test this variable to do something different.")
2490 (defun undo-more (n)
2491 "Undo back N undo-boundaries beyond what was already undone recently.
2492 Call `undo-start' to get ready to undo recent changes,
2493 then call `undo-more' one or more times to undo them."
2494 (or (listp pending-undo-list
)
2495 (user-error (concat "No further undo information"
2496 (and undo-in-region
" for region"))))
2497 (let ((undo-in-progress t
))
2498 ;; Note: The following, while pulling elements off
2499 ;; `pending-undo-list' will call primitive change functions which
2500 ;; will push more elements onto `buffer-undo-list'.
2501 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
2502 (if (null pending-undo-list
)
2503 (setq pending-undo-list t
))))
2505 (defun primitive-undo (n list
)
2506 "Undo N records from the front of the list LIST.
2507 Return what remains of the list."
2509 ;; This is a good feature, but would make undo-start
2510 ;; unable to do what is expected.
2511 ;;(when (null (car (list)))
2512 ;; ;; If the head of the list is a boundary, it is the boundary
2513 ;; ;; preceding this command. Get rid of it and don't count it.
2514 ;; (setq list (cdr list))))
2517 ;; In a writable buffer, enable undoing read-only text that is
2518 ;; so because of text properties.
2519 (inhibit-read-only t
)
2520 ;; Don't let `intangible' properties interfere with undo.
2521 (inhibit-point-motion-hooks t
)
2522 ;; We use oldlist only to check for EQ. ++kfs
2523 (oldlist buffer-undo-list
)
2527 (while (setq next
(pop list
)) ;Exit inner loop at undo boundary.
2528 ;; Handle an integer by setting point to that value.
2530 ((pred integerp
) (goto-char next
))
2531 ;; Element (t . TIME) records previous modtime.
2532 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2533 ;; UNKNOWN_MODTIME_NSECS.
2535 ;; If this records an obsolete save
2536 ;; (not matching the actual disk file)
2537 ;; then don't mark unmodified.
2538 (when (or (equal time
(visited-file-modtime))
2540 (equal (list (car time
) (cdr time
))
2541 (visited-file-modtime))))
2542 (when (fboundp 'unlock-buffer
)
2544 (set-buffer-modified-p nil
)))
2545 ;; Element (nil PROP VAL BEG . END) is property change.
2546 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2547 (when (or (> (point-min) beg
) (< (point-max) end
))
2548 (error "Changes to be undone are outside visible portion of buffer"))
2549 (put-text-property beg end prop val
))
2550 ;; Element (BEG . END) means range was inserted.
2551 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2552 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2553 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2554 (when (or (> (point-min) beg
) (< (point-max) end
))
2555 (error "Changes to be undone are outside visible portion of buffer"))
2556 ;; Set point first thing, so that undoing this undo
2557 ;; does not send point back to where it is now.
2559 (delete-region beg end
))
2560 ;; Element (apply FUN . ARGS) means call FUN to undo.
2561 (`(apply .
,fun-args
)
2562 (let ((currbuff (current-buffer)))
2563 (if (integerp (car fun-args
))
2564 ;; Long format: (apply DELTA START END FUN . ARGS).
2565 (pcase-let* ((`(,delta
,start
,end
,fun .
,args
) fun-args
)
2566 (start-mark (copy-marker start nil
))
2567 (end-mark (copy-marker end t
)))
2568 (when (or (> (point-min) start
) (< (point-max) end
))
2569 (error "Changes to be undone are outside visible portion of buffer"))
2570 (apply fun args
) ;; Use `save-current-buffer'?
2571 ;; Check that the function did what the entry
2572 ;; said it would do.
2573 (unless (and (= start start-mark
)
2574 (= (+ delta end
) end-mark
))
2575 (error "Changes to be undone by function different than announced"))
2576 (set-marker start-mark nil
)
2577 (set-marker end-mark nil
))
2579 (unless (eq currbuff
(current-buffer))
2580 (error "Undo function switched buffer"))
2581 (setq did-apply t
)))
2582 ;; Element (STRING . POS) means STRING was deleted.
2583 (`(,(and string
(pred stringp
)) .
,(and pos
(pred integerp
)))
2584 (let ((valid-marker-adjustments nil
)
2586 (when (or (< apos
(point-min)) (> apos
(point-max)))
2587 (error "Changes to be undone are outside visible portion of buffer"))
2588 ;; Check that marker adjustments which were recorded
2589 ;; with the (STRING . POS) record are still valid, ie
2590 ;; the markers haven't moved. We check their validity
2591 ;; before reinserting the string so as we don't need to
2592 ;; mind marker insertion-type.
2593 (while (and (markerp (car-safe (car list
)))
2594 (integerp (cdr-safe (car list
))))
2595 (let* ((marker-adj (pop list
))
2596 (m (car marker-adj
)))
2597 (and (eq (marker-buffer m
) (current-buffer))
2599 (push marker-adj valid-marker-adjustments
))))
2600 ;; Insert string and adjust point
2608 ;; Adjust the valid marker adjustments
2609 (dolist (adj valid-marker-adjustments
)
2610 ;; Insert might have invalidated some of the markers
2611 ;; via modification hooks. Update only the currently
2612 ;; valid ones (bug#25599).
2613 (if (marker-buffer (car adj
))
2614 (set-marker (car adj
)
2615 (- (car adj
) (cdr adj
)))))))
2616 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2617 (`(,(and marker
(pred markerp
)) .
,(and offset
(pred integerp
)))
2618 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2620 ;; Even though these elements are not expected in the undo
2621 ;; list, adjust them to be conservative for the 24.4
2622 ;; release. (Bug#16818)
2623 (when (marker-buffer marker
)
2626 (marker-buffer marker
))))
2627 (_ (error "Unrecognized entry in undo list %S" next
))))
2628 (setq arg
(1- arg
)))
2629 ;; Make sure an apply entry produces at least one undo entry,
2630 ;; so the test in `undo' for continuing an undo series
2633 (eq oldlist buffer-undo-list
))
2634 (setq buffer-undo-list
2635 (cons (list 'apply
'cdr nil
) buffer-undo-list
))))
2638 ;; Deep copy of a list
2639 (defun undo-copy-list (list)
2640 "Make a copy of undo list LIST."
2641 (mapcar 'undo-copy-list-1 list
))
2643 (defun undo-copy-list-1 (elt)
2645 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
2648 (defun undo-start (&optional beg end
)
2649 "Set `pending-undo-list' to the front of the undo list.
2650 The next call to `undo-more' will undo the most recently made change.
2651 If BEG and END are specified, then only undo elements
2652 that apply to text between BEG and END are used; other undo elements
2653 are ignored. If BEG and END are nil, all undo elements are used."
2654 (if (eq buffer-undo-list t
)
2655 (user-error "No undo information in this buffer"))
2656 (setq pending-undo-list
2657 (if (and beg end
(not (= beg end
)))
2658 (undo-make-selective-list (min beg end
) (max beg end
))
2661 ;; The positions given in elements of the undo list are the positions
2662 ;; as of the time that element was recorded to undo history. In
2663 ;; general, subsequent buffer edits render those positions invalid in
2664 ;; the current buffer, unless adjusted according to the intervening
2667 ;; Undo in region is a use case that requires adjustments to undo
2668 ;; elements. It must adjust positions of elements in the region based
2669 ;; on newer elements not in the region so as they may be correctly
2670 ;; applied in the current buffer. undo-make-selective-list
2671 ;; accomplishes this with its undo-deltas list of adjustments. An
2672 ;; example undo history from oldest to newest:
2675 ;; 123456789 buffer-undo-list undo-deltas
2676 ;; --------- ---------------- -----------
2677 ;; aaa (1 . 4) (1 . -3)
2678 ;; aaba (3 . 4) N/A (in region)
2679 ;; ccaaba (1 . 3) (1 . -2)
2680 ;; ccaabaddd (7 . 10) (7 . -3)
2681 ;; ccaabdd ("ad" . 6) (6 . 2)
2682 ;; ccaabaddd (6 . 8) (6 . -2)
2683 ;; | |<-- region: "caab", from 2 to 6
2685 ;; When the user starts a run of undos in region,
2686 ;; undo-make-selective-list is called to create the full list of in
2687 ;; region elements. Each element is adjusted forward chronologically
2688 ;; through undo-deltas to determine if it is in the region.
2690 ;; In the above example, the insertion of "b" is (3 . 4) in the
2691 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2692 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2693 ;; . 6) is assessed as in the region and placed in the selective list.
2694 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2695 ;; due to the selected element. The "b" insertion is the only element
2696 ;; fully in the region, so in this example undo-make-selective-list
2697 ;; returns (nil (5 . 6)).
2699 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2700 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2701 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2702 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2703 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2705 ;; More interesting is how to adjust the "ddd" insertion due to the
2706 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2707 ;; If the reinsertion was a manual retyping of "ad", then the total
2708 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2709 ;; the reinsertion was due to undo, one might expect the first "d"
2710 ;; character would again be a part of the "ddd" text, meaning its
2711 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2713 ;; undo-make-selective-list assumes in this situation that "ad" was a
2714 ;; new edit, even if it was inserted because of an undo.
2715 ;; Consequently, if the user undos in region "8 to 10" of the
2716 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2717 ;; "ccaabad", as though the first "d" became detached from the
2718 ;; original "ddd" insertion. This quirk is a FIXME.
2720 (defun undo-make-selective-list (start end
)
2721 "Return a list of undo elements for the region START to END.
2722 The elements come from `buffer-undo-list', but we keep only the
2723 elements inside this region, and discard those outside this
2724 region. The elements' positions are adjusted so as the returned
2725 list can be applied to the current buffer."
2726 (let ((ulist buffer-undo-list
)
2727 ;; A list of position adjusted undo elements in the region.
2728 (selective-list (list nil
))
2729 ;; A list of undo-deltas for out of region undo elements.
2734 (while (gethash ulist undo-equiv-table
)
2735 (setq ulist
(gethash ulist undo-equiv-table
))))
2736 (setq undo-elt
(car ulist
))
2739 ;; Don't put two nils together in the list
2740 (when (car selective-list
)
2741 (push nil selective-list
)))
2742 ((and (consp undo-elt
) (eq (car undo-elt
) t
))
2743 ;; This is a "was unmodified" element. Keep it
2744 ;; if we have kept everything thus far.
2745 (when (not undo-deltas
)
2746 (push undo-elt selective-list
)))
2747 ;; Skip over marker adjustments, instead relying
2748 ;; on finding them after (TEXT . POS) elements
2749 ((markerp (car-safe undo-elt
))
2752 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2754 (if (undo-elt-in-region adjusted-undo-elt start end
)
2756 (setq end
(+ end
(cdr (undo-delta adjusted-undo-elt
))))
2757 (push adjusted-undo-elt selective-list
)
2758 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2759 ;; kept. primitive-undo may discard them later.
2760 (when (and (stringp (car-safe adjusted-undo-elt
))
2761 (integerp (cdr-safe adjusted-undo-elt
)))
2762 (let ((list-i (cdr ulist
)))
2763 (while (markerp (car-safe (car list-i
)))
2764 (push (pop list-i
) selective-list
)))))
2765 (let ((delta (undo-delta undo-elt
)))
2766 (when (/= 0 (cdr delta
))
2767 (push delta undo-deltas
)))))))
2769 (nreverse selective-list
)))
2771 (defun undo-elt-in-region (undo-elt start end
)
2772 "Determine whether UNDO-ELT falls inside the region START ... END.
2773 If it crosses the edge, we return nil.
2775 Generally this function is not useful for determining
2776 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2777 because markers can be arbitrarily relocated. Instead, pass the
2778 marker adjustment's corresponding (TEXT . POS) element."
2779 (cond ((integerp undo-elt
)
2780 (and (>= undo-elt start
)
2786 ((stringp (car undo-elt
))
2787 ;; (TEXT . POSITION)
2788 (and (>= (abs (cdr undo-elt
)) start
)
2789 (<= (abs (cdr undo-elt
)) end
)))
2790 ((and (consp undo-elt
) (markerp (car undo-elt
)))
2791 ;; (MARKER . ADJUSTMENT)
2792 (<= start
(car undo-elt
) end
))
2793 ((null (car undo-elt
))
2794 ;; (nil PROPERTY VALUE BEG . END)
2795 (let ((tail (nthcdr 3 undo-elt
)))
2796 (and (>= (car tail
) start
)
2797 (<= (cdr tail
) end
))))
2798 ((integerp (car undo-elt
))
2800 (and (>= (car undo-elt
) start
)
2801 (<= (cdr undo-elt
) end
)))))
2803 (defun undo-elt-crosses-region (undo-elt start end
)
2804 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2805 This assumes we have already decided that UNDO-ELT
2806 is not *inside* the region START...END."
2807 (declare (obsolete nil
"25.1"))
2808 (cond ((atom undo-elt
) nil
)
2809 ((null (car undo-elt
))
2810 ;; (nil PROPERTY VALUE BEG . END)
2811 (let ((tail (nthcdr 3 undo-elt
)))
2812 (and (< (car tail
) end
)
2813 (> (cdr tail
) start
))))
2814 ((integerp (car undo-elt
))
2816 (and (< (car undo-elt
) end
)
2817 (> (cdr undo-elt
) start
)))))
2819 (defun undo-adjust-elt (elt deltas
)
2820 "Return adjustment of undo element ELT by the undo DELTAS
2825 (undo-adjust-pos elt deltas
))
2827 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2828 (undo-adjust-beg-end beg end deltas
))
2829 ;; (TEXT . POSITION)
2830 (`(,(and text
(pred stringp
)) .
,(and pos
(pred integerp
)))
2831 (cons text
(* (if (< pos
0) -
1 1)
2832 (undo-adjust-pos (abs pos
) deltas
))))
2833 ;; (nil PROPERTY VALUE BEG . END)
2834 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2835 `(nil ,prop
,val .
,(undo-adjust-beg-end beg end deltas
)))
2836 ;; (apply DELTA START END FUN . ARGS)
2838 ;; All others return same elt
2841 ;; (BEG . END) can adjust to the same positions, commonly when an
2842 ;; insertion was undone and they are out of region, for example:
2845 ;; 123456789 buffer-undo-list undo-deltas
2846 ;; --------- ---------------- -----------
2848 ;; abbaa (2 . 4) (2 . -2)
2849 ;; aaa ("bb" . 2) (2 . 2)
2852 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2853 ;; undo. Further adjustments to such an element should be the same as
2854 ;; for (TEXT . POSITION) elements. The options are:
2856 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2857 ;; analogous to marker insertion-type t.
2859 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2860 ;; marker insertion-type nil.
2862 ;; There was no strong reason to prefer one or the other, except that
2863 ;; the first is more consistent with prior undo in region behavior.
2864 (defun undo-adjust-beg-end (beg end deltas
)
2865 "Return cons of adjustments to BEG and END by the undo DELTAS
2867 (let ((adj-beg (undo-adjust-pos beg deltas
)))
2868 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2870 (max adj-beg
(undo-adjust-pos end deltas t
)))))
2872 (defun undo-adjust-pos (pos deltas
&optional use-
<)
2873 "Return adjustment of POS by the undo DELTAS list, comparing
2874 with < or <= based on USE-<."
2875 (dolist (d deltas pos
)
2880 ;; Don't allow pos to become less than the undo-delta
2881 ;; position. This edge case is described in the overview
2883 (max (car d
) (- pos
(cdr d
)))))))
2885 ;; Return the first affected buffer position and the delta for an undo element
2886 ;; delta is defined as the change in subsequent buffer positions if we *did*
2888 (defun undo-delta (undo-elt)
2889 (if (consp undo-elt
)
2890 (cond ((stringp (car undo-elt
))
2891 ;; (TEXT . POSITION)
2892 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
2893 ((integerp (car undo-elt
))
2895 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
2900 ;;; Default undo-boundary addition
2902 ;; This section adds a new undo-boundary at either after a command is
2903 ;; called or in some cases on a timer called after a change is made in
2905 (defvar-local undo-auto--last-boundary-cause nil
2906 "Describe the cause of the last undo-boundary.
2908 If `explicit', the last boundary was caused by an explicit call to
2909 `undo-boundary', that is one not called by the code in this
2912 If it is equal to `timer', then the last boundary was inserted
2913 by `undo-auto--boundary-timer'.
2915 If it is equal to `command', then the last boundary was inserted
2916 automatically after a command, that is by the code defined in
2919 If it is equal to a list, then the last boundary was inserted by
2920 an amalgamating command. The car of the list is the number of
2921 times an amalgamating command has been called, and the cdr are the
2922 buffers that were changed during the last command.")
2924 (defvar undo-auto-current-boundary-timer nil
2925 "Current timer which will run `undo-auto--boundary-timer' or nil.
2927 If set to non-nil, this will effectively disable the timer.")
2929 (defvar undo-auto--this-command-amalgamating nil
2930 "Non-nil if `this-command' should be amalgamated.
2931 This variable is set to nil by `undo-auto--boundaries' and is set
2932 by `undo-auto-amalgamate'." )
2934 (defun undo-auto--needs-boundary-p ()
2935 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2936 (car-safe buffer-undo-list
))
2938 (defun undo-auto--last-boundary-amalgamating-number ()
2939 "Return the number of amalgamating last commands or nil.
2940 Amalgamating commands are, by default, either
2941 `self-insert-command' and `delete-char', but can be any command
2942 that calls `undo-auto-amalgamate'."
2943 (car-safe undo-auto--last-boundary-cause
))
2945 (defun undo-auto--ensure-boundary (cause)
2946 "Add an `undo-boundary' to the current buffer if needed.
2947 REASON describes the reason that the boundary is being added; see
2948 `undo-auto--last-boundary' for more information."
2950 (undo-auto--needs-boundary-p))
2951 (let ((last-amalgamating
2952 (undo-auto--last-boundary-amalgamating-number)))
2954 (setq undo-auto--last-boundary-cause
2955 (if (eq 'amalgamate cause
)
2957 (if last-amalgamating
(1+ last-amalgamating
) 0)
2958 undo-auto--undoably-changed-buffers
)
2961 (defun undo-auto--boundaries (cause)
2962 "Check recently changed buffers and add a boundary if necessary.
2963 REASON describes the reason that the boundary is being added; see
2964 `undo-last-boundary' for more information."
2965 ;; (Bug #23785) All commands should ensure that there is an undo
2966 ;; boundary whether they have changed the current buffer or not.
2967 (when (eq cause
'command
)
2968 (add-to-list 'undo-auto--undoably-changed-buffers
(current-buffer)))
2969 (dolist (b undo-auto--undoably-changed-buffers
)
2970 (when (buffer-live-p b
)
2971 (with-current-buffer b
2972 (undo-auto--ensure-boundary cause
))))
2973 (setq undo-auto--undoably-changed-buffers nil
))
2975 (defun undo-auto--boundary-timer ()
2976 "Timer which will run `undo--auto-boundary-timer'."
2977 (setq undo-auto-current-boundary-timer nil
)
2978 (undo-auto--boundaries 'timer
))
2980 (defun undo-auto--boundary-ensure-timer ()
2981 "Ensure that the `undo-auto-boundary-timer' is set."
2982 (unless undo-auto-current-boundary-timer
2983 (setq undo-auto-current-boundary-timer
2984 (run-at-time 10 nil
#'undo-auto--boundary-timer
))))
2986 (defvar undo-auto--undoably-changed-buffers nil
2987 "List of buffers that have changed recently.
2989 This list is maintained by `undo-auto--undoable-change' and
2990 `undo-auto--boundaries' and can be affected by changes to their
2993 (defun undo-auto--add-boundary ()
2994 "Add an `undo-boundary' in appropriate buffers."
2995 (undo-auto--boundaries
2996 (let ((amal undo-auto--this-command-amalgamating
))
2997 (setq undo-auto--this-command-amalgamating nil
)
3002 (defun undo-auto-amalgamate ()
3003 "Amalgamate undo if necessary.
3004 This function can be called before an amalgamating command. It
3005 removes the previous `undo-boundary' if a series of such calls
3006 have been made. By default `self-insert-command' and
3007 `delete-char' are the only amalgamating commands, although this
3008 function could be called by any command wishing to have this
3010 (let ((last-amalgamating-count
3011 (undo-auto--last-boundary-amalgamating-number)))
3012 (setq undo-auto--this-command-amalgamating t
)
3014 last-amalgamating-count
3017 (< last-amalgamating-count
20)
3018 (eq this-command last-command
))
3019 ;; Amalgamate all buffers that have changed.
3020 (dolist (b (cdr undo-auto--last-boundary-cause
))
3021 (when (buffer-live-p b
)
3022 (with-current-buffer
3025 ;; The head of `buffer-undo-list' is nil.
3026 ;; `car-safe' doesn't work because
3027 ;; `buffer-undo-list' need not be a list!
3028 (and (listp buffer-undo-list
)
3029 (not (car buffer-undo-list
)))
3030 (setq buffer-undo-list
3031 (cdr buffer-undo-list
))))))
3032 (setq undo-auto--last-boundary-cause
0)))))
3034 (defun undo-auto--undoable-change ()
3035 "Called after every undoable buffer change."
3036 (add-to-list 'undo-auto--undoably-changed-buffers
(current-buffer))
3037 (undo-auto--boundary-ensure-timer))
3038 ;; End auto-boundary section
3040 (defun undo-amalgamate-change-group (handle)
3041 "Amalgamate changes in change-group since HANDLE.
3042 Remove all undo boundaries between the state of HANDLE and now.
3043 HANDLE is as returned by `prepare-change-group'."
3044 (dolist (elt handle
)
3045 (with-current-buffer (car elt
)
3046 (setq elt
(cdr elt
))
3047 (when (consp buffer-undo-list
)
3048 (let ((old-car (car-safe elt
))
3049 (old-cdr (cdr-safe elt
)))
3052 ;; Temporarily truncate the undo log at ELT.
3054 (setcar elt t
) (setcdr elt nil
))
3056 (or (null elt
) ;The undo-log was empty.
3057 ;; `elt' is still in the log: normal case.
3058 (eq elt
(last buffer-undo-list
))
3059 ;; `elt' is not in the log any more, but that's because
3060 ;; the log is "all new", so we should remove all
3061 ;; boundaries from it.
3062 (not (eq (last buffer-undo-list
) (last old-cdr
))))
3063 (cl-callf (lambda (x) (delq nil x
))
3064 (if (car buffer-undo-list
)
3066 ;; Preserve the undo-boundaries at either ends of the
3068 (cdr buffer-undo-list
)))))
3069 ;; Reset the modified cons cell ELT to its original content.
3071 (setcar elt old-car
)
3072 (setcdr elt old-cdr
))))))))
3075 (defcustom undo-ask-before-discard nil
3076 "If non-nil ask about discarding undo info for the current command.
3077 Normally, Emacs discards the undo info for the current command if
3078 it exceeds `undo-outer-limit'. But if you set this option
3079 non-nil, it asks in the echo area whether to discard the info.
3080 If you answer no, there is a slight risk that Emacs might crash, so
3081 only do it if you really want to undo the command.
3083 This option is mainly intended for debugging. You have to be
3084 careful if you use it for other purposes. Garbage collection is
3085 inhibited while the question is asked, meaning that Emacs might
3086 leak memory. So you should make sure that you do not wait
3087 excessively long before answering the question."
3092 (defvar undo-extra-outer-limit nil
3093 "If non-nil, an extra level of size that's ok in an undo item.
3094 We don't ask the user about truncating the undo list until the
3095 current item gets bigger than this amount.
3097 This variable only matters if `undo-ask-before-discard' is non-nil.")
3098 (make-variable-buffer-local 'undo-extra-outer-limit
)
3100 ;; When the first undo batch in an undo list is longer than
3101 ;; undo-outer-limit, this function gets called to warn the user that
3102 ;; the undo info for the current command was discarded. Garbage
3103 ;; collection is inhibited around the call, so it had better not do a
3105 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
3106 (defun undo-outer-limit-truncate (size)
3107 (if undo-ask-before-discard
3108 (when (or (null undo-extra-outer-limit
)
3109 (> size undo-extra-outer-limit
))
3110 ;; Don't ask the question again unless it gets even bigger.
3111 ;; This applies, in particular, if the user quits from the question.
3112 ;; Such a quit quits out of GC, but something else will call GC
3113 ;; again momentarily. It will call this function again,
3114 ;; but we don't want to ask the question again.
3115 (setq undo-extra-outer-limit
(+ size
50000))
3116 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
3117 (yes-or-no-p (format-message
3118 "Buffer `%s' undo info is %d bytes long; discard it? "
3119 (buffer-name) size
)))
3120 (progn (setq buffer-undo-list nil
)
3121 (setq undo-extra-outer-limit nil
)
3124 (display-warning '(undo discard-info
)
3127 "Buffer `%s' undo info was %d bytes long.\n"
3129 "The undo info was discarded because it exceeded \
3132 This is normal if you executed a command that made a huge change
3133 to the buffer. In that case, to prevent similar problems in the
3134 future, set `undo-outer-limit' to a value that is large enough to
3135 cover the maximum size of normal changes you expect a single
3136 command to make, but not so large that it might exceed the
3137 maximum memory allotted to Emacs.
3139 If you did not execute any such command, the situation is
3140 probably due to a bug and you should report it.
3142 You can disable the popping up of this buffer by adding the entry
3143 \(undo discard-info) to the user option `warning-suppress-types',
3144 which is defined in the `warnings' library.\n")
3146 (setq buffer-undo-list nil
)
3149 (defcustom password-word-equivalents
3150 '("password" "passcode" "passphrase" "pass phrase"
3151 ; These are sorted according to the GNU en_US locale.
3154 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3180 "пароль" ; kk, ru, uk
3195 "List of words equivalent to \"password\".
3196 This is used by Shell mode and other parts of Emacs to recognize
3197 password prompts, including prompts in languages other than
3198 English. Different case choices should not be assumed to be
3199 included; callers should bind `case-fold-search' to t."
3200 :type
'(repeat string
)
3204 (defvar shell-command-history nil
3205 "History list for some commands that read shell commands.
3207 Maximum length of the history list is determined by the value
3208 of `history-length', which see.")
3210 (defvar shell-command-switch
(purecopy "-c")
3211 "Switch used to have the shell execute its command line argument.")
3213 (defvar shell-command-default-error-buffer nil
3214 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3215 This buffer is used when `shell-command' or `shell-command-on-region'
3216 is run interactively. A value of nil means that output to stderr and
3217 stdout will be intermixed in the output stream.")
3219 (declare-function mailcap-file-default-commands
"mailcap" (files))
3220 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
3222 (defun minibuffer-default-add-shell-commands ()
3223 "Return a list of all commands associated with the current file.
3224 This function is used to add all related commands retrieved by `mailcap'
3225 to the end of the list of defaults just after the default value."
3227 (let* ((filename (if (listp minibuffer-default
)
3228 (car minibuffer-default
)
3229 minibuffer-default
))
3230 (commands (and filename
(require 'mailcap nil t
)
3231 (mailcap-file-default-commands (list filename
)))))
3232 (setq commands
(mapcar (lambda (command)
3233 (concat command
" " filename
))
3235 (if (listp minibuffer-default
)
3236 (append minibuffer-default commands
)
3237 (cons minibuffer-default commands
))))
3239 (declare-function shell-completion-vars
"shell" ())
3241 (defvar minibuffer-local-shell-command-map
3242 (let ((map (make-sparse-keymap)))
3243 (set-keymap-parent map minibuffer-local-map
)
3244 (define-key map
"\t" 'completion-at-point
)
3246 "Keymap used for completing shell commands in minibuffer.")
3248 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
3249 "Read a shell command from the minibuffer.
3250 The arguments are the same as the ones of `read-from-minibuffer',
3251 except READ and KEYMAP are missing and HIST defaults
3252 to `shell-command-history'."
3254 (minibuffer-with-setup-hook
3256 (shell-completion-vars)
3257 (set (make-local-variable 'minibuffer-default-add-function
)
3258 'minibuffer-default-add-shell-commands
))
3259 (apply 'read-from-minibuffer prompt initial-contents
3260 minibuffer-local-shell-command-map
3262 (or hist
'shell-command-history
)
3265 (defcustom async-shell-command-buffer
'confirm-new-buffer
3266 "What to do when the output buffer is used by another shell command.
3267 This option specifies how to resolve the conflict where a new command
3268 wants to direct its output to the buffer `*Async Shell Command*',
3269 but this buffer is already taken by another running shell command.
3271 The value `confirm-kill-process' is used to ask for confirmation before
3272 killing the already running process and running a new process
3273 in the same buffer, `confirm-new-buffer' for confirmation before running
3274 the command in a new buffer with a name other than the default buffer name,
3275 `new-buffer' for doing the same without confirmation,
3276 `confirm-rename-buffer' for confirmation before renaming the existing
3277 output buffer and running a new command in the default buffer,
3278 `rename-buffer' for doing the same without confirmation."
3279 :type
'(choice (const :tag
"Confirm killing of running command"
3280 confirm-kill-process
)
3281 (const :tag
"Confirm creation of a new buffer"
3283 (const :tag
"Create a new buffer"
3285 (const :tag
"Confirm renaming of existing buffer"
3286 confirm-rename-buffer
)
3287 (const :tag
"Rename the existing buffer"
3292 (defcustom async-shell-command-display-buffer t
3293 "Whether to display the command buffer immediately.
3294 If t, display the buffer immediately; if nil, wait until there
3296 :type
'(choice (const :tag
"Display buffer immediately"
3298 (const :tag
"Display buffer on output"
3303 (defun shell-command--save-pos-or-erase ()
3304 "Store a buffer position or erase the buffer.
3305 See `shell-command-dont-erase-buffer'."
3306 (let ((sym shell-command-dont-erase-buffer
)
3308 (setq buffer-read-only nil
)
3309 ;; Setting buffer-read-only to nil doesn't suffice
3310 ;; if some text has a non-nil read-only property,
3311 ;; which comint sometimes adds for prompts.
3313 (cond ((eq sym
'save-point
) (point))
3314 ((eq sym
'beg-last-out
) (point-max))
3316 (let ((inhibit-read-only t
))
3317 (erase-buffer) nil
))))
3319 (goto-char (point-max))
3320 (push (cons (current-buffer) pos
)
3321 shell-command-saved-pos
))))
3323 (defun shell-command--set-point-after-cmd (&optional buffer
)
3324 "Set point in BUFFER after command complete.
3325 BUFFER is the output buffer of the command; if nil, then defaults
3326 to the current BUFFER.
3327 Set point to the `cdr' of the element in `shell-command-saved-pos'
3328 whose `car' is BUFFER."
3329 (when shell-command-dont-erase-buffer
3330 (let* ((sym shell-command-dont-erase-buffer
)
3331 (buf (or buffer
(current-buffer)))
3332 (pos (alist-get buf shell-command-saved-pos
)))
3333 (setq shell-command-saved-pos
3334 (assq-delete-all buf shell-command-saved-pos
))
3335 (when (buffer-live-p buf
)
3336 (let ((win (car (get-buffer-window-list buf
)))
3337 (pmax (with-current-buffer buf
(point-max))))
3338 (unless (and pos
(memq sym
'(save-point beg-last-out
)))
3340 ;; Set point in the window displaying buf, if any; otherwise
3341 ;; display buf temporary in selected frame and set the point.
3343 (set-window-point win pos
)
3344 (save-window-excursion
3345 (let ((win (display-buffer
3347 '(nil (inhibit-switch-frame . t
)))))
3348 (set-window-point win pos
)))))))))
3350 (defun async-shell-command (command &optional output-buffer error-buffer
)
3351 "Execute string COMMAND asynchronously in background.
3353 Like `shell-command', but adds `&' at the end of COMMAND
3354 to execute it asynchronously.
3356 The output appears in the buffer `*Async Shell Command*'.
3357 That buffer is in shell mode.
3359 You can configure `async-shell-command-buffer' to specify what to do in
3360 case when `*Async Shell Command*' buffer is already taken by another
3361 running shell command. To run COMMAND without displaying the output
3362 in a window you can configure `display-buffer-alist' to use the action
3363 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3365 In Elisp, you will often be better served by calling `start-process'
3366 directly, since it offers more control and does not impose the use of a
3367 shell (with its need to quote arguments)."
3370 (read-shell-command "Async shell command: " nil nil
3374 ((eq major-mode
'dired-mode
)
3375 (dired-get-filename nil t
)))))
3376 (and filename
(file-relative-name filename
))))
3378 shell-command-default-error-buffer
))
3379 (unless (string-match "&[ \t]*\\'" command
)
3380 (setq command
(concat command
" &")))
3381 (shell-command command output-buffer error-buffer
))
3383 (defun shell-command (command &optional output-buffer error-buffer
)
3384 "Execute string COMMAND in inferior shell; display output, if any.
3385 With prefix argument, insert the COMMAND's output at point.
3387 Interactively, prompt for COMMAND in the minibuffer.
3389 If COMMAND ends in `&', execute it asynchronously.
3390 The output appears in the buffer `*Async Shell Command*'.
3391 That buffer is in shell mode. You can also use
3392 `async-shell-command' that automatically adds `&'.
3394 Otherwise, COMMAND is executed synchronously. The output appears in
3395 the buffer `*Shell Command Output*'. If the output is short enough to
3396 display in the echo area (which is determined by the variables
3397 `resize-mini-windows' and `max-mini-window-height'), it is shown
3398 there, but it is nonetheless available in buffer `*Shell Command
3399 Output*' even though that buffer is not automatically displayed.
3401 To specify a coding system for converting non-ASCII characters
3402 in the shell command output, use \\[universal-coding-system-argument] \
3403 before this command.
3405 Noninteractive callers can specify coding systems by binding
3406 `coding-system-for-read' and `coding-system-for-write'.
3408 The optional second argument OUTPUT-BUFFER, if non-nil,
3409 says to put the output in some other buffer.
3410 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3411 and insert the output there; a non-nil value of
3412 `shell-command-dont-erase-buffer' prevents the buffer from being
3413 erased. If OUTPUT-BUFFER is not a buffer and not nil, insert the
3414 output in current buffer after point leaving mark after it. This
3415 cannot be done asynchronously.
3417 If the command terminates without error, but generates output,
3418 and you did not specify \"insert it in the current buffer\",
3419 the output can be displayed in the echo area or in its buffer.
3420 If the output is short enough to display in the echo area
3421 \(determined by the variable `max-mini-window-height' if
3422 `resize-mini-windows' is non-nil), it is shown there.
3423 Otherwise, the buffer containing the output is displayed.
3425 If there is output and an error, and you did not specify \"insert it
3426 in the current buffer\", a message about the error goes at the end
3429 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3430 or buffer name to which to direct the command's standard error output.
3431 If it is nil, error output is mingled with regular output.
3432 In an interactive call, the variable `shell-command-default-error-buffer'
3433 specifies the value of ERROR-BUFFER.
3435 In Elisp, you will often be better served by calling `call-process' or
3436 `start-process' directly, since it offers more control and does not impose
3437 the use of a shell (with its need to quote arguments)."
3441 (read-shell-command "Shell command: " nil nil
3445 ((eq major-mode
'dired-mode
)
3446 (dired-get-filename nil t
)))))
3447 (and filename
(file-relative-name filename
))))
3449 shell-command-default-error-buffer
))
3450 ;; Look for a handler in case default-directory is a remote file name.
3452 (find-file-name-handler (directory-file-name default-directory
)
3455 (funcall handler
'shell-command command output-buffer error-buffer
)
3456 (if (and output-buffer
3457 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
3458 ;; Output goes in current buffer.
3462 (expand-file-name "scor"
3463 (or small-temporary-file-directory
3464 temporary-file-directory
)))
3466 (barf-if-buffer-read-only)
3468 ;; We do not use -f for csh; we will not support broken use of
3469 ;; .cshrcs. Even the BSD csh manual says to use
3470 ;; "if ($?prompt) exit" before things which are not useful
3471 ;; non-interactively. Besides, if someone wants their other
3472 ;; aliases for shell commands then they can still have them.
3473 (call-process shell-file-name nil
3477 nil shell-command-switch command
)
3478 (when (and error-file
(file-exists-p error-file
))
3479 (if (< 0 (nth 7 (file-attributes error-file
)))
3480 (with-current-buffer (get-buffer-create error-buffer
)
3481 (let ((pos-from-end (- (point-max) (point))))
3484 ;; Do no formatting while reading error file,
3485 ;; because that can run a shell command, and we
3486 ;; don't want that to cause an infinite recursion.
3487 (format-insert-file error-file nil
)
3488 ;; Put point after the inserted errors.
3489 (goto-char (- (point-max) pos-from-end
)))
3490 (display-buffer (current-buffer))))
3491 (delete-file error-file
))
3492 ;; This is like exchange-point-and-mark, but doesn't
3493 ;; activate the mark. It is cleaner to avoid activation,
3494 ;; even though the command loop would deactivate the mark
3495 ;; because we inserted text.
3496 (goto-char (prog1 (mark t
)
3497 (set-marker (mark-marker) (point)
3498 (current-buffer)))))
3499 ;; Output goes in a separate buffer.
3500 ;; Preserve the match data in case called from a program.
3501 ;; FIXME: It'd be ridiculous for an Elisp function to call
3502 ;; shell-command and assume that it won't mess the match-data!
3504 (if (string-match "[ \t]*&[ \t]*\\'" command
)
3505 ;; Command ending with ampersand means asynchronous.
3506 (let* ((buffer (get-buffer-create
3507 (or output-buffer
"*Async Shell Command*")))
3508 (bname (buffer-name buffer
))
3509 (directory default-directory
)
3511 ;; Remove the ampersand.
3512 (setq command
(substring command
0 (match-beginning 0)))
3513 ;; Ask the user what to do with already running process.
3514 (setq proc
(get-buffer-process buffer
))
3517 ((eq async-shell-command-buffer
'confirm-kill-process
)
3518 ;; If will kill a process, query first.
3519 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3521 (error "Shell command in progress")))
3522 ((eq async-shell-command-buffer
'confirm-new-buffer
)
3523 ;; If will create a new buffer, query first.
3524 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3525 (setq buffer
(generate-new-buffer bname
))
3526 (error "Shell command in progress")))
3527 ((eq async-shell-command-buffer
'new-buffer
)
3528 ;; It will create a new buffer.
3529 (setq buffer
(generate-new-buffer bname
)))
3530 ((eq async-shell-command-buffer
'confirm-rename-buffer
)
3531 ;; If will rename the buffer, query first.
3532 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3534 (with-current-buffer buffer
3536 (setq buffer
(get-buffer-create bname
)))
3537 (error "Shell command in progress")))
3538 ((eq async-shell-command-buffer
'rename-buffer
)
3539 ;; It will rename the buffer.
3540 (with-current-buffer buffer
3542 (setq buffer
(get-buffer-create bname
)))))
3543 (with-current-buffer buffer
3544 (shell-command--save-pos-or-erase)
3545 (setq default-directory directory
)
3546 (setq proc
(start-process "Shell" buffer shell-file-name
3547 shell-command-switch command
))
3548 (setq mode-line-process
'(":%s"))
3549 (require 'shell
) (shell-mode)
3550 (set-process-sentinel proc
'shell-command-sentinel
)
3551 ;; Use the comint filter for proper handling of
3552 ;; carriage motion (see comint-inhibit-carriage-motion).
3553 (set-process-filter proc
'comint-output-filter
)
3554 (if async-shell-command-display-buffer
3555 (display-buffer buffer
'(nil (allow-no-window . t
)))
3556 (add-function :before
(process-filter proc
)
3557 (lambda (process _string
)
3558 (let ((buf (process-buffer process
)))
3559 (when (and (zerop (buffer-size buf
))
3560 (string= (buffer-name buf
)
3562 (display-buffer buf
))))))))
3563 ;; Otherwise, command is executed synchronously.
3564 (shell-command-on-region (point) (point) command
3565 output-buffer nil error-buffer
)))))))
3567 (defun display-message-or-buffer (message &optional buffer-name action frame
)
3568 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3569 MESSAGE may be either a string or a buffer.
3571 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3572 for maximum height of the echo area, as defined by `max-mini-window-height'
3573 if `resize-mini-windows' is non-nil.
3575 Returns either the string shown in the echo area, or when a pop-up
3576 buffer is used, the window used to display it.
3578 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3579 name of the buffer used to display it in the case where a pop-up buffer
3580 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3581 string and it is displayed in the echo area, it is not specified whether
3582 the contents are inserted into the buffer anyway.
3584 Optional arguments ACTION and FRAME are as for `display-buffer',
3585 and are only used if a pop-up buffer is displayed."
3586 (cond ((and (stringp message
) (not (string-match "\n" message
)))
3587 ;; Trivial case where we can use the echo area
3588 (message "%s" message
))
3589 ((and (stringp message
)
3590 (= (string-match "\n" message
) (1- (length message
))))
3591 ;; Trivial case where we can just remove single trailing newline
3592 (message "%s" (substring message
0 (1- (length message
)))))
3595 (with-current-buffer
3596 (if (bufferp message
)
3598 (get-buffer-create (or buffer-name
"*Message*")))
3600 (unless (bufferp message
)
3605 (if (= (buffer-size) 0)
3607 (count-screen-lines nil nil nil
(minibuffer-window)))))
3609 ((and (or (<= lines
1)
3611 (if resize-mini-windows
3612 (cond ((floatp max-mini-window-height
)
3614 max-mini-window-height
))
3615 ((integerp max-mini-window-height
)
3616 max-mini-window-height
)
3620 ;; Don't use the echo area if the output buffer is
3621 ;; already displayed in the selected frame.
3622 (not (get-buffer-window (current-buffer))))
3624 (goto-char (point-max))
3627 (message "%s" (buffer-substring (point-min) (point))))
3630 (goto-char (point-min))
3631 (display-buffer (current-buffer) action frame
))))))))
3634 ;; We have a sentinel to prevent insertion of a termination message
3635 ;; in the buffer itself, and to set the point in the buffer when
3636 ;; `shell-command-dont-erase-buffer' is non-nil.
3637 (defun shell-command-sentinel (process signal
)
3638 (when (memq (process-status process
) '(exit signal
))
3639 (shell-command--set-point-after-cmd (process-buffer process
))
3641 (car (cdr (cdr (process-command process
))))
3642 (substring signal
0 -
1))))
3644 (defun shell-command-on-region (start end command
3645 &optional output-buffer replace
3646 error-buffer display-error-buffer
3647 region-noncontiguous-p
)
3648 "Execute string COMMAND in inferior shell with region as input.
3649 Normally display output (if any) in temp buffer `*Shell Command Output*';
3650 Prefix arg means replace the region with it. Return the exit code of
3653 To specify a coding system for converting non-ASCII characters
3654 in the input and output to the shell command, use \\[universal-coding-system-argument]
3655 before this command. By default, the input (from the current buffer)
3656 is encoded using coding-system specified by `process-coding-system-alist',
3657 falling back to `default-process-coding-system' if no match for COMMAND
3658 is found in `process-coding-system-alist'.
3660 Noninteractive callers can specify coding systems by binding
3661 `coding-system-for-read' and `coding-system-for-write'.
3663 If the command generates output, the output may be displayed
3664 in the echo area or in a buffer.
3665 If the output is short enough to display in the echo area
3666 \(determined by the variable `max-mini-window-height' if
3667 `resize-mini-windows' is non-nil), it is shown there.
3668 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3669 The output is available in that buffer in both cases.
3671 If there is output and an error, a message about the error
3672 appears at the end of the output.
3674 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3675 command's output. If the value is a buffer or buffer name,
3676 erase that buffer and insert the output there; a non-nil value of
3677 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3678 If the value is nil, use the buffer `*Shell Command Output*'.
3679 Any other non-nil value means to insert the output in the
3680 current buffer after START.
3682 Optional fifth arg REPLACE, if non-nil, means to insert the
3683 output in place of text from START to END, putting point and mark
3686 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3687 or buffer name to which to direct the command's standard error
3688 output. If nil, error output is mingled with regular output.
3689 When called interactively, `shell-command-default-error-buffer'
3690 is used for ERROR-BUFFER.
3692 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3693 display the error buffer if there were any errors. When called
3694 interactively, this is t."
3695 (interactive (let (string)
3697 (user-error "The mark is not set now, so there is no region"))
3698 ;; Do this before calling region-beginning
3699 ;; and region-end, in case subprocess output
3700 ;; relocates them while we are in the minibuffer.
3701 (setq string
(read-shell-command "Shell command on region: "))
3702 ;; call-interactively recognizes region-beginning and
3703 ;; region-end specially, leaving them in the history.
3704 (list (region-beginning) (region-end)
3708 shell-command-default-error-buffer
3710 (region-noncontiguous-p))))
3714 (expand-file-name "scor"
3715 (or small-temporary-file-directory
3716 temporary-file-directory
)))
3719 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3720 (if region-noncontiguous-p
3721 (let ((input (concat (funcall region-extract-function
'delete
) "\n"))
3725 (call-process-region (point-min) (point-max)
3727 nil shell-command-switch
3729 (setq output
(split-string (buffer-string) "\n")))
3731 (funcall region-insert-function output
))
3734 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
3735 ;; Replace specified region with output from command.
3736 (let ((swap (and replace
(< start end
))))
3737 ;; Don't muck with mark unless REPLACE says we should.
3739 (and replace
(push-mark (point) 'nomsg
))
3741 (call-shell-region start end command replace
3745 ;; It is rude to delete a buffer which the command is not using.
3746 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3747 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3748 ;; (kill-buffer shell-buffer)))
3749 ;; Don't muck with mark unless REPLACE says we should.
3750 (and replace swap
(exchange-point-and-mark)))
3751 ;; No prefix argument: put the output in a temp buffer,
3752 ;; replacing its entire contents.
3753 (let ((buffer (get-buffer-create
3754 (or output-buffer
"*Shell Command Output*"))))
3756 (if (and (eq buffer
(current-buffer))
3757 (or (not shell-command-dont-erase-buffer
)
3758 (and (not (eq buffer
(get-buffer "*Shell Command Output*")))
3759 (not (region-active-p)))))
3760 ;; If the input is the same buffer as the output,
3761 ;; delete everything but the specified region,
3762 ;; then replace that region with the output.
3763 (progn (setq buffer-read-only nil
)
3764 (delete-region (max start end
) (point-max))
3765 (delete-region (point-min) (min start end
))
3767 (call-process-region (point-min) (point-max)
3772 nil shell-command-switch
3774 ;; Clear the output buffer, then run the command with
3776 (let ((directory default-directory
))
3777 (with-current-buffer buffer
3778 (if (not output-buffer
)
3779 (setq default-directory directory
))
3780 (shell-command--save-pos-or-erase)))
3782 (call-shell-region start end command nil
3784 (list buffer error-file
)
3786 ;; Report the output.
3787 (with-current-buffer buffer
3788 (setq mode-line-process
3789 (cond ((null exit-status
)
3791 ((stringp exit-status
)
3792 (format " - Signal [%s]" exit-status
))
3793 ((not (equal 0 exit-status
))
3794 (format " - Exit [%d]" exit-status
)))))
3795 (if (with-current-buffer buffer
(> (point-max) (point-min)))
3796 ;; There's some output, display it
3798 (display-message-or-buffer buffer
)
3799 (shell-command--set-point-after-cmd buffer
))
3800 ;; No output; error?
3803 (< 0 (nth 7 (file-attributes error-file
))))
3804 (format "some error output%s"
3805 (if shell-command-default-error-buffer
3806 (format " to the \"%s\" buffer"
3807 shell-command-default-error-buffer
)
3810 (cond ((null exit-status
)
3811 (message "(Shell command failed with error)"))
3812 ((equal 0 exit-status
)
3813 (message "(Shell command succeeded with %s)"
3815 ((stringp exit-status
)
3816 (message "(Shell command killed by signal %s)"
3819 (message "(Shell command failed with code %d and %s)"
3820 exit-status output
))))
3821 ;; Don't kill: there might be useful info in the undo-log.
3822 ;; (kill-buffer buffer)
3825 (when (and error-file
(file-exists-p error-file
))
3826 (if (< 0 (nth 7 (file-attributes error-file
)))
3827 (with-current-buffer (get-buffer-create error-buffer
)
3828 (let ((pos-from-end (- (point-max) (point))))
3831 ;; Do no formatting while reading error file,
3832 ;; because that can run a shell command, and we
3833 ;; don't want that to cause an infinite recursion.
3834 (format-insert-file error-file nil
)
3835 ;; Put point after the inserted errors.
3836 (goto-char (- (point-max) pos-from-end
)))
3837 (and display-error-buffer
3838 (display-buffer (current-buffer)))))
3839 (delete-file error-file
))
3842 (defun shell-command-to-string (command)
3843 "Execute shell command COMMAND and return its output as a string."
3844 (with-output-to-string
3845 (with-current-buffer
3847 (process-file shell-file-name nil t nil shell-command-switch command
))))
3849 (defun process-file (program &optional infile buffer display
&rest args
)
3850 "Process files synchronously in a separate process.
3851 Similar to `call-process', but may invoke a file handler based on
3852 `default-directory'. The current working directory of the
3853 subprocess is `default-directory'.
3855 File names in INFILE and BUFFER are handled normally, but file
3856 names in ARGS should be relative to `default-directory', as they
3857 are passed to the process verbatim. (This is a difference to
3858 `call-process' which does not support file handlers for INFILE
3861 Some file handlers might not support all variants, for example
3862 they might behave as if DISPLAY was nil, regardless of the actual
3864 (let ((fh (find-file-name-handler default-directory
'process-file
))
3867 (if fh
(apply fh
'process-file program infile buffer display args
)
3868 (when infile
(setq lc
(file-local-copy infile
)))
3869 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
3870 (make-temp-file "emacs")))
3872 (apply 'call-process program
3874 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
3876 (when stderr-file
(copy-file stderr-file
(cadr buffer
) t
))))
3877 (when stderr-file
(delete-file stderr-file
))
3878 (when lc
(delete-file lc
)))))
3880 (defvar process-file-side-effects t
3881 "Whether a call of `process-file' changes remote files.
3883 By default, this variable is always set to t, meaning that a
3884 call of `process-file' could potentially change any file on a
3885 remote host. When set to nil, a file handler could optimize
3886 its behavior with respect to remote file attribute caching.
3888 You should only ever change this variable with a let-binding;
3889 never with `setq'.")
3891 (defun start-file-process (name buffer program
&rest program-args
)
3892 "Start a program in a subprocess. Return the process object for it.
3894 Similar to `start-process', but may invoke a file handler based on
3895 `default-directory'. See Info node `(elisp)Magic File Names'.
3897 This handler ought to run PROGRAM, perhaps on the local host,
3898 perhaps on a remote host that corresponds to `default-directory'.
3899 In the latter case, the local part of `default-directory' becomes
3900 the working directory of the process.
3902 PROGRAM and PROGRAM-ARGS might be file names. They are not
3903 objects of file handler invocation. File handlers might not
3904 support pty association, if PROGRAM is nil."
3905 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
3906 (if fh
(apply fh
'start-file-process name buffer program program-args
)
3907 (apply 'start-process name buffer program program-args
))))
3911 (defvar tabulated-list-format
)
3912 (defvar tabulated-list-entries
)
3913 (defvar tabulated-list-sort-key
)
3914 (declare-function tabulated-list-init-header
"tabulated-list" ())
3915 (declare-function tabulated-list-print
"tabulated-list"
3916 (&optional remember-pos update
))
3918 (defvar process-menu-query-only nil
)
3920 (defvar process-menu-mode-map
3921 (let ((map (make-sparse-keymap)))
3922 (define-key map
[?d
] 'process-menu-delete-process
)
3925 (define-derived-mode process-menu-mode tabulated-list-mode
"Process Menu"
3926 "Major mode for listing the processes called by Emacs."
3927 (setq tabulated-list-format
[("Process" 15 t
)
3930 ;; 25 is the length of the long standard buffer
3931 ;; name "*Async Shell Command*<10>" (bug#30016)
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 clipboard strings into kill ring before replacing them.
4324 When one selects something in another program to paste it into Emacs,
4325 but kills something in Emacs before actually pasting it,
4326 this selection is gone unless this variable is non-nil,
4327 in which case the other program's selection is saved in the `kill-ring'
4328 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4333 (defcustom kill-do-not-save-duplicates nil
4334 "Do not add a new string to `kill-ring' if it duplicates the last one.
4335 The comparison is done using `equal-including-properties'."
4340 (defun kill-new (string &optional replace
)
4341 "Make STRING the latest kill in the kill ring.
4342 Set `kill-ring-yank-pointer' to point to it.
4343 If `interprogram-cut-function' is non-nil, apply it to STRING.
4344 Optional second argument REPLACE non-nil means that STRING will replace
4345 the front of the kill ring, rather than being added to the list.
4347 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4348 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4351 When the yank handler has a non-nil PARAM element, the original STRING
4352 argument is not used by `insert-for-yank'. However, since Lisp code
4353 may access and use elements from the kill ring directly, the STRING
4354 argument should still be a \"useful\" string for such uses."
4355 (unless (and kill-do-not-save-duplicates
4356 ;; Due to text properties such as 'yank-handler that
4357 ;; can alter the contents to yank, comparison using
4358 ;; `equal' is unsafe.
4359 (equal-including-properties string
(car kill-ring
)))
4360 (if (fboundp 'menu-bar-update-yank-menu
)
4361 (menu-bar-update-yank-menu string
(and replace
(car kill-ring
)))))
4362 (when save-interprogram-paste-before-kill
4363 (let ((interprogram-paste (and interprogram-paste-function
4364 (funcall interprogram-paste-function
))))
4365 (when interprogram-paste
4366 (dolist (s (if (listp interprogram-paste
)
4367 (nreverse interprogram-paste
)
4368 (list interprogram-paste
)))
4369 (unless (and kill-do-not-save-duplicates
4370 (equal-including-properties s
(car kill-ring
)))
4371 (push s kill-ring
))))))
4372 (unless (and kill-do-not-save-duplicates
4373 (equal-including-properties string
(car kill-ring
)))
4374 (if (and replace kill-ring
)
4375 (setcar kill-ring string
)
4376 (push string kill-ring
)
4377 (if (> (length kill-ring
) kill-ring-max
)
4378 (setcdr (nthcdr (1- kill-ring-max
) kill-ring
) nil
))))
4379 (setq kill-ring-yank-pointer kill-ring
)
4380 (if interprogram-cut-function
4381 (funcall interprogram-cut-function string
)))
4383 ;; It has been argued that this should work similar to `self-insert-command'
4384 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4385 (defcustom kill-append-merge-undo nil
4386 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4391 (defun kill-append (string before-p
)
4392 "Append STRING to the end of the latest kill in the kill ring.
4393 If BEFORE-P is non-nil, prepend STRING to the kill.
4394 Also removes the last undo boundary in the current buffer,
4395 depending on `kill-append-merge-undo'.
4396 If `interprogram-cut-function' is set, pass the resulting kill to it."
4397 (let* ((cur (car kill-ring
)))
4398 (kill-new (if before-p
(concat string cur
) (concat cur string
))
4399 (or (= (length cur
) 0)
4400 (equal nil
(get-text-property 0 'yank-handler cur
))))
4401 (when (and kill-append-merge-undo
(not buffer-read-only
))
4402 (let ((prev buffer-undo-list
)
4403 (next (cdr buffer-undo-list
)))
4404 ;; find the next undo boundary
4408 ;; remove this undo boundary
4410 (setcdr prev
(cdr next
)))))))
4412 (defcustom yank-pop-change-selection nil
4413 "Whether rotating the kill ring changes the window system selection.
4414 If non-nil, whenever the kill ring is rotated (usually via the
4415 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4416 to copy the new kill to the window system selection."
4421 (defun current-kill (n &optional do-not-move
)
4422 "Rotate the yanking point by N places, and then return that kill.
4423 If N is zero and `interprogram-paste-function' is set to a
4424 function that returns a string or a list of strings, and if that
4425 function doesn't return nil, then that string (or list) is added
4426 to the front of the kill ring and the string (or first string in
4427 the list) is returned as the latest kill.
4429 If N is not zero, and if `yank-pop-change-selection' is
4430 non-nil, use `interprogram-cut-function' to transfer the
4431 kill at the new yank point into the window system selection.
4433 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4434 move the yanking point; just return the Nth kill forward."
4436 (let ((interprogram-paste (and (= n
0)
4437 interprogram-paste-function
4438 (funcall interprogram-paste-function
))))
4439 (if interprogram-paste
4441 ;; Disable the interprogram cut function when we add the new
4442 ;; text to the kill ring, so Emacs doesn't try to own the
4443 ;; selection, with identical text.
4444 (let ((interprogram-cut-function nil
))
4445 (if (listp interprogram-paste
)
4446 (mapc 'kill-new
(nreverse interprogram-paste
))
4447 (kill-new interprogram-paste
)))
4449 (or kill-ring
(error "Kill ring is empty"))
4450 (let ((ARGth-kill-element
4451 (nthcdr (mod (- n
(length kill-ring-yank-pointer
))
4455 (setq kill-ring-yank-pointer ARGth-kill-element
)
4456 (when (and yank-pop-change-selection
4458 interprogram-cut-function
)
4459 (funcall interprogram-cut-function
(car ARGth-kill-element
))))
4460 (car ARGth-kill-element
)))))
4464 ;;;; Commands for manipulating the kill ring.
4466 (defcustom kill-read-only-ok nil
4467 "Non-nil means don't signal an error for killing read-only text."
4471 (defun kill-region (beg end
&optional region
)
4472 "Kill (\"cut\") text between point and mark.
4473 This deletes the text from the buffer and saves it in the kill ring.
4474 The command \\[yank] can retrieve it from there.
4475 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4477 If you want to append the killed region to the last killed text,
4478 use \\[append-next-kill] before \\[kill-region].
4480 Any command that calls this function is a \"kill command\".
4481 If the previous command was also a kill command,
4482 the text killed this time appends to the text killed last time
4483 to make one entry in the kill ring.
4485 The killed text is filtered by `filter-buffer-substring' before it is
4486 saved in the kill ring, so the actual saved text might be different
4487 from what was killed.
4489 If the buffer is read-only, Emacs will beep and refrain from deleting
4490 the text, but put the text in the kill ring anyway. This means that
4491 you can use the killing commands to copy text from a read-only buffer.
4493 Lisp programs should use this function for killing text.
4494 (To delete text, use `delete-region'.)
4495 Supply two arguments, character positions BEG and END indicating the
4496 stretch of text to be killed. If the optional argument REGION is
4497 non-nil, the function ignores BEG and END, and kills the current
4499 ;; Pass mark first, then point, because the order matters when
4500 ;; calling `kill-append'.
4501 (interactive (list (mark) (point) 'region
))
4502 (unless (and beg end
)
4503 (user-error "The mark is not set now, so there is no region"))
4505 (let ((string (if region
4506 (funcall region-extract-function
'delete
)
4507 (filter-buffer-substring beg end
'delete
))))
4508 (when string
;STRING is nil if BEG = END
4509 ;; Add that string to the kill ring, one way or another.
4510 (if (eq last-command
'kill-region
)
4511 (kill-append string
(< end beg
))
4513 (when (or string
(eq last-command
'kill-region
))
4514 (setq this-command
'kill-region
))
4515 (setq deactivate-mark t
)
4517 ((buffer-read-only text-read-only
)
4518 ;; The code above failed because the buffer, or some of the characters
4519 ;; in the region, are read-only.
4520 ;; We should beep, in case the user just isn't aware of this.
4521 ;; However, there's no harm in putting
4522 ;; the region's text in the kill ring, anyway.
4523 (copy-region-as-kill beg end region
)
4524 ;; Set this-command now, so it will be set even if we get an error.
4525 (setq this-command
'kill-region
)
4526 ;; This should barf, if appropriate, and give us the correct error.
4527 (if kill-read-only-ok
4528 (progn (message "Read only text copied to kill ring") nil
)
4529 ;; Signal an error if the buffer is read-only.
4530 (barf-if-buffer-read-only)
4531 ;; If the buffer isn't read-only, the text is.
4532 (signal 'text-read-only
(list (current-buffer)))))))
4534 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4535 ;; to get two copies of the text when the user accidentally types M-w and
4536 ;; then corrects it with the intended C-w.
4537 (defun copy-region-as-kill (beg end
&optional region
)
4538 "Save the region as if killed, but don't kill it.
4539 In Transient Mark mode, deactivate the mark.
4540 If `interprogram-cut-function' is non-nil, also save the text for a window
4541 system cut and paste.
4543 The copied text is filtered by `filter-buffer-substring' before it is
4544 saved in the kill ring, so the actual saved text might be different
4545 from what was in the buffer.
4547 When called from Lisp, save in the kill ring the stretch of text
4548 between BEG and END, unless the optional argument REGION is
4549 non-nil, in which case ignore BEG and END, and save the current
4552 This command's old key binding has been given to `kill-ring-save'."
4553 ;; Pass mark first, then point, because the order matters when
4554 ;; calling `kill-append'.
4555 (interactive (list (mark) (point)
4556 (prefix-numeric-value current-prefix-arg
)))
4557 (let ((str (if region
4558 (funcall region-extract-function nil
)
4559 (filter-buffer-substring beg end
))))
4560 (if (eq last-command
'kill-region
)
4561 (kill-append str
(< end beg
))
4563 (setq deactivate-mark t
)
4566 (defun kill-ring-save (beg end
&optional region
)
4567 "Save the region as if killed, but don't kill it.
4568 In Transient Mark mode, deactivate the mark.
4569 If `interprogram-cut-function' is non-nil, also save the text for a window
4570 system cut and paste.
4572 If you want to append the killed line to the last killed text,
4573 use \\[append-next-kill] before \\[kill-ring-save].
4575 The copied text is filtered by `filter-buffer-substring' before it is
4576 saved in the kill ring, so the actual saved text might be different
4577 from what was in the buffer.
4579 When called from Lisp, save in the kill ring the stretch of text
4580 between BEG and END, unless the optional argument REGION is
4581 non-nil, in which case ignore BEG and END, and save the current
4584 This command is similar to `copy-region-as-kill', except that it gives
4585 visual feedback indicating the extent of the region being copied."
4586 ;; Pass mark first, then point, because the order matters when
4587 ;; calling `kill-append'.
4588 (interactive (list (mark) (point)
4589 (prefix-numeric-value current-prefix-arg
)))
4590 (copy-region-as-kill beg end region
)
4591 ;; This use of called-interactively-p is correct because the code it
4592 ;; controls just gives the user visual feedback.
4593 (if (called-interactively-p 'interactive
)
4594 (indicate-copied-region)))
4596 (defun indicate-copied-region (&optional message-len
)
4597 "Indicate that the region text has been copied interactively.
4598 If the mark is visible in the selected window, blink the cursor
4599 between point and mark if there is currently no active region
4602 If the mark lies outside the selected window, display an
4603 informative message containing a sample of the copied text. The
4604 optional argument MESSAGE-LEN, if non-nil, specifies the length
4605 of this sample text; it defaults to 40."
4606 (let ((mark (mark t
))
4608 ;; Inhibit quitting so we can make a quit here
4609 ;; look like a C-g typed as a command.
4611 (if (pos-visible-in-window-p mark
(selected-window))
4612 ;; Swap point-and-mark quickly so as to show the region that
4613 ;; was selected. Don't do it if the region is highlighted.
4614 (unless (and (region-active-p)
4615 (face-background 'region
))
4616 ;; Swap point and mark.
4617 (set-marker (mark-marker) (point) (current-buffer))
4619 (sit-for blink-matching-delay
)
4621 (set-marker (mark-marker) mark
(current-buffer))
4623 ;; If user quit, deactivate the mark
4624 ;; as C-g would as a command.
4625 (and quit-flag
(region-active-p)
4627 (let ((len (min (abs (- mark point
))
4628 (or message-len
40))))
4630 ;; Don't say "killed"; that is misleading.
4631 (message "Saved text until \"%s\""
4632 (buffer-substring-no-properties (- mark len
) mark
))
4633 (message "Saved text from \"%s\""
4634 (buffer-substring-no-properties mark
(+ mark len
))))))))
4636 (defun append-next-kill (&optional interactive
)
4637 "Cause following command, if it kills, to add to previous kill.
4638 If the next command kills forward from point, the kill is
4639 appended to the previous killed text. If the command kills
4640 backward, the kill is prepended. Kill commands that act on the
4641 region, such as `kill-region', are regarded as killing forward if
4642 point is after mark, and killing backward if point is before
4645 If the next command is not a kill command, `append-next-kill' has
4648 The argument is used for internal purposes; do not supply one."
4650 ;; We don't use (interactive-p), since that breaks kbd macros.
4653 (setq this-command
'kill-region
)
4654 (message "If the next command is a kill, it will append"))
4655 (setq last-command
'kill-region
)))
4657 (defvar bidi-directional-controls-chars
"\x202a-\x202e\x2066-\x2069"
4658 "Character set that matches bidirectional formatting control characters.")
4660 (defvar bidi-directional-non-controls-chars
"^\x202a-\x202e\x2066-\x2069"
4661 "Character set that matches any character except bidirectional controls.")
4663 (defun squeeze-bidi-context-1 (from to category replacement
)
4664 "A subroutine of `squeeze-bidi-context'.
4665 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4666 (let ((pt (copy-marker from
))
4667 (limit (copy-marker to
))
4676 ;; L and R categories include embedding and
4677 ;; override controls, but we don't want to
4678 ;; replace them, because that might change
4679 ;; the visual order. Likewise with PDF and
4680 ;; isolate controls.
4681 (+ pt
(skip-chars-forward
4682 bidi-directional-non-controls-chars
4684 ;; Replace any run of non-RTL characters by a single LRM.
4685 (if (null (re-search-forward category lim1 t
))
4686 ;; No more characters of CATEGORY, we are done.
4688 (replace-match replacement nil t
)
4689 (move-marker pt
(point)))
4691 ;; Skip directional controls, if any.
4693 pt
(+ pt
(skip-chars-forward bidi-directional-controls-chars limit
))))))
4695 (defun squeeze-bidi-context (from to
)
4696 "Replace characters between FROM and TO while keeping bidi context.
4698 This function replaces the region of text with as few characters
4699 as possible, while preserving the effect that region will have on
4700 bidirectional display before and after the region."
4701 (let ((start (set-marker (make-marker)
4702 (if (> from
0) from
(+ (point-max) from
))))
4703 (end (set-marker (make-marker) to
))
4704 ;; This is for when they copy text with read-only text
4706 (inhibit-read-only t
))
4707 (if (null (marker-position end
))
4708 (setq end
(point-max-marker)))
4709 ;; Replace each run of non-RTL characters with a single LRM.
4710 (squeeze-bidi-context-1 start end
"\\CR+" "\x200e")
4711 ;; Replace each run of non-LTR characters with a single RLM. Note
4712 ;; that the \cR category includes both the Arabic Letter (AL) and
4713 ;; R characters; here we ignore the distinction between them,
4714 ;; because that distinction only affects Arabic Number (AN)
4715 ;; characters, which are weak and don't affect the reordering.
4716 (squeeze-bidi-context-1 start end
"\\CL+" "\x200f")))
4718 (defun line-substring-with-bidi-context (start end
&optional no-properties
)
4719 "Return buffer text between START and END with its bidi context.
4721 START and END are assumed to belong to the same physical line
4722 of buffer text. This function prepends and appends to the text
4723 between START and END bidi control characters that preserve the
4724 visual order of that text when it is inserted at some other place."
4725 (if (or (< start
(point-min))
4726 (> end
(point-max)))
4727 (signal 'args-out-of-range
(list (current-buffer) start end
)))
4728 (let ((buf (current-buffer))
4729 substr para-dir from to
)
4732 (setq para-dir
(current-bidi-paragraph-direction))
4733 (setq from
(line-beginning-position)
4734 to
(line-end-position))
4736 ;; If we don't have any mixed directional characters in the
4737 ;; entire line, we can just copy the substring without adding
4739 (if (or (looking-at-p "\\CR*$")
4740 (looking-at-p "\\CL*$"))
4741 (setq substr
(if no-properties
4742 (buffer-substring-no-properties start end
)
4743 (buffer-substring start end
)))
4747 (insert-buffer-substring-no-properties buf from to
)
4748 (insert-buffer-substring buf from to
))
4749 (squeeze-bidi-context 1 (1+ (- start from
)))
4750 (squeeze-bidi-context (- end to
) nil
)
4751 (buffer-substring 1 (point-max)))))
4753 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4754 ;; (1) force the string to have the same base embedding
4755 ;; direction as the paragraph direction at the source, no matter
4756 ;; what is the paragraph direction at destination; and (2) avoid
4757 ;; affecting the visual order of the surrounding text at
4758 ;; destination if there are characters of different
4759 ;; directionality there.
4760 (concat (if (eq para-dir
'left-to-right
) "\x2066" "\x2067")
4763 (defun buffer-substring-with-bidi-context (start end
&optional no-properties
)
4764 "Return portion of current buffer between START and END with bidi context.
4766 This function works similar to `buffer-substring', but it prepends and
4767 appends to the text bidi directional control characters necessary to
4768 preserve the visual appearance of the text if it is inserted at another
4769 place. This is useful when the buffer substring includes bidirectional
4770 text and control characters that cause non-trivial reordering on display.
4771 If copied verbatim, such text can have a very different visual appearance,
4772 and can also change the visual appearance of the surrounding text at the
4773 destination of the copy.
4775 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4776 the text properties."
4777 (let (line-end substr
)
4778 (if (or (< start
(point-min))
4779 (> end
(point-max)))
4780 (signal 'args-out-of-range
(list (current-buffer) start end
)))
4783 (setq line-end
(min end
(line-end-position)))
4784 (while (< start end
)
4788 (line-substring-with-bidi-context start line-end
4791 (setq start
(point))
4792 (setq line-end
(min end
(line-end-position))))
4797 (defcustom yank-handled-properties
4798 '((font-lock-face . yank-handle-font-lock-face-property
)
4799 (category . yank-handle-category-property
))
4800 "List of special text property handling conditions for yanking.
4801 Each element should have the form (PROP . FUN), where PROP is a
4802 property symbol and FUN is a function. When the `yank' command
4803 inserts text into the buffer, it scans the inserted text for
4804 stretches of text that have `eq' values of the text property
4805 PROP; for each such stretch of text, FUN is called with three
4806 arguments: the property's value in that text, and the start and
4807 end positions of the text.
4809 This is done prior to removing the properties specified by
4810 `yank-excluded-properties'."
4812 :type
'(repeat (cons (symbol :tag
"property symbol")
4816 ;; This is actually used in subr.el but defcustom does not work there.
4817 (defcustom yank-excluded-properties
4818 '(category field follow-link fontified font-lock-face help-echo
4819 intangible invisible keymap local-map mouse-face read-only
4821 "Text properties to discard when yanking.
4822 The value should be a list of text properties to discard or t,
4823 which means to discard all text properties.
4825 See also `yank-handled-properties'."
4826 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
4830 (defvar yank-window-start nil
)
4831 (defvar yank-undo-function nil
4832 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4833 Function is called with two parameters, START and END corresponding to
4834 the value of the mark and point; it is guaranteed that START <= END.
4835 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4837 (defun yank-pop (&optional arg
)
4838 "Replace just-yanked stretch of killed text with a different stretch.
4839 This command is allowed only immediately after a `yank' or a `yank-pop'.
4840 At such a time, the region contains a stretch of reinserted
4841 previously-killed text. `yank-pop' deletes that text and inserts in its
4842 place a different stretch of killed text.
4844 With no argument, the previous kill is inserted.
4845 With argument N, insert the Nth previous kill.
4846 If N is negative, this is a more recent kill.
4848 The sequence of kills wraps around, so that after the oldest one
4849 comes the newest one.
4851 This command honors the `yank-handled-properties' and
4852 `yank-excluded-properties' variables, and the `yank-handler' text
4853 property, in the way that `yank' does."
4855 (if (not (eq last-command
'yank
))
4856 (user-error "Previous command was not a yank"))
4857 (setq this-command
'yank
)
4858 (unless arg
(setq arg
1))
4859 (let ((inhibit-read-only t
)
4860 (before (< (point) (mark t
))))
4862 (funcall (or yank-undo-function
'delete-region
) (point) (mark t
))
4863 (funcall (or yank-undo-function
'delete-region
) (mark t
) (point)))
4864 (setq yank-undo-function nil
)
4865 (set-marker (mark-marker) (point) (current-buffer))
4866 (insert-for-yank (current-kill arg
))
4867 ;; Set the window start back where it was in the yank command,
4869 (set-window-start (selected-window) yank-window-start t
)
4871 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4872 ;; It is cleaner to avoid activation, even though the command
4873 ;; loop would deactivate the mark because we inserted text.
4874 (goto-char (prog1 (mark t
)
4875 (set-marker (mark-marker) (point) (current-buffer))))))
4878 (defun yank (&optional arg
)
4879 "Reinsert (\"paste\") the last stretch of killed text.
4880 More precisely, reinsert the most recent kill, which is the
4881 stretch of killed text most recently killed OR yanked. Put point
4882 at the end, and set mark at the beginning without activating it.
4883 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4884 With argument N, reinsert the Nth most recent kill.
4886 This command honors the `yank-handled-properties' and
4887 `yank-excluded-properties' variables, and the `yank-handler' text
4888 property, as described below.
4890 Properties listed in `yank-handled-properties' are processed,
4891 then those listed in `yank-excluded-properties' are discarded.
4893 If STRING has a non-nil `yank-handler' property anywhere, the
4894 normal insert behavior is altered, and instead, for each contiguous
4895 segment of STRING that has a given value of the `yank-handler'
4896 property, that value is used as follows:
4898 The value of a `yank-handler' property must be a list of one to four
4899 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4900 FUNCTION, if non-nil, should be a function of one argument (the
4901 object to insert); FUNCTION is called instead of `insert'.
4902 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4903 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4904 PARAM may be a list of strings to insert as a rectangle). If PARAM
4905 is nil, then the current segment of STRING is used.
4906 If NOEXCLUDE is present and non-nil, the normal removal of
4907 `yank-excluded-properties' is not performed; instead FUNCTION is
4908 responsible for the removal. This may be necessary if FUNCTION
4909 adjusts point before or after inserting the object.
4910 UNDO, if present and non-nil, should be a function to be called
4911 by `yank-pop' to undo the insertion of the current PARAM. It is
4912 given two arguments, the start and end of the region. FUNCTION
4913 may set `yank-undo-function' to override UNDO.
4915 See also the command `yank-pop' (\\[yank-pop])."
4917 (setq yank-window-start
(window-start))
4918 ;; If we don't get all the way thru, make last-command indicate that
4919 ;; for the following command.
4920 (setq this-command t
)
4922 (insert-for-yank (current-kill (cond
4927 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4928 ;; It is cleaner to avoid activation, even though the command
4929 ;; loop would deactivate the mark because we inserted text.
4930 (goto-char (prog1 (mark t
)
4931 (set-marker (mark-marker) (point) (current-buffer)))))
4932 ;; If we do get all the way thru, make this-command indicate that.
4933 (if (eq this-command t
)
4934 (setq this-command
'yank
))
4937 (defun rotate-yank-pointer (arg)
4938 "Rotate the yanking point in the kill ring.
4939 With ARG, rotate that many kills forward (or backward, if negative)."
4943 ;; Some kill commands.
4945 ;; Internal subroutine of delete-char
4946 (defun kill-forward-chars (arg)
4947 (if (listp arg
) (setq arg
(car arg
)))
4948 (if (eq arg
'-
) (setq arg -
1))
4949 (kill-region (point) (+ (point) arg
)))
4951 ;; Internal subroutine of backward-delete-char
4952 (defun kill-backward-chars (arg)
4953 (if (listp arg
) (setq arg
(car arg
)))
4954 (if (eq arg
'-
) (setq arg -
1))
4955 (kill-region (point) (- (point) arg
)))
4957 (defcustom backward-delete-char-untabify-method
'untabify
4958 "The method for untabifying when deleting backward.
4959 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4960 `hungry' -- delete all whitespace, both tabs and spaces;
4961 `all' -- delete all whitespace, including tabs, spaces and newlines;
4962 nil -- just delete one character."
4963 :type
'(choice (const untabify
) (const hungry
) (const all
) (const nil
))
4967 (defun backward-delete-char-untabify (arg &optional killp
)
4968 "Delete characters backward, changing tabs into spaces.
4969 The exact behavior depends on `backward-delete-char-untabify-method'.
4970 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4971 Interactively, ARG is the prefix arg (default 1)
4972 and KILLP is t if a prefix arg was specified."
4973 (interactive "*p\nP")
4974 (when (eq backward-delete-char-untabify-method
'untabify
)
4977 (while (and (> count
0) (not (bobp)))
4978 (if (= (preceding-char) ?
\t)
4979 (let ((col (current-column)))
4981 (setq col
(- col
(current-column)))
4982 (insert-char ?\s col
)
4985 (setq count
(1- count
))))))
4986 (let* ((skip (cond ((eq backward-delete-char-untabify-method
'hungry
) " \t")
4987 ((eq backward-delete-char-untabify-method
'all
)
4990 (let* ((oldpt (point))
4991 (wh (- oldpt
(save-excursion
4992 (skip-chars-backward skip
)
4993 (constrain-to-field nil oldpt
)))))
4994 (+ arg
(if (zerop wh
) 0 (1- wh
))))
4996 ;; Avoid warning about delete-backward-char
4997 (with-no-warnings (delete-backward-char n killp
))))
4999 (defun zap-to-char (arg char
)
5000 "Kill up to and including ARGth occurrence of CHAR.
5001 Case is ignored if `case-fold-search' is non-nil in the current buffer.
5002 Goes backward if ARG is negative; error if CHAR not found."
5003 (interactive (list (prefix-numeric-value current-prefix-arg
)
5004 (read-char "Zap to char: " t
)))
5005 ;; Avoid "obsolete" warnings for translation-table-for-input.
5007 (if (char-table-p translation-table-for-input
)
5008 (setq char
(or (aref translation-table-for-input char
) char
))))
5009 (kill-region (point) (progn
5010 (search-forward (char-to-string char
) nil nil arg
)
5013 ;; kill-line and its subroutines.
5015 (defcustom kill-whole-line nil
5016 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
5020 (defun kill-line (&optional arg
)
5021 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5022 With prefix argument ARG, kill that many lines from point.
5023 Negative arguments kill lines backward.
5024 With zero argument, kills the text before point on the current line.
5026 When calling from a program, nil means \"no arg\",
5027 a number counts as a prefix arg.
5029 To kill a whole line, when point is not at the beginning, type \
5030 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5032 If `show-trailing-whitespace' is non-nil, this command will just
5033 kill the rest of the current line, even if there are no nonblanks
5036 If option `kill-whole-line' is non-nil, then this command kills the whole line
5037 including its terminating newline, when used at the beginning of a line
5038 with no argument. As a consequence, you can always kill a whole line
5039 by typing \\[move-beginning-of-line] \\[kill-line].
5041 If you want to append the killed line to the last killed text,
5042 use \\[append-next-kill] before \\[kill-line].
5044 If the buffer is read-only, Emacs will beep and refrain from deleting
5045 the line, but put the line in the kill ring anyway. This means that
5046 you can use this command to copy text from a read-only buffer.
5047 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5050 (kill-region (point)
5051 ;; It is better to move point to the other end of the kill
5052 ;; before killing. That way, in a read-only buffer, point
5053 ;; moves across the text that is copied to the kill ring.
5054 ;; The choice has no effect on undo now that undo records
5055 ;; the value of point from before the command was run.
5058 (forward-visible-line (prefix-numeric-value arg
))
5060 (signal 'end-of-buffer nil
))
5063 (end-of-visible-line) (point))))
5064 (if (or (save-excursion
5065 ;; If trailing whitespace is visible,
5066 ;; don't treat it as nothing.
5067 (unless show-trailing-whitespace
5068 (skip-chars-forward " \t" end
))
5070 (and kill-whole-line
(bolp)))
5071 (forward-visible-line 1)
5075 (defun kill-whole-line (&optional arg
)
5077 With prefix ARG, kill that many lines starting from the current line.
5078 If ARG is negative, kill backward. Also kill the preceding newline.
5079 \(This is meant to make \\[repeat] work well with negative arguments.)
5080 If ARG is zero, kill current line but exclude the trailing newline."
5082 (or arg
(setq arg
1))
5083 (if (and (> arg
0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5084 (signal 'end-of-buffer nil
))
5085 (if (and (< arg
0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5086 (signal 'beginning-of-buffer nil
))
5087 (unless (eq last-command
'kill-region
)
5089 (setq last-command
'kill-region
))
5091 ;; We need to kill in two steps, because the previous command
5092 ;; could have been a kill command, in which case the text
5093 ;; before point needs to be prepended to the current kill
5094 ;; ring entry and the text after point appended. Also, we
5095 ;; need to use save-excursion to avoid copying the same text
5096 ;; twice to the kill ring in read-only buffers.
5098 (kill-region (point) (progn (forward-visible-line 0) (point))))
5099 (kill-region (point) (progn (end-of-visible-line) (point))))
5102 (kill-region (point) (progn (end-of-visible-line) (point))))
5103 (kill-region (point)
5104 (progn (forward-visible-line (1+ arg
))
5105 (unless (bobp) (backward-char))
5109 (kill-region (point) (progn (forward-visible-line 0) (point))))
5110 (kill-region (point)
5111 (progn (forward-visible-line arg
) (point))))))
5113 (defun forward-visible-line (arg)
5114 "Move forward by ARG lines, ignoring currently invisible newlines only.
5115 If ARG is negative, move backward -ARG lines.
5116 If ARG is zero, move to the beginning of the current line."
5121 (or (zerop (forward-line 1))
5122 (signal 'end-of-buffer nil
))
5123 ;; If the newline we just skipped is invisible,
5126 (get-char-property (1- (point)) 'invisible
)))
5127 (if (if (eq buffer-invisibility-spec t
)
5129 (or (memq prop buffer-invisibility-spec
)
5130 (assq prop buffer-invisibility-spec
)))
5131 (setq arg
(1+ arg
))))
5132 (setq arg
(1- arg
)))
5133 ;; If invisible text follows, and it is a number of complete lines,
5135 (let ((opoint (point)))
5136 (while (and (not (eobp))
5138 (get-char-property (point) 'invisible
)))
5139 (if (eq buffer-invisibility-spec t
)
5141 (or (memq prop buffer-invisibility-spec
)
5142 (assq prop buffer-invisibility-spec
)))))
5144 (if (get-text-property (point) 'invisible
)
5145 (or (next-single-property-change (point) 'invisible
)
5147 (next-overlay-change (point)))))
5149 (goto-char opoint
))))
5151 (while (or first
(<= arg
0))
5154 (or (zerop (forward-line -
1))
5155 (signal 'beginning-of-buffer nil
)))
5156 ;; If the newline we just moved to is invisible,
5160 (get-char-property (1- (point)) 'invisible
)))
5161 (unless (if (eq buffer-invisibility-spec t
)
5163 (or (memq prop buffer-invisibility-spec
)
5164 (assq prop buffer-invisibility-spec
)))
5165 (setq arg
(1+ arg
)))))
5167 ;; If invisible text follows, and it is a number of complete lines,
5169 (let ((opoint (point)))
5170 (while (and (not (bobp))
5172 (get-char-property (1- (point)) 'invisible
)))
5173 (if (eq buffer-invisibility-spec t
)
5175 (or (memq prop buffer-invisibility-spec
)
5176 (assq prop buffer-invisibility-spec
)))))
5178 (if (get-text-property (1- (point)) 'invisible
)
5179 (or (previous-single-property-change (point) 'invisible
)
5181 (previous-overlay-change (point)))))
5183 (goto-char opoint
)))))
5184 ((beginning-of-buffer end-of-buffer
)
5187 (defun end-of-visible-line ()
5188 "Move to end of current visible line."
5190 ;; If the following character is currently invisible,
5191 ;; skip all characters with that same `invisible' property value,
5192 ;; then find the next newline.
5193 (while (and (not (eobp))
5195 (skip-chars-forward "^\n")
5197 (get-char-property (point) 'invisible
)))
5198 (if (eq buffer-invisibility-spec t
)
5200 (or (memq prop buffer-invisibility-spec
)
5201 (assq prop buffer-invisibility-spec
))))))
5202 (skip-chars-forward "^\n")
5203 (if (get-text-property (point) 'invisible
)
5204 (goto-char (or (next-single-property-change (point) 'invisible
)
5206 (goto-char (next-overlay-change (point))))
5209 (defun kill-current-buffer ()
5210 "Kill the current buffer.
5211 When called in the minibuffer, get out of the minibuffer
5212 using `abort-recursive-edit'.
5214 This is like `kill-this-buffer', but it doesn't have to be invoked
5215 via the menu bar, and pays no attention to the menu-bar's frame."
5217 (let ((frame (selected-frame)))
5218 (if (and (frame-live-p frame
)
5219 (not (window-minibuffer-p (frame-selected-window frame
))))
5220 (kill-buffer (current-buffer))
5221 (abort-recursive-edit))))
5224 (defun insert-buffer (buffer)
5225 "Insert after point the contents of BUFFER.
5226 Puts mark after the inserted text.
5227 BUFFER may be a buffer or a buffer name."
5228 (declare (interactive-only insert-buffer-substring
))
5232 (barf-if-buffer-read-only)
5233 (read-buffer "Insert buffer: "
5234 (if (eq (selected-window) (next-window))
5235 (other-buffer (current-buffer))
5236 (window-buffer (next-window)))
5240 (insert-buffer-substring (get-buffer buffer
))
5244 (defun append-to-buffer (buffer start end
)
5245 "Append to specified buffer the text of the region.
5246 It is inserted into that buffer before its point.
5248 When calling from a program, give three arguments:
5249 BUFFER (or buffer name), START and END.
5250 START and END specify the portion of the current buffer to be copied."
5252 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t
))
5253 (region-beginning) (region-end)))
5254 (let* ((oldbuf (current-buffer))
5255 (append-to (get-buffer-create buffer
))
5256 (windows (get-buffer-window-list append-to t t
))
5259 (with-current-buffer append-to
5260 (setq point
(point))
5261 (barf-if-buffer-read-only)
5262 (insert-buffer-substring oldbuf start end
)
5263 (dolist (window windows
)
5264 (when (= (window-point window
) point
)
5265 (set-window-point window
(point))))))))
5267 (defun prepend-to-buffer (buffer start end
)
5268 "Prepend to specified buffer the text of the region.
5269 It is inserted into that buffer after its point.
5271 When calling from a program, give three arguments:
5272 BUFFER (or buffer name), START and END.
5273 START and END specify the portion of the current buffer to be copied."
5274 (interactive "BPrepend to buffer: \nr")
5275 (let ((oldbuf (current-buffer)))
5276 (with-current-buffer (get-buffer-create buffer
)
5277 (barf-if-buffer-read-only)
5279 (insert-buffer-substring oldbuf start end
)))))
5281 (defun copy-to-buffer (buffer start end
)
5282 "Copy to specified buffer the text of the region.
5283 It is inserted into that buffer, replacing existing text there.
5285 When calling from a program, give three arguments:
5286 BUFFER (or buffer name), START and END.
5287 START and END specify the portion of the current buffer to be copied."
5288 (interactive "BCopy to buffer: \nr")
5289 (let ((oldbuf (current-buffer)))
5290 (with-current-buffer (get-buffer-create buffer
)
5291 (barf-if-buffer-read-only)
5294 (insert-buffer-substring oldbuf start end
)))))
5296 (define-error 'mark-inactive
(purecopy "The mark is not active now"))
5298 (defvar activate-mark-hook nil
5299 "Hook run when the mark becomes active.
5300 It is also run at the end of a command, if the mark is active and
5301 it is possible that the region may have changed.")
5303 (defvar deactivate-mark-hook nil
5304 "Hook run when the mark becomes inactive.")
5306 (defun mark (&optional force
)
5307 "Return this buffer's mark value as integer, or nil if never set.
5309 In Transient Mark mode, this function signals an error if
5310 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5311 or the argument FORCE is non-nil, it disregards whether the mark
5312 is active, and returns an integer or nil in the usual way.
5314 If you are using this in an editing command, you are most likely making
5315 a mistake; see the documentation of `set-mark'."
5316 (if (or force
(not transient-mark-mode
) mark-active mark-even-if-inactive
)
5317 (marker-position (mark-marker))
5318 (signal 'mark-inactive nil
)))
5320 ;; Behind display-selections-p.
5322 (defun deactivate-mark (&optional force
)
5323 "Deactivate the mark.
5324 If Transient Mark mode is disabled, this function normally does
5325 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5327 Deactivating the mark sets `mark-active' to nil, updates the
5328 primary selection according to `select-active-regions', and runs
5329 `deactivate-mark-hook'.
5331 If Transient Mark mode was temporarily enabled, reset the value
5332 of the variable `transient-mark-mode'; if this causes Transient
5333 Mark mode to be disabled, don't change `mark-active' to nil or
5334 run `deactivate-mark-hook'."
5335 (when (or (region-active-p) force
)
5336 (when (and (if (eq select-active-regions
'only
)
5337 (eq (car-safe transient-mark-mode
) 'only
)
5338 select-active-regions
)
5340 (display-selections-p))
5341 ;; The var `saved-region-selection', if non-nil, is the text in
5342 ;; the region prior to the last command modifying the buffer.
5343 ;; Set the selection to that, or to the current region.
5344 (cond (saved-region-selection
5345 (if (gui-backend-selection-owner-p 'PRIMARY
)
5346 (gui-set-selection 'PRIMARY saved-region-selection
))
5347 (setq saved-region-selection nil
))
5348 ;; If another program has acquired the selection, region
5349 ;; deactivation should not clobber it (Bug#11772).
5350 ((and (/= (region-beginning) (region-end))
5351 (or (gui-backend-selection-owner-p 'PRIMARY
)
5352 (null (gui-backend-selection-exists-p 'PRIMARY
))))
5353 (gui-set-selection 'PRIMARY
5354 (funcall region-extract-function nil
)))))
5355 (when mark-active
(force-mode-line-update)) ;Refresh toolbar (bug#16382).
5357 ((eq (car-safe transient-mark-mode
) 'only
)
5358 (setq transient-mark-mode
(cdr transient-mark-mode
))
5359 (if (eq transient-mark-mode
(default-value 'transient-mark-mode
))
5360 (kill-local-variable 'transient-mark-mode
)))
5361 ((eq transient-mark-mode
'lambda
)
5362 (kill-local-variable 'transient-mark-mode
)))
5363 (setq mark-active nil
)
5364 (run-hooks 'deactivate-mark-hook
)
5365 (redisplay--update-region-highlight (selected-window))))
5367 (defun activate-mark (&optional no-tmm
)
5369 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5371 (unless (region-active-p)
5372 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5373 (setq mark-active t
)
5374 (unless (or transient-mark-mode no-tmm
)
5375 (setq-local transient-mark-mode
'lambda
))
5376 (run-hooks 'activate-mark-hook
))))
5378 (defun set-mark (pos)
5379 "Set this buffer's mark to POS. Don't use this function!
5380 That is to say, don't use this function unless you want
5381 the user to see that the mark has moved, and you want the previous
5382 mark position to be lost.
5384 Normally, when a new mark is set, the old one should go on the stack.
5385 This is why most applications should use `push-mark', not `set-mark'.
5387 Novice Emacs Lisp programmers often try to use the mark for the wrong
5388 purposes. The mark saves a location for the user's convenience.
5389 Most editing commands should not alter the mark.
5390 To remember a location for internal use in the Lisp program,
5391 store it in a Lisp variable. Example:
5393 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5396 (set-marker (mark-marker) pos
(current-buffer))
5397 (activate-mark 'no-tmm
))
5398 ;; Normally we never clear mark-active except in Transient Mark mode.
5399 ;; But when we actually clear out the mark value too, we must
5400 ;; clear mark-active in any mode.
5402 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5403 ;; it should never be nil if the mark is nil.
5404 (setq mark-active nil
)
5405 (set-marker (mark-marker) nil
)))
5407 (defun save-mark-and-excursion--save ()
5409 (let ((mark (mark-marker)))
5410 (and (marker-position mark
) (copy-marker mark
)))
5413 (defun save-mark-and-excursion--restore (saved-mark-info)
5414 (let ((saved-mark (car saved-mark-info
))
5415 (omark (marker-position (mark-marker)))
5417 (saved-mark-active (cdr saved-mark-info
)))
5419 (if (null saved-mark
)
5420 (set-marker (mark-marker) nil
)
5421 (setf nmark
(marker-position saved-mark
))
5422 (set-marker (mark-marker) nmark
)
5423 (set-marker saved-mark nil
))
5425 (let ((cur-mark-active mark-active
))
5426 (setq mark-active saved-mark-active
)
5427 ;; If mark is active now, and either was not active or was at a
5428 ;; different place, run the activate hook.
5429 (if saved-mark-active
5430 (when (or (not cur-mark-active
)
5431 (not (eq omark nmark
)))
5432 (run-hooks 'activate-mark-hook
))
5433 ;; If mark has ceased to be active, run deactivate hook.
5434 (when cur-mark-active
5435 (run-hooks 'deactivate-mark-hook
))))))
5437 (defmacro save-mark-and-excursion
(&rest body
)
5438 "Like `save-excursion', but also save and restore the mark state.
5439 This macro does what `save-excursion' did before Emacs 25.1."
5440 (declare (indent 0) (debug t
))
5441 (let ((saved-marker-sym (make-symbol "saved-marker")))
5442 `(let ((,saved-marker-sym
(save-mark-and-excursion--save)))
5444 (save-excursion ,@body
)
5445 (save-mark-and-excursion--restore ,saved-marker-sym
)))))
5447 (defcustom use-empty-active-region nil
5448 "Whether \"region-aware\" commands should act on empty regions.
5449 If nil, region-aware commands treat the empty region as inactive.
5450 If non-nil, region-aware commands treat the region as active as
5451 long as the mark is active, even if the region is empty.
5453 Region-aware commands are those that act on the region if it is
5454 active and Transient Mark mode is enabled, and on the text near
5458 :group
'editing-basics
)
5460 (defun use-region-p ()
5461 "Return t if the region is active and it is appropriate to act on it.
5462 This is used by commands that act specially on the region under
5463 Transient Mark mode.
5465 The return value is t if Transient Mark mode is enabled and the
5466 mark is active; furthermore, if `use-empty-active-region' is nil,
5467 the region must not be empty. Otherwise, the return value is nil.
5469 For some commands, it may be appropriate to ignore the value of
5470 `use-empty-active-region'; in that case, use `region-active-p'."
5471 (and (region-active-p)
5472 (or use-empty-active-region
(> (region-end) (region-beginning)))))
5474 (defun region-active-p ()
5475 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5477 Some commands act specially on the region when Transient Mark
5478 mode is enabled. Usually, such commands should use
5479 `use-region-p' instead of this function, because `use-region-p'
5480 also checks the value of `use-empty-active-region'."
5481 (and transient-mark-mode mark-active
5482 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5483 ;; without the mark being set (e.g. bug#17324). We really should fix
5484 ;; that problem, but in the mean time, let's make sure we don't say the
5485 ;; region is active when there's no mark.
5486 (progn (cl-assert (mark)) t
)))
5488 (defun region-bounds ()
5489 "Return the boundaries of the region as a pair of positions.
5490 Value is a list of cons cells of the form (START . END)."
5491 (funcall region-extract-function
'bounds
))
5493 (defun region-noncontiguous-p ()
5494 "Return non-nil if the region contains several pieces.
5495 An example is a rectangular region handled as a list of
5496 separate contiguous regions for each line."
5497 (> (length (region-bounds)) 1))
5499 (defvar redisplay-unhighlight-region-function
5500 (lambda (rol) (when (overlayp rol
) (delete-overlay rol
))))
5502 (defvar redisplay-highlight-region-function
5503 (lambda (start end window rol
)
5504 (if (not (overlayp rol
))
5505 (let ((nrol (make-overlay start end
)))
5506 (funcall redisplay-unhighlight-region-function rol
)
5507 (overlay-put nrol
'window window
)
5508 (overlay-put nrol
'face
'region
)
5509 ;; Normal priority so that a large region doesn't hide all the
5510 ;; overlays within it, but high secondary priority so that if it
5511 ;; ends/starts in the middle of a small overlay, that small overlay
5512 ;; won't hide the region's boundaries.
5513 (overlay-put nrol
'priority
'(nil .
100))
5515 (unless (and (eq (overlay-buffer rol
) (current-buffer))
5516 (eq (overlay-start rol
) start
)
5517 (eq (overlay-end rol
) end
))
5518 (move-overlay rol start end
(current-buffer)))
5521 (defun redisplay--update-region-highlight (window)
5522 (let ((rol (window-parameter window
'internal-region-overlay
)))
5523 (if (not (and (region-active-p)
5524 (or highlight-nonselected-windows
5525 (eq window
(selected-window))
5526 (and (window-minibuffer-p)
5527 (eq window
(minibuffer-selected-window))))))
5528 (funcall redisplay-unhighlight-region-function rol
)
5529 (let* ((pt (window-point window
))
5531 (start (min pt mark
))
5534 (funcall redisplay-highlight-region-function
5535 start end window rol
)))
5536 (unless (equal new rol
)
5537 (set-window-parameter window
'internal-region-overlay
5540 (defvar pre-redisplay-functions
(list #'redisplay--update-region-highlight
)
5541 "Hook run just before redisplay.
5542 It is called in each window that is to be redisplayed. It takes one argument,
5543 which is the window that will be redisplayed. When run, the `current-buffer'
5544 is set to the buffer displayed in that window.")
5546 (defun redisplay--pre-redisplay-functions (windows)
5547 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5549 (with-current-buffer (window-buffer (selected-window))
5550 (run-hook-with-args 'pre-redisplay-functions
(selected-window)))
5551 (dolist (win (if (listp windows
) windows
(window-list-1 nil nil t
)))
5552 (with-current-buffer (window-buffer win
)
5553 (run-hook-with-args 'pre-redisplay-functions win
))))))
5555 (add-function :before pre-redisplay-function
5556 #'redisplay--pre-redisplay-functions
)
5559 (defvar-local mark-ring nil
5560 "The list of former marks of the current buffer, most recent first.")
5561 (put 'mark-ring
'permanent-local t
)
5563 (defcustom mark-ring-max
16
5564 "Maximum size of mark ring. Start discarding off end if gets this big."
5566 :group
'editing-basics
)
5568 (defvar global-mark-ring nil
5569 "The list of saved global marks, most recent first.")
5571 (defcustom global-mark-ring-max
16
5572 "Maximum size of global mark ring. \
5573 Start discarding off end if gets this big."
5575 :group
'editing-basics
)
5577 (defun pop-to-mark-command ()
5578 "Jump to mark, and pop a new position for mark off the ring.
5579 \(Does not affect global mark ring)."
5582 (user-error "No mark set in this buffer")
5583 (if (= (point) (mark t
))
5584 (message "Mark popped"))
5585 (goto-char (mark t
))
5588 (defun push-mark-command (arg &optional nomsg
)
5589 "Set mark at where point is.
5590 If no prefix ARG and mark is already set there, just activate it.
5591 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5593 (let ((mark (mark t
)))
5594 (if (or arg
(null mark
) (/= mark
(point)))
5595 (push-mark nil nomsg t
)
5596 (activate-mark 'no-tmm
)
5598 (message "Mark activated")))))
5600 (defcustom set-mark-command-repeat-pop nil
5601 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5602 That means that C-u \\[set-mark-command] \\[set-mark-command]
5603 will pop the mark twice, and
5604 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5605 will pop the mark three times.
5607 A value of nil means \\[set-mark-command]'s behavior does not change
5608 after C-u \\[set-mark-command]."
5610 :group
'editing-basics
)
5612 (defun set-mark-command (arg)
5613 "Set the mark where point is, and activate it; or jump to the mark.
5614 Setting the mark also alters the region, which is the text
5615 between point and mark; this is the closest equivalent in
5616 Emacs to what some editors call the \"selection\".
5618 With no prefix argument, set the mark at point, and push the
5619 old mark position on local mark ring. Also push the new mark on
5620 global mark ring, if the previous mark was set in another buffer.
5622 When Transient Mark Mode is off, immediately repeating this
5623 command activates `transient-mark-mode' temporarily.
5625 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5626 jump to the mark, and set the mark from
5627 position popped off the local mark ring (this does not affect the global
5628 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5629 mark ring (see `pop-global-mark').
5631 If `set-mark-command-repeat-pop' is non-nil, repeating
5632 the \\[set-mark-command] command with no prefix argument pops the next position
5633 off the local (or global) mark ring and jumps there.
5635 With \\[universal-argument] \\[universal-argument] as prefix
5636 argument, unconditionally set mark where point is, even if
5637 `set-mark-command-repeat-pop' is non-nil.
5639 Novice Emacs Lisp programmers often try to use the mark for the wrong
5640 purposes. See the documentation of `set-mark' for more information."
5642 (cond ((eq transient-mark-mode
'lambda
)
5643 (kill-local-variable 'transient-mark-mode
))
5644 ((eq (car-safe transient-mark-mode
) 'only
)
5647 ((and (consp arg
) (> (prefix-numeric-value arg
) 4))
5648 (push-mark-command nil
))
5649 ((not (eq this-command
'set-mark-command
))
5651 (pop-to-mark-command)
5652 (push-mark-command t
)))
5653 ((and set-mark-command-repeat-pop
5654 (eq last-command
'pop-global-mark
)
5656 (setq this-command
'pop-global-mark
)
5658 ((or (and set-mark-command-repeat-pop
5659 (eq last-command
'pop-to-mark-command
))
5661 (setq this-command
'pop-to-mark-command
)
5662 (pop-to-mark-command))
5663 ((eq last-command
'set-mark-command
)
5664 (if (region-active-p)
5667 (message "Mark deactivated"))
5669 (message "Mark activated")))
5671 (push-mark-command nil
))))
5673 (defun push-mark (&optional location nomsg activate
)
5674 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5675 If the last global mark pushed was not in the current buffer,
5676 also push LOCATION on the global mark ring.
5677 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5679 Novice Emacs Lisp programmers often try to use the mark for the wrong
5680 purposes. See the documentation of `set-mark' for more information.
5682 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5683 (unless (null (mark t
))
5684 (setq mark-ring
(cons (copy-marker (mark-marker)) mark-ring
))
5685 (when (> (length mark-ring
) mark-ring-max
)
5686 (move-marker (car (nthcdr mark-ring-max mark-ring
)) nil
)
5687 (setcdr (nthcdr (1- mark-ring-max
) mark-ring
) nil
)))
5688 (set-marker (mark-marker) (or location
(point)) (current-buffer))
5689 ;; Now push the mark on the global mark ring.
5690 (if (and global-mark-ring
5691 (eq (marker-buffer (car global-mark-ring
)) (current-buffer)))
5692 ;; The last global mark pushed was in this same buffer.
5693 ;; Don't push another one.
5695 (setq global-mark-ring
(cons (copy-marker (mark-marker)) global-mark-ring
))
5696 (when (> (length global-mark-ring
) global-mark-ring-max
)
5697 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring
)) nil
)
5698 (setcdr (nthcdr (1- global-mark-ring-max
) global-mark-ring
) nil
)))
5699 (or nomsg executing-kbd-macro
(> (minibuffer-depth) 0)
5700 (message "Mark set"))
5701 (if (or activate
(not transient-mark-mode
))
5702 (set-mark (mark t
)))
5706 "Pop off mark ring into the buffer's actual mark.
5707 Does not set point. Does nothing if mark ring is empty."
5709 (setq mark-ring
(nconc mark-ring
(list (copy-marker (mark-marker)))))
5710 (set-marker (mark-marker) (+ 0 (car mark-ring
)) (current-buffer))
5711 (move-marker (car mark-ring
) nil
)
5712 (if (null (mark t
)) (ding))
5713 (setq mark-ring
(cdr mark-ring
)))
5716 (define-obsolete-function-alias
5717 'exchange-dot-and-mark
'exchange-point-and-mark
"23.3")
5718 (defun exchange-point-and-mark (&optional arg
)
5719 "Put the mark where point is now, and point where the mark is now.
5720 This command works even when the mark is not active,
5721 and it reactivates the mark.
5723 If Transient Mark mode is on, a prefix ARG deactivates the mark
5724 if it is active, and otherwise avoids reactivating it. If
5725 Transient Mark mode is off, a prefix ARG enables Transient Mark
5728 (let ((omark (mark t
))
5729 (temp-highlight (eq (car-safe transient-mark-mode
) 'only
)))
5731 (user-error "No mark set in this buffer"))
5734 (cond (temp-highlight
5735 (setq-local transient-mark-mode
(cons 'only transient-mark-mode
)))
5736 ((or (and arg
(region-active-p)) ; (xor arg (not (region-active-p)))
5737 (not (or arg
(region-active-p))))
5739 (t (activate-mark)))
5742 (defcustom shift-select-mode t
5743 "When non-nil, shifted motion keys activate the mark momentarily.
5745 While the mark is activated in this way, any shift-translated point
5746 motion key extends the region, and if Transient Mark mode was off, it
5747 is temporarily turned on. Furthermore, the mark will be deactivated
5748 by any subsequent point motion key that was not shift-translated, or
5749 by any action that normally deactivates the mark in Transient Mark mode.
5751 See `this-command-keys-shift-translated' for the meaning of
5754 :group
'editing-basics
)
5756 (defun handle-shift-selection ()
5757 "Activate/deactivate mark depending on invocation thru shift translation.
5758 This function is called by `call-interactively' when a command
5759 with a `^' character in its `interactive' spec is invoked, before
5760 running the command itself.
5762 If `shift-select-mode' is enabled and the command was invoked
5763 through shift translation, set the mark and activate the region
5764 temporarily, unless it was already set in this way. See
5765 `this-command-keys-shift-translated' for the meaning of shift
5768 Otherwise, if the region has been activated temporarily,
5769 deactivate it, and restore the variable `transient-mark-mode' to
5771 (cond ((and shift-select-mode this-command-keys-shift-translated
)
5772 (unless (and mark-active
5773 (eq (car-safe transient-mark-mode
) 'only
))
5774 (setq-local transient-mark-mode
5776 (unless (eq transient-mark-mode
'lambda
)
5777 transient-mark-mode
)))
5778 (push-mark nil nil t
)))
5779 ((eq (car-safe transient-mark-mode
) 'only
)
5780 (setq transient-mark-mode
(cdr transient-mark-mode
))
5781 (if (eq transient-mark-mode
(default-value 'transient-mark-mode
))
5782 (kill-local-variable 'transient-mark-mode
))
5783 (deactivate-mark))))
5785 (define-minor-mode transient-mark-mode
5786 "Toggle Transient Mark mode.
5787 With a prefix argument ARG, enable Transient Mark mode if ARG is
5788 positive, and disable it otherwise. If called from Lisp, enable
5789 Transient Mark mode if ARG is omitted or nil.
5791 Transient Mark mode is a global minor mode. When enabled, the
5792 region is highlighted with the `region' face whenever the mark
5793 is active. The mark is \"deactivated\" by changing the buffer,
5794 and after certain other operations that set the mark but whose
5795 main purpose is something else--for example, incremental search,
5796 \\[beginning-of-buffer], and \\[end-of-buffer].
5798 You can also deactivate the mark by typing \\[keyboard-quit] or
5799 \\[keyboard-escape-quit].
5801 Many commands change their behavior when Transient Mark mode is
5802 in effect and the mark is active, by acting on the region instead
5803 of their usual default part of the buffer's text. Examples of
5804 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5805 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5806 To see the documentation of commands which are sensitive to the
5807 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5808 or \"mark.*active\" at the prompt."
5810 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5811 :variable
(default-value 'transient-mark-mode
))
5813 (defvar widen-automatically t
5814 "Non-nil means it is ok for commands to call `widen' when they want to.
5815 Some commands will do this in order to go to positions outside
5816 the current accessible part of the buffer.
5818 If `widen-automatically' is nil, these commands will do something else
5819 as a fallback, and won't change the buffer bounds.")
5821 (defvar non-essential nil
5822 "Whether the currently executing code is performing an essential task.
5823 This variable should be non-nil only when running code which should not
5824 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5825 user for a password when we are simply scanning a set of files in the
5826 background or displaying possible completions before the user even asked
5829 (defun pop-global-mark ()
5830 "Pop off global mark ring and jump to the top location."
5832 ;; Pop entries which refer to non-existent buffers.
5833 (while (and global-mark-ring
(not (marker-buffer (car global-mark-ring
))))
5834 (setq global-mark-ring
(cdr global-mark-ring
)))
5835 (or global-mark-ring
5836 (error "No global mark set"))
5837 (let* ((marker (car global-mark-ring
))
5838 (buffer (marker-buffer marker
))
5839 (position (marker-position marker
)))
5840 (setq global-mark-ring
(nconc (cdr global-mark-ring
)
5841 (list (car global-mark-ring
))))
5843 (or (and (>= position
(point-min))
5844 (<= position
(point-max)))
5845 (if widen-automatically
5847 (error "Global mark position is outside accessible part of buffer")))
5848 (goto-char position
)
5849 (switch-to-buffer buffer
)))
5851 (defcustom next-line-add-newlines nil
5852 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5855 :group
'editing-basics
)
5857 (defun next-line (&optional arg try-vscroll
)
5858 "Move cursor vertically down ARG lines.
5859 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5860 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5861 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5862 function will not vscroll.
5866 If there is no character in the target line exactly under the current column,
5867 the cursor is positioned after the character in that line which spans this
5868 column, or at the end of the line if it is not long enough.
5869 If there is no line in the buffer after this one, behavior depends on the
5870 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5871 to create a line, and moves the cursor to that line. Otherwise it moves the
5872 cursor to the end of the buffer.
5874 If the variable `line-move-visual' is non-nil, this command moves
5875 by display lines. Otherwise, it moves by buffer lines, without
5876 taking variable-width characters or continued lines into account.
5877 See \\[next-logical-line] for a command that always moves by buffer lines.
5879 The command \\[set-goal-column] can be used to create
5880 a semipermanent goal column for this command.
5881 Then instead of trying to move exactly vertically (or as close as possible),
5882 this command moves to the specified goal column (or as close as possible).
5883 The goal column is stored in the variable `goal-column', which is nil
5884 when there is no goal column. Note that setting `goal-column'
5885 overrides `line-move-visual' and causes this command to move by buffer
5886 lines rather than by display lines."
5887 (declare (interactive-only forward-line
))
5888 (interactive "^p\np")
5889 (or arg
(setq arg
1))
5890 (if (and next-line-add-newlines
(= arg
1))
5891 (if (save-excursion (end-of-line) (eobp))
5892 ;; When adding a newline, don't expand an abbrev.
5893 (let ((abbrev-mode nil
))
5895 (insert (if use-hard-newlines hard-newline
"\n")))
5896 (line-move arg nil nil try-vscroll
))
5897 (if (called-interactively-p 'interactive
)
5899 (line-move arg nil nil try-vscroll
)
5900 ((beginning-of-buffer end-of-buffer
)
5901 (signal (car err
) (cdr err
))))
5902 (line-move arg nil nil try-vscroll
)))
5905 (defun previous-line (&optional arg try-vscroll
)
5906 "Move cursor vertically up ARG lines.
5907 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5908 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5909 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5910 function will not vscroll.
5914 If there is no character in the target line exactly over the current column,
5915 the cursor is positioned after the character in that line which spans this
5916 column, or at the end of the line if it is not long enough.
5918 If the variable `line-move-visual' is non-nil, this command moves
5919 by display lines. Otherwise, it moves by buffer lines, without
5920 taking variable-width characters or continued lines into account.
5921 See \\[previous-logical-line] for a command that always moves by buffer lines.
5923 The command \\[set-goal-column] can be used to create
5924 a semipermanent goal column for this command.
5925 Then instead of trying to move exactly vertically (or as close as possible),
5926 this command moves to the specified goal column (or as close as possible).
5927 The goal column is stored in the variable `goal-column', which is nil
5928 when there is no goal column. Note that setting `goal-column'
5929 overrides `line-move-visual' and causes this command to move by buffer
5930 lines rather than by display lines."
5931 (declare (interactive-only
5932 "use `forward-line' with negative argument instead."))
5933 (interactive "^p\np")
5934 (or arg
(setq arg
1))
5935 (if (called-interactively-p 'interactive
)
5937 (line-move (- arg
) nil nil try-vscroll
)
5938 ((beginning-of-buffer end-of-buffer
)
5939 (signal (car err
) (cdr err
))))
5940 (line-move (- arg
) nil nil try-vscroll
))
5943 (defcustom track-eol nil
5944 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5945 This means moving to the end of each line moved onto.
5946 The beginning of a blank line does not count as the end of a line.
5947 This has no effect when the variable `line-move-visual' is non-nil."
5949 :group
'editing-basics
)
5951 (defcustom goal-column nil
5952 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5953 A non-nil setting overrides the variable `line-move-visual', which see."
5954 :type
'(choice integer
5955 (const :tag
"None" nil
))
5956 :group
'editing-basics
)
5957 (make-variable-buffer-local 'goal-column
)
5959 (defvar temporary-goal-column
0
5960 "Current goal column for vertical motion.
5961 It is the column where point was at the start of the current run
5962 of vertical motion commands.
5964 When moving by visual lines via the function `line-move-visual', it is a cons
5965 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5966 divided by the default column width, and HSCROLL is the number of
5967 columns by which window is scrolled from left margin.
5969 When the `track-eol' feature is doing its job, the value is
5970 `most-positive-fixnum'.")
5972 (defvar last--line-number-width
0
5973 "Last value of width used for displaying line numbers.
5974 Used internally by `line-move-visual'.")
5976 (defcustom line-move-ignore-invisible t
5977 "Non-nil means commands that move by lines ignore invisible newlines.
5978 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5979 as if newlines that are invisible didn't exist, and count
5980 only visible newlines. Thus, moving across 2 newlines
5981 one of which is invisible will be counted as a one-line move.
5982 Also, a non-nil value causes invisible text to be ignored when
5983 counting columns for the purposes of keeping point in the same
5984 column by \\[next-line] and \\[previous-line].
5986 Outline mode sets this."
5988 :group
'editing-basics
)
5990 (defcustom line-move-visual t
5991 "When non-nil, `line-move' moves point by visual lines.
5992 This movement is based on where the cursor is displayed on the
5993 screen, instead of relying on buffer contents alone. It takes
5994 into account variable-width characters and line continuation.
5995 If nil, `line-move' moves point by logical lines.
5996 A non-nil setting of `goal-column' overrides the value of this variable
5997 and forces movement by logical lines.
5998 A window that is horizontally scrolled also forces movement by logical
6001 :group
'editing-basics
6004 ;; Only used if display-graphic-p.
6005 (declare-function font-info
"font.c" (name &optional frame
))
6007 (defun default-font-height ()
6008 "Return the height in pixels of the current buffer's default face font.
6010 If the default font is remapped (see `face-remapping-alist'), the
6011 function returns the height of the remapped face."
6012 (let ((default-font (face-font 'default
)))
6014 ((and (display-multi-font-p)
6015 ;; Avoid calling font-info if the frame's default font was
6016 ;; not changed since the frame was created. That's because
6017 ;; font-info is expensive for some fonts, see bug #14838.
6018 (not (string= (frame-parameter nil
'font
) default-font
)))
6019 (aref (font-info default-font
) 3))
6020 (t (frame-char-height)))))
6022 (defun default-font-width ()
6023 "Return the width in pixels of the current buffer's default face font.
6025 If the default font is remapped (see `face-remapping-alist'), the
6026 function returns the width of the remapped face."
6027 (let ((default-font (face-font 'default
)))
6029 ((and (display-multi-font-p)
6030 ;; Avoid calling font-info if the frame's default font was
6031 ;; not changed since the frame was created. That's because
6032 ;; font-info is expensive for some fonts, see bug #14838.
6033 (not (string= (frame-parameter nil
'font
) default-font
)))
6034 (let* ((info (font-info (face-font 'default
)))
6035 (width (aref info
11)))
6039 (t (frame-char-width)))))
6041 (defun default-line-height ()
6042 "Return the pixel height of current buffer's default-face text line.
6044 The value includes `line-spacing', if any, defined for the buffer
6046 (let ((dfh (default-font-height))
6047 (lsp (if (display-graphic-p)
6049 (default-value 'line-spacing
)
6050 (frame-parameter nil
'line-spacing
)
6054 (setq lsp
(truncate (* (frame-char-height) lsp
))))
6057 (defun window-screen-lines ()
6058 "Return the number of screen lines in the text area of the selected window.
6060 This is different from `window-text-height' in that this function counts
6061 lines in units of the height of the font used by the default face displayed
6062 in the window, not in units of the frame's default font, and also accounts
6063 for `line-spacing', if any, defined for the window's buffer or frame.
6065 The value is a floating-point number."
6066 (let ((edges (window-inside-pixel-edges))
6067 (dlh (default-line-height)))
6068 (/ (float (- (nth 3 edges
) (nth 1 edges
))) dlh
)))
6070 ;; Returns non-nil if partial move was done.
6071 (defun line-move-partial (arg noerror
&optional _to-end
)
6073 ;; Move backward (up).
6074 ;; If already vscrolled, reduce vscroll
6075 (let ((vs (window-vscroll nil t
))
6076 (dlh (default-line-height)))
6078 (set-window-vscroll nil
(- vs dlh
) t
)))
6080 ;; Move forward (down).
6081 (let* ((lh (window-line-height -
1))
6086 (this-lh (window-line-height))
6087 (this-height (car this-lh
))
6088 (this-ypos (nth 2 this-lh
))
6089 (dlh (default-line-height))
6090 (wslines (window-screen-lines))
6091 (edges (window-inside-pixel-edges))
6092 (winh (- (nth 3 edges
) (nth 1 edges
) 1))
6094 (if (> (mod wslines
1.0) 0.0)
6095 (setq wslines
(round (+ wslines
0.5))))
6100 (<= this-ypos
(- dlh
)))
6102 (let ((wend (pos-visible-in-window-p t nil t
)))
6103 (setq rbot
(nth 3 wend
)
6105 vpos
(nth 5 wend
))))
6107 (let ((wstart (pos-visible-in-window-p nil nil t
)))
6108 (setq this-ypos
(nth 2 wstart
)
6109 this-height
(nth 4 wstart
))))
6112 (let ((ppos (posn-at-point))
6114 (setq col-row
(posn-actual-col-row ppos
))
6116 (- (cdr col-row
) (window-vscroll))
6117 (cdr (posn-col-row ppos
))))))
6118 ;; VPOS > 0 means the last line is only partially visible.
6119 ;; But if the part that is visible is at least as tall as the
6120 ;; default font, that means the line is actually fully
6121 ;; readable, and something like line-spacing is hidden. So in
6122 ;; that case we accept the last line in the window as still
6123 ;; visible, and consider the margin as starting one line
6125 (if (and vpos
(> vpos
0))
6127 (>= rowh
(default-font-height))
6129 (setq last-line
(min (- wslines scroll-margin
) vpos
))
6130 (setq last-line
(min (- wslines scroll-margin
1) (1- vpos
)))))
6132 ;; If last line of window is fully visible, and vscrolling
6133 ;; more would make this line invisible, move forward.
6134 ((and (or (< (setq vs
(window-vscroll nil t
)) dlh
)
6136 (<= this-height dlh
))
6137 (or (null rbot
) (= rbot
0)))
6139 ;; If cursor is not in the bottom scroll margin, and the
6140 ;; current line is not too tall, move forward.
6141 ((and (or (null this-height
) (<= this-height winh
))
6146 ;; When already vscrolled, we vscroll some more if we can,
6147 ;; or clear vscroll and move forward at end of tall image.
6149 (when (or (and rbot
(> rbot
0))
6150 (and this-height
(> this-height dlh
)))
6151 (set-window-vscroll nil
(+ vs dlh
) t
)))
6152 ;; If cursor just entered the bottom scroll margin, move forward,
6153 ;; but also optionally vscroll one line so redisplay won't recenter.
6157 ;; Don't vscroll if the partially-visible line at window
6158 ;; bottom is not too tall (a.k.a. "just one more text
6159 ;; line"): in that case, we do want redisplay to behave
6160 ;; normally, i.e. recenter or whatever.
6162 ;; Note: ROWH + RBOT from the value returned by
6163 ;; pos-visible-in-window-p give the total height of the
6164 ;; partially-visible glyph row at the end of the window. As
6165 ;; we are dealing with floats, we disregard sub-pixel
6166 ;; discrepancies between that and DLH.
6167 (if (and rowh rbot
(>= (- (+ rowh rbot
) winh
) 1))
6168 (set-window-vscroll nil dlh t
))
6169 (line-move-1 arg noerror
)
6171 ;; If there are lines above the last line, scroll-up one line.
6172 ((and vpos
(> vpos
0))
6175 ;; Finally, start vscroll.
6177 (set-window-vscroll nil dlh t
)))))))
6180 ;; This is like line-move-1 except that it also performs
6181 ;; vertical scrolling of tall images if appropriate.
6182 ;; That is not really a clean thing to do, since it mixes
6183 ;; scrolling with cursor motion. But so far we don't have
6184 ;; a cleaner solution to the problem of making C-n do something
6185 ;; useful given a tall image.
6186 (defun line-move (arg &optional noerror _to-end try-vscroll
)
6187 "Move forward ARG lines.
6188 If NOERROR, don't signal an error if we can't move ARG lines.
6190 TRY-VSCROLL controls whether to vscroll tall lines: if either
6191 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6194 (line-move-1 arg noerror
)
6195 (unless (and auto-window-vscroll try-vscroll
6196 ;; Only vscroll for single line moves
6198 ;; Under scroll-conservatively, the display engine
6199 ;; does this better.
6200 (zerop scroll-conservatively
)
6201 ;; But don't vscroll in a keyboard macro.
6202 (not defining-kbd-macro
)
6203 (not executing-kbd-macro
)
6204 (line-move-partial arg noerror
))
6205 (set-window-vscroll nil
0 t
)
6206 (if (and line-move-visual
6207 ;; Display-based column are incompatible with goal-column.
6209 ;; When the text in the window is scrolled to the left,
6210 ;; display-based motion doesn't make sense (because each
6211 ;; logical line occupies exactly one screen line).
6212 (not (> (window-hscroll) 0))
6213 ;; Likewise when the text _was_ scrolled to the left
6214 ;; when the current run of vertical motion commands
6216 (not (and (memq last-command
6217 `(next-line previous-line
,this-command
))
6219 (numberp temporary-goal-column
)
6220 (>= temporary-goal-column
6221 (- (window-width) hscroll-margin
)))))
6222 (prog1 (line-move-visual arg noerror
)
6223 ;; If we moved into a tall line, set vscroll to make
6224 ;; scrolling through tall images more smooth.
6225 (let ((lh (line-pixel-height))
6226 (edges (window-inside-pixel-edges))
6227 (dlh (default-line-height))
6229 (setq winh
(- (nth 3 edges
) (nth 1 edges
) 1))
6231 (< (point) (window-start))
6236 (line-move-1 arg noerror
)))))
6238 ;; Display-based alternative to line-move-1.
6239 ;; Arg says how many lines to move. The value is t if we can move the
6240 ;; specified number of lines.
6241 (defun line-move-visual (arg &optional noerror
)
6242 "Move ARG lines forward.
6243 If NOERROR, don't signal an error if we can't move that many lines."
6244 (let ((opoint (point))
6245 (hscroll (window-hscroll))
6246 (lnum-width (line-number-display-width t
))
6248 ;; Check if the previous command was a line-motion command, or if
6249 ;; we were called from some other command.
6250 (if (and (consp temporary-goal-column
)
6251 (memq last-command
`(next-line previous-line
,this-command
)))
6252 ;; If so, there's no need to reset `temporary-goal-column',
6253 ;; but we may need to hscroll.
6255 (if (or (/= (cdr temporary-goal-column
) hscroll
)
6256 (> (cdr temporary-goal-column
) 0))
6257 (setq target-hscroll
(cdr temporary-goal-column
)))
6258 ;; Update the COLUMN part of temporary-goal-column if the
6259 ;; line-number display changed its width since the last
6261 (setq temporary-goal-column
6262 (cons (+ (car temporary-goal-column
)
6263 (/ (float (- lnum-width last--line-number-width
))
6264 (frame-char-width)))
6265 (cdr temporary-goal-column
)))
6266 (setq last--line-number-width lnum-width
))
6267 ;; Otherwise, we should reset `temporary-goal-column'.
6268 (let ((posn (posn-at-point))
6271 ;; Handle the `overflow-newline-into-fringe' case
6272 ;; (left-fringe is for the R2L case):
6273 ((memq (nth 1 posn
) '(right-fringe left-fringe
))
6274 (setq temporary-goal-column
(cons (window-width) hscroll
)))
6275 ((car (posn-x-y posn
))
6276 (setq x-pos
(car (posn-x-y posn
)))
6277 ;; In R2L lines, the X pixel coordinate is measured from the
6278 ;; left edge of the window, but columns are still counted
6279 ;; from the logical-order beginning of the line, i.e. from
6280 ;; the right edge in this case. We need to adjust for that.
6281 (if (eq (current-bidi-paragraph-direction) 'right-to-left
)
6282 (setq x-pos
(- (window-body-width nil t
) 1 x-pos
)))
6283 (setq temporary-goal-column
6284 (cons (/ (float x-pos
)
6287 (executing-kbd-macro
6288 ;; When we move beyond the first/last character visible in
6289 ;; the window, posn-at-point will return nil, so we need to
6290 ;; approximate the goal column as below.
6291 (setq temporary-goal-column
6292 (mod (current-column) (window-text-width)))))))
6294 (set-window-hscroll (selected-window) target-hscroll
))
6295 ;; vertical-motion can move more than it was asked to if it moves
6296 ;; across display strings with newlines. We don't want to ring
6297 ;; the bell and announce beginning/end of buffer in that case.
6298 (or (and (or (and (>= arg
0)
6299 (>= (vertical-motion
6300 (cons (or goal-column
6301 (if (consp temporary-goal-column
)
6302 (car temporary-goal-column
)
6303 temporary-goal-column
))
6307 (<= (vertical-motion
6308 (cons (or goal-column
6309 (if (consp temporary-goal-column
)
6310 (car temporary-goal-column
)
6311 temporary-goal-column
))
6316 ;; If the goal column lies on a display string,
6317 ;; `vertical-motion' advances the cursor to the end
6318 ;; of the string. For arg < 0, this can cause the
6319 ;; cursor to get stuck. (Bug#3020).
6320 (= (vertical-motion arg
) arg
)))
6322 (signal (if (< arg
0) 'beginning-of-buffer
'end-of-buffer
)
6325 ;; This is the guts of next-line and previous-line.
6326 ;; Arg says how many lines to move.
6327 ;; The value is t if we can move the specified number of lines.
6328 (defun line-move-1 (arg &optional noerror _to-end
)
6329 ;; Don't run any point-motion hooks, and disregard intangibility,
6330 ;; for intermediate positions.
6331 (let ((inhibit-point-motion-hooks t
)
6334 (if (consp temporary-goal-column
)
6335 (setq temporary-goal-column
(+ (car temporary-goal-column
)
6336 (cdr temporary-goal-column
))))
6339 (if (not (memq last-command
'(next-line previous-line
)))
6340 (setq temporary-goal-column
6341 (if (and track-eol
(eolp)
6342 ;; Don't count beg of empty line as end of line
6343 ;; unless we just did explicit end-of-line.
6344 (or (not (bolp)) (eq last-command
'move-end-of-line
)))
6345 most-positive-fixnum
6348 (if (not (or (integerp selective-display
)
6349 line-move-ignore-invisible
))
6350 ;; Use just newline characters.
6351 ;; Set ARG to 0 if we move as many lines as requested.
6353 (progn (if (> arg
1) (forward-line (1- arg
)))
6354 ;; This way of moving forward ARG lines
6355 ;; verifies that we have a newline after the last one.
6356 ;; It doesn't get confused by intangible text.
6358 (if (zerop (forward-line 1))
6360 (and (zerop (forward-line arg
))
6364 (signal (if (< arg
0)
6365 'beginning-of-buffer
6368 ;; Move by arg lines, but ignore invisible ones.
6370 (while (and (> arg
0) (not done
))
6371 ;; If the following character is currently invisible,
6372 ;; skip all characters with that same `invisible' property value.
6373 (while (and (not (eobp)) (invisible-p (point)))
6374 (goto-char (next-char-property-change (point))))
6376 ;; We don't use `end-of-line', since we want to escape
6377 ;; from field boundaries occurring exactly at point.
6378 (goto-char (constrain-to-field
6379 (let ((inhibit-field-text-motion t
))
6380 (line-end-position))
6382 'inhibit-line-move-field-capture
))
6383 ;; If there's no invisibility here, move over the newline.
6387 (signal 'end-of-buffer nil
)
6389 ((and (> arg
1) ;; Use vertical-motion for last move
6390 (not (integerp selective-display
))
6391 (not (invisible-p (point))))
6392 ;; We avoid vertical-motion when possible
6393 ;; because that has to fontify.
6395 ;; Otherwise move a more sophisticated way.
6396 ((zerop (vertical-motion 1))
6398 (signal 'end-of-buffer nil
)
6401 (setq arg
(1- arg
))))
6402 ;; The logic of this is the same as the loop above,
6403 ;; it just goes in the other direction.
6404 (while (and (< arg
0) (not done
))
6405 ;; For completely consistency with the forward-motion
6406 ;; case, we should call beginning-of-line here.
6407 ;; However, if point is inside a field and on a
6408 ;; continued line, the call to (vertical-motion -1)
6409 ;; below won't move us back far enough; then we return
6410 ;; to the same column in line-move-finish, and point
6411 ;; gets stuck -- cyd
6416 (signal 'beginning-of-buffer nil
)
6418 ((and (< arg -
1) ;; Use vertical-motion for last move
6419 (not (integerp selective-display
))
6420 (not (invisible-p (1- (point)))))
6422 ((zerop (vertical-motion -
1))
6424 (signal 'beginning-of-buffer nil
)
6428 (while (and ;; Don't move over previous invis lines
6429 ;; if our target is the middle of this line.
6430 (or (zerop (or goal-column temporary-goal-column
))
6432 (not (bobp)) (invisible-p (1- (point))))
6433 (goto-char (previous-char-property-change (point))))))))
6434 ;; This is the value the function returns.
6438 ;; If we did not move down as far as desired, at least go
6439 ;; to end of line. Be sure to call point-entered and
6440 ;; point-left-hooks.
6441 (let* ((npoint (prog1 (line-end-position)
6442 (goto-char opoint
)))
6443 (inhibit-point-motion-hooks nil
))
6444 (goto-char npoint
)))
6446 ;; If we did not move up as far as desired,
6447 ;; at least go to beginning of line.
6448 (let* ((npoint (prog1 (line-beginning-position)
6449 (goto-char opoint
)))
6450 (inhibit-point-motion-hooks nil
))
6451 (goto-char npoint
)))
6453 (line-move-finish (or goal-column temporary-goal-column
)
6454 opoint
(> orig-arg
0)))))))
6456 (defun line-move-finish (column opoint forward
)
6459 ;; Set REPEAT to t to repeat the whole thing.
6464 (line-beg (line-beginning-position))
6466 ;; Compute the end of the line
6467 ;; ignoring effectively invisible newlines.
6469 ;; Like end-of-line but ignores fields.
6470 (skip-chars-forward "^\n")
6471 (while (and (not (eobp)) (invisible-p (point)))
6472 (goto-char (next-char-property-change (point)))
6473 (skip-chars-forward "^\n"))
6476 ;; Move to the desired column.
6477 (if (and line-move-visual
6478 (not (or truncate-lines truncate-partial-width-windows
)))
6479 ;; Under line-move-visual, goal-column should be
6480 ;; interpreted in units of the frame's canonical character
6481 ;; width, which is exactly what vertical-motion does.
6482 (vertical-motion (cons column
0))
6483 (line-move-to-column (truncate column
)))
6485 ;; Corner case: suppose we start out in a field boundary in
6486 ;; the middle of a continued line. When we get to
6487 ;; line-move-finish, point is at the start of a new *screen*
6488 ;; line but the same text line; then line-move-to-column would
6489 ;; move us backwards. Test using C-n with point on the "x" in
6490 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6497 ;; Process intangibility within a line.
6498 ;; With inhibit-point-motion-hooks bound to nil, a call to
6499 ;; goto-char moves point past intangible text.
6501 ;; However, inhibit-point-motion-hooks controls both the
6502 ;; intangibility and the point-entered/point-left hooks. The
6503 ;; following hack avoids calling the point-* hooks
6504 ;; unnecessarily. Note that we move *forward* past intangible
6505 ;; text when the initial and final points are the same.
6507 (let ((inhibit-point-motion-hooks nil
))
6510 ;; If intangibility moves us to a different (later) place
6511 ;; in the same line, use that as the destination.
6512 (if (<= (point) line-end
)
6514 ;; If that position is "too late",
6515 ;; try the previous allowable position.
6519 ;; If going forward, don't accept the previous
6520 ;; allowable position if it is before the target line.
6521 (< line-beg
(point))
6522 ;; If going backward, don't accept the previous
6523 ;; allowable position if it is still after the target line.
6524 (<= (point) line-end
))
6526 ;; As a last resort, use the end of the line.
6527 (setq new line-end
))))
6529 ;; Now move to the updated destination, processing fields
6530 ;; as well as intangibility.
6532 (let ((inhibit-point-motion-hooks nil
))
6534 ;; Ignore field boundaries if the initial and final
6535 ;; positions have the same `field' property, even if the
6536 ;; fields are non-contiguous. This seems to be "nicer"
6537 ;; behavior in many situations.
6538 (if (eq (get-char-property new
'field
)
6539 (get-char-property opoint
'field
))
6541 (constrain-to-field new opoint t t
6542 'inhibit-line-move-field-capture
))))
6544 ;; If all this moved us to a different line,
6545 ;; retry everything within that new line.
6546 (when (or (< (point) line-beg
) (> (point) line-end
))
6547 ;; Repeat the intangibility and field processing.
6548 (setq repeat t
))))))
6550 (defun line-move-to-column (col)
6551 "Try to find column COL, considering invisibility.
6552 This function works only in certain cases,
6553 because what we really need is for `move-to-column'
6554 and `current-column' to be able to ignore invisible text."
6557 (move-to-column col
))
6559 (when (and line-move-ignore-invisible
6560 (not (bolp)) (invisible-p (1- (point))))
6561 (let ((normal-location (point))
6562 (normal-column (current-column)))
6563 ;; If the following character is currently invisible,
6564 ;; skip all characters with that same `invisible' property value.
6565 (while (and (not (eobp))
6566 (invisible-p (point)))
6567 (goto-char (next-char-property-change (point))))
6568 ;; Have we advanced to a larger column position?
6569 (if (> (current-column) normal-column
)
6570 ;; We have made some progress towards the desired column.
6571 ;; See if we can make any further progress.
6572 (line-move-to-column (+ (current-column) (- col normal-column
)))
6573 ;; Otherwise, go to the place we originally found
6574 ;; and move back over invisible text.
6575 ;; that will get us to the same place on the screen
6576 ;; but with a more reasonable buffer position.
6577 (goto-char normal-location
)
6579 ;; We want the real line beginning, so it's consistent
6580 ;; with bolp below, otherwise we might infloop.
6581 (let ((inhibit-field-text-motion t
))
6582 (line-beginning-position))))
6583 (while (and (not (bolp)) (invisible-p (1- (point))))
6584 (goto-char (previous-char-property-change (point) line-beg
))))))))
6586 (defun move-end-of-line (arg)
6587 "Move point to end of current line as displayed.
6588 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6589 If point reaches the beginning or end of buffer, it stops there.
6591 To ignore the effects of the `intangible' text or overlay
6592 property, bind `inhibit-point-motion-hooks' to t.
6593 If there is an image in the current line, this function
6594 disregards newlines that are part of the text on which the image
6597 (or arg
(setq arg
1))
6602 (let ((goal-column 0)
6603 (line-move-visual nil
))
6604 (and (line-move arg t
)
6605 ;; With bidi reordering, we may not be at bol,
6606 ;; so make sure we are.
6607 (skip-chars-backward "^\n")
6610 (while (and (not (bobp)) (invisible-p (1- (point))))
6611 (goto-char (previous-single-char-property-change
6612 (point) 'invisible
)))
6616 (if (and (> (point) newpos
)
6617 (eq (preceding-char) ?
\n))
6619 (if (and (> (point) newpos
) (not (eobp))
6620 (not (eq (following-char) ?
\n)))
6621 ;; If we skipped something intangible and now we're not
6622 ;; really at eol, keep going.
6626 (defun move-beginning-of-line (arg)
6627 "Move point to beginning of current line as displayed.
6628 \(If there's an image in the line, this disregards newlines
6629 which are part of the text that the image rests on.)
6631 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6632 If point reaches the beginning or end of buffer, it stops there.
6633 \(But if the buffer doesn't end in a newline, it stops at the
6634 beginning of the last line.)
6635 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6637 (or arg
(setq arg
1))
6639 (let ((orig (point))
6640 first-vis first-vis-field-value
)
6642 ;; Move by lines, if ARG is not 1 (the default).
6644 (let ((line-move-visual nil
))
6645 (line-move (1- arg
) t
)))
6647 ;; Move to beginning-of-line, ignoring fields and invisible text.
6648 (skip-chars-backward "^\n")
6649 (while (and (not (bobp)) (invisible-p (1- (point))))
6650 (goto-char (previous-char-property-change (point)))
6651 (skip-chars-backward "^\n"))
6653 ;; Now find first visible char in the line.
6654 (while (and (< (point) orig
) (invisible-p (point)))
6655 (goto-char (next-char-property-change (point) orig
)))
6656 (setq first-vis
(point))
6658 ;; See if fields would stop us from reaching FIRST-VIS.
6659 (setq first-vis-field-value
6660 (constrain-to-field first-vis orig
(/= arg
1) t nil
))
6662 (goto-char (if (/= first-vis-field-value first-vis
)
6663 ;; If yes, obey them.
6664 first-vis-field-value
6665 ;; Otherwise, move to START with attention to fields.
6666 ;; (It is possible that fields never matter in this case.)
6667 (constrain-to-field (point) orig
6668 (/= arg
1) t nil
)))))
6671 ;; Many people have said they rarely use this feature, and often type
6672 ;; it by accident. Maybe it shouldn't even be on a key.
6673 (put 'set-goal-column
'disabled t
)
6675 (defun set-goal-column (arg)
6676 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6677 Those commands will move to this position in the line moved to
6678 rather than trying to keep the same horizontal position.
6679 With a non-nil argument ARG, clears out the goal column
6680 so that \\[next-line] and \\[previous-line] resume vertical motion.
6681 The goal column is stored in the variable `goal-column'.
6682 This is a buffer-local setting."
6686 (setq goal-column nil
)
6687 (message "No goal column"))
6688 (setq goal-column
(current-column))
6689 ;; The older method below can be erroneous if `set-goal-column' is bound
6690 ;; to a sequence containing %
6691 ;;(message (substitute-command-keys
6692 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6696 (format "Goal column %d " goal-column
)
6697 (substitute-command-keys
6698 "(use \\[set-goal-column] with an arg to unset it)")))
6703 ;;; Editing based on visual lines, as opposed to logical lines.
6705 (defun end-of-visual-line (&optional n
)
6706 "Move point to end of current visual line.
6707 With argument N not nil or 1, move forward N - 1 visual lines first.
6708 If point reaches the beginning or end of buffer, it stops there.
6709 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6713 (let ((line-move-visual t
))
6714 (line-move (1- n
) t
)))
6715 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6716 ;; constrain to field boundaries, so we don't either.
6717 (vertical-motion (cons (window-width) 0)))
6719 (defun beginning-of-visual-line (&optional n
)
6720 "Move point to beginning of current visual line.
6721 With argument N not nil or 1, move forward N - 1 visual lines first.
6722 If point reaches the beginning or end of buffer, it stops there.
6723 \(But if the buffer doesn't end in a newline, it stops at the
6724 beginning of the last visual line.)
6725 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6728 (let ((opoint (point)))
6730 (let ((line-move-visual t
))
6731 (line-move (1- n
) t
)))
6733 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6734 (goto-char (constrain-to-field (point) opoint
(/= n
1)))))
6736 (defun kill-visual-line (&optional arg
)
6737 "Kill the rest of the visual line.
6738 With prefix argument ARG, kill that many visual lines from point.
6739 If ARG is negative, kill visual lines backward.
6740 If ARG is zero, kill the text before point on the current visual
6743 If you want to append the killed line to the last killed text,
6744 use \\[append-next-kill] before \\[kill-line].
6746 If the buffer is read-only, Emacs will beep and refrain from deleting
6747 the line, but put the line in the kill ring anyway. This means that
6748 you can use this command to copy text from a read-only buffer.
6749 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6752 ;; Like in `kill-line', it's better to move point to the other end
6753 ;; of the kill before killing.
6754 (let ((opoint (point))
6755 (kill-whole-line (and kill-whole-line
(bolp))))
6757 (vertical-motion (prefix-numeric-value arg
))
6758 (end-of-visual-line 1)
6759 (if (= (point) opoint
)
6761 ;; Skip any trailing whitespace at the end of the visual line.
6762 ;; We used to do this only if `show-trailing-whitespace' is
6763 ;; nil, but that's wrong; the correct thing would be to check
6764 ;; whether the trailing whitespace is highlighted. But, it's
6765 ;; OK to just do this unconditionally.
6766 (skip-chars-forward " \t")))
6767 (kill-region opoint
(if (and kill-whole-line
(= (following-char) ?
\n))
6771 (defun next-logical-line (&optional arg try-vscroll
)
6772 "Move cursor vertically down ARG lines.
6773 This is identical to `next-line', except that it always moves
6774 by logical lines instead of visual lines, ignoring the value of
6775 the variable `line-move-visual'."
6776 (interactive "^p\np")
6777 (let ((line-move-visual nil
))
6779 (next-line arg try-vscroll
))))
6781 (defun previous-logical-line (&optional arg try-vscroll
)
6782 "Move cursor vertically up ARG lines.
6783 This is identical to `previous-line', except that it always moves
6784 by logical lines instead of visual lines, ignoring the value of
6785 the variable `line-move-visual'."
6786 (interactive "^p\np")
6787 (let ((line-move-visual nil
))
6789 (previous-line arg try-vscroll
))))
6791 (defgroup visual-line nil
6792 "Editing based on visual lines."
6796 (defvar visual-line-mode-map
6797 (let ((map (make-sparse-keymap)))
6798 (define-key map
[remap kill-line
] 'kill-visual-line
)
6799 (define-key map
[remap move-beginning-of-line
] 'beginning-of-visual-line
)
6800 (define-key map
[remap move-end-of-line
] 'end-of-visual-line
)
6801 ;; These keybindings interfere with xterm function keys. Are
6802 ;; there any other suitable bindings?
6803 ;; (define-key map "\M-[" 'previous-logical-line)
6804 ;; (define-key map "\M-]" 'next-logical-line)
6807 (defcustom visual-line-fringe-indicators
'(nil nil
)
6808 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6809 The value should be a list of the form (LEFT RIGHT), where LEFT
6810 and RIGHT are symbols representing the bitmaps to display, to
6811 indicate wrapped lines, in the left and right fringes respectively.
6812 See also `fringe-indicator-alist'.
6813 The default is not to display fringe indicators for wrapped lines.
6814 This variable does not affect fringe indicators displayed for
6816 :type
'(list (choice (const :tag
"Hide left indicator" nil
)
6817 (const :tag
"Left curly arrow" left-curly-arrow
)
6818 (symbol :tag
"Other bitmap"))
6819 (choice (const :tag
"Hide right indicator" nil
)
6820 (const :tag
"Right curly arrow" right-curly-arrow
)
6821 (symbol :tag
"Other bitmap")))
6822 :set
(lambda (symbol value
)
6823 (dolist (buf (buffer-list))
6824 (with-current-buffer buf
6825 (when (and (boundp 'visual-line-mode
)
6826 (symbol-value 'visual-line-mode
))
6827 (setq fringe-indicator-alist
6828 (cons (cons 'continuation value
)
6831 (copy-tree fringe-indicator-alist
)))))))
6832 (set-default symbol value
)))
6834 (defvar visual-line--saved-state nil
)
6836 (define-minor-mode visual-line-mode
6837 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6838 Interactively, with a prefix argument, enable
6839 Visual Line mode if the prefix argument is positive,
6840 and disable it otherwise. If called from Lisp, toggle
6841 the mode if ARG is `toggle', disable the mode if ARG is
6842 a non-positive integer, and enable the mode otherwise
6843 \(including if ARG is omitted or nil or a positive integer).
6845 When Visual Line mode is enabled, `word-wrap' is turned on in
6846 this buffer, and simple editing commands are redefined to act on
6847 visual lines, not logical lines. See Info node `Visual Line
6849 :keymap visual-line-mode-map
6852 (if visual-line-mode
6854 (set (make-local-variable 'visual-line--saved-state
) nil
)
6855 ;; Save the local values of some variables, to be restored if
6856 ;; visual-line-mode is turned off.
6857 (dolist (var '(line-move-visual truncate-lines
6858 truncate-partial-width-windows
6859 word-wrap fringe-indicator-alist
))
6860 (if (local-variable-p var
)
6861 (push (cons var
(symbol-value var
))
6862 visual-line--saved-state
)))
6863 (set (make-local-variable 'line-move-visual
) t
)
6864 (set (make-local-variable 'truncate-partial-width-windows
) nil
)
6865 (setq truncate-lines nil
6867 fringe-indicator-alist
6868 (cons (cons 'continuation visual-line-fringe-indicators
)
6869 fringe-indicator-alist
)))
6870 (kill-local-variable 'line-move-visual
)
6871 (kill-local-variable 'word-wrap
)
6872 (kill-local-variable 'truncate-lines
)
6873 (kill-local-variable 'truncate-partial-width-windows
)
6874 (kill-local-variable 'fringe-indicator-alist
)
6875 (dolist (saved visual-line--saved-state
)
6876 (set (make-local-variable (car saved
)) (cdr saved
)))
6877 (kill-local-variable 'visual-line--saved-state
)))
6879 (defun turn-on-visual-line-mode ()
6880 (visual-line-mode 1))
6882 (define-globalized-minor-mode global-visual-line-mode
6883 visual-line-mode turn-on-visual-line-mode
)
6886 (defun transpose-chars (arg)
6887 "Interchange characters around point, moving forward one character.
6888 With prefix arg ARG, effect is to take character before point
6889 and drag it forward past ARG other characters (backward if ARG negative).
6890 If no argument and at end of line, the previous two chars are exchanged."
6892 (when (and (null arg
) (eolp) (not (bobp))
6893 (not (get-text-property (1- (point)) 'read-only
)))
6895 (transpose-subr 'forward-char
(prefix-numeric-value arg
)))
6897 (defun transpose-words (arg)
6898 "Interchange words around point, leaving point at end of them.
6899 With prefix arg ARG, effect is to take word before or around point
6900 and drag it forward past ARG other words (backward if ARG negative).
6901 If ARG is zero, the words around or after point and around or after mark
6903 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6905 (transpose-subr 'forward-word arg
))
6907 (defun transpose-sexps (arg)
6908 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6909 Unlike `transpose-words', point must be between the two sexps and not
6910 in the middle of a sexp to be transposed.
6911 With non-zero prefix arg ARG, effect is to take the sexp before point
6912 and drag it forward past ARG other sexps (backward if ARG is negative).
6913 If ARG is zero, the sexps ending at or after point and at or after mark
6918 ;; Here we should try to simulate the behavior of
6919 ;; (cons (progn (forward-sexp x) (point))
6920 ;; (progn (forward-sexp (- x)) (point)))
6921 ;; Except that we don't want to rely on the second forward-sexp
6922 ;; putting us back to where we want to be, since forward-sexp-function
6923 ;; might do funny things like infix-precedence.
6925 (looking-at "\\sw\\|\\s_")
6927 (save-excursion (forward-char -
1) (looking-at "\\sw\\|\\s_"))))
6928 ;; Jumping over a symbol. We might be inside it, mind you.
6929 (progn (funcall (if (> arg
0)
6930 'skip-syntax-backward
'skip-syntax-forward
)
6932 (cons (save-excursion (forward-sexp arg
) (point)) (point)))
6933 ;; Otherwise, we're between sexps. Take a step back before jumping
6934 ;; to make sure we'll obey the same precedence no matter which direction
6936 (funcall (if (> arg
0) 'skip-syntax-backward
'skip-syntax-forward
) " .")
6937 (cons (save-excursion (forward-sexp arg
) (point))
6938 (progn (while (or (forward-comment (if (> arg
0) 1 -
1))
6939 (not (zerop (funcall (if (> arg
0)
6940 'skip-syntax-forward
6941 'skip-syntax-backward
)
6946 (defun transpose-lines (arg)
6947 "Exchange current line and previous line, leaving point after both.
6948 With argument ARG, takes previous line and moves it past ARG lines.
6949 With argument 0, interchanges line point is in with line mark is in."
6951 (transpose-subr (function
6955 ;; Move forward over ARG lines,
6956 ;; but create newlines if necessary.
6957 (setq arg
(forward-line arg
))
6958 (if (/= (preceding-char) ?
\n)
6959 (setq arg
(1+ arg
)))
6962 (forward-line arg
))))
6965 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6966 ;; which seems inconsistent with the ARG /= 0 case.
6967 ;; FIXME document SPECIAL.
6968 (defun transpose-subr (mover arg
&optional special
)
6969 "Subroutine to do the work of transposing objects.
6970 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6971 moves forward by units of the given object (e.g. forward-sentence,
6972 forward-paragraph). If ARG is zero, exchanges the current object
6973 with the one containing mark. If ARG is an integer, moves the
6974 current object past ARG following (if ARG is positive) or
6975 preceding (if ARG is negative) objects, leaving point after the
6977 (let ((aux (if special mover
6979 (cons (progn (funcall mover x
) (point))
6980 (progn (funcall mover
(- x
)) (point))))))
6985 (setq pos1
(funcall aux
1))
6986 (goto-char (or (mark) (error "No mark set in this buffer")))
6987 (setq pos2
(funcall aux
1))
6988 (transpose-subr-1 pos1 pos2
))
6989 (exchange-point-and-mark))
6991 (setq pos1
(funcall aux -
1))
6992 (setq pos2
(funcall aux arg
))
6993 (transpose-subr-1 pos1 pos2
)
6994 (goto-char (car pos2
)))
6996 (setq pos1
(funcall aux -
1))
6997 (goto-char (car pos1
))
6998 (setq pos2
(funcall aux arg
))
6999 (transpose-subr-1 pos1 pos2
)
7000 (goto-char (+ (car pos2
) (- (cdr pos1
) (car pos1
))))))))
7002 (defun transpose-subr-1 (pos1 pos2
)
7003 (when (> (car pos1
) (cdr pos1
)) (setq pos1
(cons (cdr pos1
) (car pos1
))))
7004 (when (> (car pos2
) (cdr pos2
)) (setq pos2
(cons (cdr pos2
) (car pos2
))))
7005 (when (> (car pos1
) (car pos2
))
7007 (setq pos1 pos2 pos2 swap
)))
7008 (if (> (cdr pos1
) (car pos2
)) (error "Don't have two things to transpose"))
7009 (atomic-change-group
7010 ;; This sequence of insertions attempts to preserve marker
7011 ;; positions at the start and end of the transposed objects.
7012 (let* ((word (buffer-substring (car pos2
) (cdr pos2
)))
7013 (len1 (- (cdr pos1
) (car pos1
)))
7014 (len2 (length word
))
7015 (boundary (make-marker)))
7016 (set-marker boundary
(car pos2
))
7017 (goto-char (cdr pos1
))
7018 (insert-before-markers word
)
7019 (setq word
(delete-and-extract-region (car pos1
) (+ (car pos1
) len1
)))
7020 (goto-char boundary
)
7022 (goto-char (+ boundary len1
))
7023 (delete-region (point) (+ (point) len2
))
7024 (set-marker boundary nil
))))
7026 (defun backward-word (&optional arg
)
7027 "Move backward until encountering the beginning of a word.
7028 With argument ARG, do this that many times.
7029 If ARG is omitted or nil, move point backward one word.
7031 The word boundaries are normally determined by the buffer's syntax
7032 table, but `find-word-boundary-function-table', such as set up
7033 by `subword-mode', can change that. If a Lisp program needs to
7034 move by words determined strictly by the syntax table, it should
7035 use `backward-word-strictly' instead."
7037 (forward-word (- (or arg
1))))
7039 (defun mark-word (&optional arg allow-extend
)
7040 "Set mark ARG words away from point.
7041 The place mark goes is the same place \\[forward-word] would
7042 move to with the same argument.
7043 Interactively, if this command is repeated
7044 or (in Transient Mark mode) if the mark is active,
7045 it marks the next ARG words after the ones already marked."
7046 (interactive "P\np")
7047 (cond ((and allow-extend
7048 (or (and (eq last-command this-command
) (mark t
))
7050 (setq arg
(if arg
(prefix-numeric-value arg
)
7051 (if (< (mark) (point)) -
1 1)))
7060 (forward-word (prefix-numeric-value arg
))
7064 (defun kill-word (arg)
7065 "Kill characters forward until encountering the end of a word.
7066 With argument ARG, do this that many times."
7068 (kill-region (point) (progn (forward-word arg
) (point))))
7070 (defun backward-kill-word (arg)
7071 "Kill characters backward until encountering the beginning of a word.
7072 With argument ARG, do this that many times."
7074 (kill-word (- arg
)))
7076 (defun current-word (&optional strict really-word
)
7077 "Return the word at or near point, as a string.
7078 The return value includes no text properties.
7080 If optional arg STRICT is non-nil, return nil unless point is
7081 within or adjacent to a word, otherwise look for a word within
7082 point's line. If there is no word anywhere on point's line, the
7083 value is nil regardless of STRICT.
7085 By default, this function treats as a single word any sequence of
7086 characters that have either word or symbol syntax. If optional
7087 arg REALLY-WORD is non-nil, only characters of word syntax can
7090 (let* ((oldpoint (point)) (start (point)) (end (point))
7091 (syntaxes (if really-word
"w" "w_"))
7092 (not-syntaxes (concat "^" syntaxes
)))
7093 (skip-syntax-backward syntaxes
) (setq start
(point))
7094 (goto-char oldpoint
)
7095 (skip-syntax-forward syntaxes
) (setq end
(point))
7096 (when (and (eq start oldpoint
) (eq end oldpoint
)
7097 ;; Point is neither within nor adjacent to a word.
7099 ;; Look for preceding word in same line.
7100 (skip-syntax-backward not-syntaxes
(line-beginning-position))
7102 ;; No preceding word in same line.
7103 ;; Look for following word in same line.
7105 (skip-syntax-forward not-syntaxes
(line-end-position))
7106 (setq start
(point))
7107 (skip-syntax-forward syntaxes
)
7110 (skip-syntax-backward syntaxes
)
7111 (setq start
(point))))
7112 ;; If we found something nonempty, return it as a string.
7113 (unless (= start end
)
7114 (buffer-substring-no-properties start end
)))))
7116 (defcustom fill-prefix nil
7117 "String for filling to insert at front of new line, or nil for none."
7118 :type
'(choice (const :tag
"None" nil
)
7121 (make-variable-buffer-local 'fill-prefix
)
7122 (put 'fill-prefix
'safe-local-variable
'string-or-null-p
)
7124 (defcustom auto-fill-inhibit-regexp nil
7125 "Regexp to match lines which should not be auto-filled."
7126 :type
'(choice (const :tag
"None" nil
)
7130 (defun do-auto-fill ()
7131 "The default value for `normal-auto-fill-function'.
7132 This is the default auto-fill function, some major modes use a different one.
7133 Returns t if it really did any work."
7134 (let (fc justify give-up
7135 (fill-prefix fill-prefix
))
7136 (if (or (not (setq justify
(current-justification)))
7137 (null (setq fc
(current-fill-column)))
7138 (and (eq justify
'left
)
7139 (<= (current-column) fc
))
7140 (and auto-fill-inhibit-regexp
7141 (save-excursion (beginning-of-line)
7142 (looking-at auto-fill-inhibit-regexp
))))
7143 nil
;; Auto-filling not required
7144 (if (memq justify
'(full center right
))
7145 (save-excursion (unjustify-current-line)))
7147 ;; Choose a fill-prefix automatically.
7148 (when (and adaptive-fill-mode
7149 (or (null fill-prefix
) (string= fill-prefix
"")))
7151 (fill-context-prefix
7152 (save-excursion (fill-forward-paragraph -
1) (point))
7153 (save-excursion (fill-forward-paragraph 1) (point)))))
7154 (and prefix
(not (equal prefix
""))
7155 ;; Use auto-indentation rather than a guessed empty prefix.
7156 (not (and fill-indent-according-to-mode
7157 (string-match "\\`[ \t]*\\'" prefix
)))
7158 (setq fill-prefix prefix
))))
7160 (while (and (not give-up
) (> (current-column) fc
))
7161 ;; Determine where to split the line.
7165 ;; Don't split earlier in the line than the length of the
7166 ;; fill prefix, since the resulting line would be longer.
7168 (move-to-column (string-width fill-prefix
)))
7169 (let ((after-prefix (point)))
7170 (move-to-column (1+ fc
))
7171 (fill-move-to-break-point after-prefix
)
7174 ;; See whether the place we found is any good.
7176 (goto-char fill-point
)
7178 ;; There is no use breaking at end of line.
7179 (save-excursion (skip-chars-forward " ") (eolp))
7180 ;; Don't split right after a comment starter
7181 ;; since we would just make another comment starter.
7182 (and comment-start-skip
7183 (let ((limit (point)))
7185 (and (re-search-forward comment-start-skip
7187 (eq (point) limit
))))))
7188 ;; No good place to break => stop trying.
7190 ;; Ok, we have a useful place to break the line. Do it.
7191 (let ((prev-column (current-column)))
7192 ;; If point is at the fill-point, do not `save-excursion'.
7193 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7194 ;; point will end up before it rather than after it.
7196 (skip-chars-backward " \t")
7197 (= (point) fill-point
))
7198 (default-indent-new-line t
)
7200 (goto-char fill-point
)
7201 (default-indent-new-line t
)))
7202 ;; Now do justification, if required
7203 (if (not (eq justify
'left
))
7206 (justify-current-line justify nil t
)))
7207 ;; If making the new line didn't reduce the hpos of
7208 ;; the end of the line, then give up now;
7209 ;; trying again will not help.
7210 (if (>= (current-column) prev-column
)
7211 (setq give-up t
))))))
7212 ;; Justify last line.
7213 (justify-current-line justify t t
)
7216 (defvar comment-line-break-function
'comment-indent-new-line
7217 "Mode-specific function which line breaks and continues a comment.
7218 This function is called during auto-filling when a comment syntax
7220 The function should take a single optional argument, which is a flag
7221 indicating whether it should use soft newlines.")
7223 (defun default-indent-new-line (&optional soft
)
7224 "Break line at point and indent.
7225 If a comment syntax is defined, call `comment-indent-new-line'.
7227 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7228 unless optional argument SOFT is non-nil."
7231 (funcall comment-line-break-function soft
)
7232 ;; Insert the newline before removing empty space so that markers
7233 ;; get preserved better.
7234 (if soft
(insert-and-inherit ?
\n) (newline 1))
7235 (save-excursion (forward-char -
1) (delete-horizontal-space))
7236 (delete-horizontal-space)
7238 (if (and fill-prefix
(not adaptive-fill-mode
))
7239 ;; Blindly trust a non-adaptive fill-prefix.
7241 (indent-to-left-margin)
7242 (insert-before-markers-and-inherit fill-prefix
))
7245 ;; If there's an adaptive prefix, use it unless we're inside
7246 ;; a comment and the prefix is not a comment starter.
7248 (indent-to-left-margin)
7249 (insert-and-inherit fill-prefix
))
7250 ;; If we're not inside a comment, just try to indent.
7251 (t (indent-according-to-mode))))))
7253 (defun internal-auto-fill ()
7254 "The function called by `self-insert-command' to perform auto-filling."
7255 (when (or (not comment-start
)
7256 (not comment-auto-fill-only-comments
)
7257 (nth 4 (syntax-ppss)))
7258 (funcall auto-fill-function
)))
7260 (defvar normal-auto-fill-function
'do-auto-fill
7261 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7262 Some major modes set this.")
7264 (put 'auto-fill-function
:minor-mode-function
'auto-fill-mode
)
7265 ;; `functions' and `hooks' are usually unsafe to set, but setting
7266 ;; auto-fill-function to nil in a file-local setting is safe and
7267 ;; can be useful to prevent auto-filling.
7268 (put 'auto-fill-function
'safe-local-variable
'null
)
7270 (define-minor-mode auto-fill-mode
7271 "Toggle automatic line breaking (Auto Fill mode).
7272 Interactively, with a prefix argument, enable
7273 Auto Fill mode if the prefix argument is positive,
7274 and disable it otherwise. If called from Lisp, toggle
7275 the mode if ARG is `toggle', disable the mode if ARG is
7276 a non-positive integer, and enable the mode otherwise
7277 \(including if ARG is omitted or nil or a positive integer).
7279 When Auto Fill mode is enabled, inserting a space at a column
7280 beyond `current-fill-column' automatically breaks the line at a
7283 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7286 The value of `normal-auto-fill-function' specifies the function to use
7287 for `auto-fill-function' when turning Auto Fill mode on."
7288 :variable
(auto-fill-function
7289 .
(lambda (v) (setq auto-fill-function
7290 (if v normal-auto-fill-function
)))))
7292 ;; This holds a document string used to document auto-fill-mode.
7293 (defun auto-fill-function ()
7294 "Automatically break line at a previous space, in insertion of text."
7297 (defun turn-on-auto-fill ()
7298 "Unconditionally turn on Auto Fill mode."
7301 (defun turn-off-auto-fill ()
7302 "Unconditionally turn off Auto Fill mode."
7303 (auto-fill-mode -
1))
7305 (custom-add-option 'text-mode-hook
'turn-on-auto-fill
)
7307 (defun set-fill-column (arg)
7308 "Set `fill-column' to specified argument.
7309 Use \\[universal-argument] followed by a number to specify a column.
7310 Just \\[universal-argument] as argument means to use the current column."
7312 (list (or current-prefix-arg
7313 ;; We used to use current-column silently, but C-x f is too easily
7314 ;; typed as a typo for C-x C-f, so we turned it into an error and
7315 ;; now an interactive prompt.
7316 (read-number "Set fill-column to: " (current-column)))))
7318 (setq arg
(current-column)))
7319 (if (not (integerp arg
))
7320 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7321 (error "set-fill-column requires an explicit argument")
7322 (message "Fill column set to %d (was %d)" arg fill-column
)
7323 (setq fill-column arg
)))
7325 (defun set-selective-display (arg)
7326 "Set `selective-display' to ARG; clear it if no arg.
7327 When the value of `selective-display' is a number > 0,
7328 lines whose indentation is >= that value are not displayed.
7329 The variable `selective-display' has a separate value for each buffer."
7331 (if (eq selective-display t
)
7332 (error "selective-display already in use for marked lines"))
7335 (narrow-to-region (point-min) (point))
7336 (goto-char (window-start))
7337 (vertical-motion (window-height)))))
7338 (setq selective-display
7339 (and arg
(prefix-numeric-value arg
)))
7340 (recenter current-vpos
))
7341 (set-window-start (selected-window) (window-start))
7342 (princ "selective-display set to " t
)
7343 (prin1 selective-display t
)
7346 (defvaralias 'indicate-unused-lines
'indicate-empty-lines
)
7348 (defun toggle-truncate-lines (&optional arg
)
7349 "Toggle truncating of long lines for the current buffer.
7350 When truncating is off, long lines are folded.
7351 With prefix argument ARG, truncate long lines if ARG is positive,
7352 otherwise fold them. Note that in side-by-side windows, this
7353 command has no effect if `truncate-partial-width-windows' is
7356 (setq truncate-lines
7358 (not truncate-lines
)
7359 (> (prefix-numeric-value arg
) 0)))
7360 (force-mode-line-update)
7361 (unless truncate-lines
7362 (let ((buffer (current-buffer)))
7363 (walk-windows (lambda (window)
7364 (if (eq buffer
(window-buffer window
))
7365 (set-window-hscroll window
0)))
7367 (message "Truncate long lines %s"
7368 (if truncate-lines
"enabled" "disabled")))
7370 (defun toggle-word-wrap (&optional arg
)
7371 "Toggle whether to use word-wrapping for continuation lines.
7372 With prefix argument ARG, wrap continuation lines at word boundaries
7373 if ARG is positive, otherwise wrap them at the right screen edge.
7374 This command toggles the value of `word-wrap'. It has no effect
7375 if long lines are truncated."
7380 (> (prefix-numeric-value arg
) 0)))
7381 (force-mode-line-update)
7382 (message "Word wrapping %s"
7383 (if word-wrap
"enabled" "disabled")))
7385 (defvar overwrite-mode-textual
(purecopy " Ovwrt")
7386 "The string displayed in the mode line when in overwrite mode.")
7387 (defvar overwrite-mode-binary
(purecopy " Bin Ovwrt")
7388 "The string displayed in the mode line when in binary overwrite mode.")
7390 (define-minor-mode overwrite-mode
7391 "Toggle Overwrite mode.
7392 With a prefix argument ARG, enable Overwrite mode if ARG is
7393 positive, and disable it otherwise. If called from Lisp, enable
7394 the mode if ARG is omitted or nil.
7396 When Overwrite mode is enabled, printing characters typed in
7397 replace existing text on a one-for-one basis, rather than pushing
7398 it to the right. At the end of a line, such characters extend
7399 the line. Before a tab, such characters insert until the tab is
7400 filled in. \\[quoted-insert] still inserts characters in
7401 overwrite mode; this is supposed to make it easier to insert
7402 characters when necessary."
7403 :variable
(overwrite-mode
7404 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-textual
)))))
7406 (define-minor-mode binary-overwrite-mode
7407 "Toggle Binary Overwrite mode.
7408 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7409 is positive, and disable it otherwise. If called from Lisp,
7410 enable the mode if ARG is omitted or nil.
7412 When Binary Overwrite mode is enabled, printing characters typed
7413 in replace existing text. Newlines are not treated specially, so
7414 typing at the end of a line joins the line to the next, with the
7415 typed character between them. Typing before a tab character
7416 simply replaces the tab with the character typed.
7417 \\[quoted-insert] replaces the text at the cursor, just as
7418 ordinary typing characters do.
7420 Note that Binary Overwrite mode is not its own minor mode; it is
7421 a specialization of overwrite mode, entered by setting the
7422 `overwrite-mode' variable to `overwrite-mode-binary'."
7423 :variable
(overwrite-mode
7424 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-binary
)))))
7426 (define-minor-mode line-number-mode
7427 "Toggle line number display in the mode line (Line Number mode).
7428 With a prefix argument ARG, enable Line Number mode if ARG is
7429 positive, and disable it otherwise. If called from Lisp, enable
7430 the mode if ARG is omitted or nil.
7432 Line numbers do not appear for very large buffers and buffers
7433 with very long lines; see variables `line-number-display-limit'
7434 and `line-number-display-limit-width'."
7435 :init-value t
:global t
:group
'mode-line
)
7437 (define-minor-mode column-number-mode
7438 "Toggle column number display in the mode line (Column Number mode).
7439 With a prefix argument ARG, enable Column Number mode if ARG is
7440 positive, and disable it otherwise.
7442 If called from Lisp, enable the mode if ARG is omitted or nil."
7443 :global t
:group
'mode-line
)
7445 (define-minor-mode size-indication-mode
7446 "Toggle buffer size display in the mode line (Size Indication mode).
7447 With a prefix argument ARG, enable Size Indication mode if ARG is
7448 positive, and disable it otherwise.
7450 If called from Lisp, enable the mode if ARG is omitted or nil."
7451 :global t
:group
'mode-line
)
7453 (define-minor-mode auto-save-mode
7454 "Toggle auto-saving in the current buffer (Auto Save mode).
7455 With a prefix argument ARG, enable Auto Save mode if ARG is
7456 positive, and disable it otherwise.
7458 If called from Lisp, enable the mode if ARG is omitted or nil."
7459 :variable
((and buffer-auto-save-file-name
7460 ;; If auto-save is off because buffer has shrunk,
7461 ;; then toggling should turn it on.
7462 (>= buffer-saved-size
0))
7464 (setq buffer-auto-save-file-name
7467 ((and buffer-file-name auto-save-visited-file-name
7468 (not buffer-read-only
))
7470 (t (make-auto-save-file-name))))))
7471 ;; If -1 was stored here, to temporarily turn off saving,
7473 (and (< buffer-saved-size
0)
7474 (setq buffer-saved-size
0)))
7476 (defgroup paren-blinking nil
7477 "Blinking matching of parens and expressions."
7478 :prefix
"blink-matching-"
7479 :group
'paren-matching
)
7481 (defcustom blink-matching-paren t
7482 "Non-nil means show matching open-paren when close-paren is inserted.
7483 If t, highlight the paren. If `jump', briefly move cursor to its
7484 position. If `jump-offscreen', move cursor there even if the
7485 position is off screen. With any other non-nil value, the
7486 off-screen position of the opening paren will be shown in the
7489 (const :tag
"Disable" nil
)
7490 (const :tag
"Highlight" t
)
7491 (const :tag
"Move cursor" jump
)
7492 (const :tag
"Move cursor, even if off screen" jump-offscreen
))
7493 :group
'paren-blinking
)
7495 (defcustom blink-matching-paren-on-screen t
7496 "Non-nil means show matching open-paren when it is on screen.
7497 If nil, don't show it (but the open-paren can still be shown
7498 in the echo area when it is off screen).
7500 This variable has no effect if `blink-matching-paren' is nil.
7501 \(In that case, the open-paren is never shown.)
7502 It is also ignored if `show-paren-mode' is enabled."
7504 :group
'paren-blinking
)
7506 (defcustom blink-matching-paren-distance
(* 100 1024)
7507 "If non-nil, maximum distance to search backwards for matching open-paren.
7508 If nil, search stops at the beginning of the accessible portion of the buffer."
7509 :version
"23.2" ; 25->100k
7510 :type
'(choice (const nil
) integer
)
7511 :group
'paren-blinking
)
7513 (defcustom blink-matching-delay
1
7514 "Time in seconds to delay after showing a matching paren."
7516 :group
'paren-blinking
)
7518 (defcustom blink-matching-paren-dont-ignore-comments nil
7519 "If nil, `blink-matching-paren' ignores comments.
7520 More precisely, when looking for the matching parenthesis,
7521 it skips the contents of comments that end before point."
7523 :group
'paren-blinking
)
7525 (defun blink-matching-check-mismatch (start end
)
7526 "Return whether or not START...END are matching parens.
7527 END is the current point and START is the blink position.
7528 START might be nil if no matching starter was found.
7529 Returns non-nil if we find there is a mismatch."
7530 (let* ((end-syntax (syntax-after (1- end
)))
7531 (matching-paren (and (consp end-syntax
)
7532 (eq (syntax-class end-syntax
) 5)
7534 ;; For self-matched chars like " and $, we can't know when they're
7535 ;; mismatched or unmatched, so we can only do it for parens.
7536 (when matching-paren
7539 (eq (char-after start
) matching-paren
)
7540 ;; The cdr might hold a new paren-class info rather than
7541 ;; a matching-char info, in which case the two CDRs
7543 (eq matching-paren
(cdr-safe (syntax-after start
)))))))))
7545 (defvar blink-matching-check-function
#'blink-matching-check-mismatch
7546 "Function to check parentheses mismatches.
7547 The function takes two arguments (START and END) where START is the
7548 position just before the opening token and END is the position right after.
7549 START can be nil, if it was not found.
7550 The function should return non-nil if the two tokens do not match.")
7552 (defvar blink-matching--overlay
7553 (let ((ol (make-overlay (point) (point) nil t
)))
7554 (overlay-put ol
'face
'show-paren-match
)
7557 "Overlay used to highlight the matching paren.")
7559 (defun blink-matching-open ()
7560 "Momentarily highlight the beginning of the sexp before point."
7562 (when (and (not (bobp))
7563 blink-matching-paren
)
7564 (let* ((oldpos (point))
7565 (message-log-max nil
) ; Don't log messages about paren matching.
7569 (if blink-matching-paren-distance
7571 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7572 (- (point) blink-matching-paren-distance
))
7574 (let ((parse-sexp-ignore-comments
7575 (and parse-sexp-ignore-comments
7576 (not blink-matching-paren-dont-ignore-comments
))))
7579 (syntax-propertize (point))
7581 ;; backward-sexp skips backward over prefix chars,
7582 ;; so move back to the matching paren.
7583 (while (and (< (point) (1- oldpos
))
7584 (let ((code (syntax-after (point))))
7585 (or (eq (syntax-class code
) 6)
7586 (eq (logand 1048576 (car code
))
7591 (mismatch (funcall blink-matching-check-function blinkpos oldpos
)))
7596 (minibuffer-message "Mismatched parentheses")
7597 (message "Mismatched parentheses"))
7599 (minibuffer-message "No matching parenthesis found")
7600 (message "No matching parenthesis found"))))
7601 ((not blinkpos
) nil
)
7603 (eq blink-matching-paren
'jump-offscreen
)
7604 (pos-visible-in-window-p blinkpos
))
7605 ;; Matching open within window, temporarily move to or highlight
7606 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7608 (and blink-matching-paren-on-screen
7609 (not show-paren-mode
)
7610 (if (memq blink-matching-paren
'(jump jump-offscreen
))
7612 (goto-char blinkpos
)
7613 (sit-for blink-matching-delay
))
7616 (move-overlay blink-matching--overlay blinkpos
(1+ blinkpos
)
7618 (sit-for blink-matching-delay
))
7619 (delete-overlay blink-matching--overlay
)))))
7621 (let ((open-paren-line-string
7623 (goto-char blinkpos
)
7624 ;; Show what precedes the open in its line, if anything.
7626 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7627 (buffer-substring (line-beginning-position)
7629 ;; Show what follows the open in its line, if anything.
7632 (skip-chars-forward " \t")
7634 (buffer-substring blinkpos
7635 (line-end-position)))
7636 ;; Otherwise show the previous nonblank line,
7638 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7640 (buffer-substring (progn
7641 (skip-chars-backward "\n \t")
7642 (line-beginning-position))
7643 (progn (end-of-line)
7644 (skip-chars-backward " \t")
7646 ;; Replace the newline and other whitespace with `...'.
7648 (buffer-substring blinkpos
(1+ blinkpos
))))
7649 ;; There is nothing to show except the char itself.
7650 (t (buffer-substring blinkpos
(1+ blinkpos
)))))))
7653 (substring-no-properties open-paren-line-string
))))))))
7655 (defvar blink-paren-function
'blink-matching-open
7656 "Function called, if non-nil, whenever a close parenthesis is inserted.
7657 More precisely, a char with closeparen syntax is self-inserted.")
7659 (defun blink-paren-post-self-insert-function ()
7660 (when (and (eq (char-before) last-command-event
) ; Sanity check.
7661 (memq (char-syntax last-command-event
) '(?\
) ?\$
))
7662 blink-paren-function
7663 (not executing-kbd-macro
)
7664 (not noninteractive
)
7665 ;; Verify an even number of quoting characters precede the close.
7666 ;; FIXME: Also check if this parenthesis closes a comment as
7667 ;; can happen in Pascal and SML.
7668 (= 1 (logand 1 (- (point)
7671 (skip-syntax-backward "/\\")
7673 (funcall blink-paren-function
)))
7675 (put 'blink-paren-post-self-insert-function
'priority
100)
7677 (add-hook 'post-self-insert-hook
#'blink-paren-post-self-insert-function
7678 ;; Most likely, this hook is nil, so this arg doesn't matter,
7679 ;; but I use it as a reminder that this function usually
7680 ;; likes to be run after others since it does
7681 ;; `sit-for'. That's also the reason it get a `priority' prop
7685 ;; This executes C-g typed while Emacs is waiting for a command.
7686 ;; Quitting out of a program does not go through here;
7687 ;; that happens in the maybe_quit function at the C code level.
7688 (defun keyboard-quit ()
7689 "Signal a `quit' condition.
7690 During execution of Lisp code, this character causes a quit directly.
7691 At top-level, as an editor command, this simply beeps."
7693 ;; Avoid adding the region to the window selection.
7694 (setq saved-region-selection nil
)
7695 (let (select-active-regions)
7697 (if (fboundp 'kmacro-keyboard-quit
)
7698 (kmacro-keyboard-quit))
7699 (when completion-in-region-mode
7700 (completion-in-region-mode -
1))
7701 ;; Force the next redisplay cycle to remove the "Def" indicator from
7702 ;; all the mode lines.
7703 (if defining-kbd-macro
7704 (force-mode-line-update t
))
7705 (setq defining-kbd-macro nil
)
7706 (let ((debug-on-quit nil
))
7707 (signal 'quit nil
)))
7709 (defvar buffer-quit-function nil
7710 "Function to call to \"quit\" the current buffer, or nil if none.
7711 \\[keyboard-escape-quit] calls this function when its more local actions
7712 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7714 (defun keyboard-escape-quit ()
7715 "Exit the current \"mode\" (in a generalized sense of the word).
7716 This command can exit an interactive command such as `query-replace',
7717 can clear out a prefix argument or a region,
7718 can get out of the minibuffer or other recursive edit,
7719 cancel the use of the current buffer (for special-purpose buffers),
7720 or go back to just one window (by deleting all but the selected window)."
7722 (cond ((eq last-command
'mode-exited
) nil
)
7725 ((> (minibuffer-depth) 0)
7726 (abort-recursive-edit))
7729 ((> (recursion-depth) 0)
7730 (exit-recursive-edit))
7731 (buffer-quit-function
7732 (funcall buffer-quit-function
))
7733 ((not (one-window-p t
))
7734 (delete-other-windows))
7735 ((string-match "^ \\*" (buffer-name (current-buffer)))
7738 (defun play-sound-file (file &optional volume device
)
7739 "Play sound stored in FILE.
7740 VOLUME and DEVICE correspond to the keywords of the sound
7741 specification for `play-sound'."
7742 (interactive "fPlay sound file: ")
7743 (let ((sound (list :file file
)))
7745 (plist-put sound
:volume volume
))
7747 (plist-put sound
:device device
))
7749 (play-sound sound
)))
7752 (defcustom read-mail-command
'rmail
7753 "Your preference for a mail reading package.
7754 This is used by some keybindings which support reading mail.
7755 See also `mail-user-agent' concerning sending mail."
7756 :type
'(radio (function-item :tag
"Rmail" :format
"%t\n" rmail
)
7757 (function-item :tag
"Gnus" :format
"%t\n" gnus
)
7758 (function-item :tag
"Emacs interface to MH"
7759 :format
"%t\n" mh-rmail
)
7760 (function :tag
"Other"))
7764 (defcustom mail-user-agent
'message-user-agent
7765 "Your preference for a mail composition package.
7766 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7767 outgoing email message. This variable lets you specify which
7768 mail-sending package you prefer.
7770 Valid values include:
7772 `message-user-agent' -- use the Message package.
7773 See Info node `(message)'.
7774 `sendmail-user-agent' -- use the Mail package.
7775 See Info node `(emacs)Sending Mail'.
7776 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7777 See Info node `(mh-e)'.
7778 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7779 paraphernalia if Gnus is running, particularly
7780 the Gcc: header for archiving.
7782 Additional valid symbols may be available; check with the author of
7783 your package for details. The function should return non-nil if it
7786 See also `read-mail-command' concerning reading mail."
7787 :type
'(radio (function-item :tag
"Message package"
7790 (function-item :tag
"Mail package"
7792 sendmail-user-agent
)
7793 (function-item :tag
"Emacs interface to MH"
7796 (function-item :tag
"Message with full Gnus features"
7799 (function :tag
"Other"))
7800 :version
"23.2" ; sendmail->message
7803 (defcustom compose-mail-user-agent-warnings t
7804 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7805 If the value of `mail-user-agent' is the default, and the user
7806 appears to have customizations applying to the old default,
7807 `compose-mail' issues a warning."
7812 (defun rfc822-goto-eoh ()
7813 "If the buffer starts with a mail header, move point to the header's end.
7814 Otherwise, moves to `point-min'.
7815 The end of the header is the start of the next line, if there is one,
7816 else the end of the last line. This function obeys RFC822."
7817 (goto-char (point-min))
7818 (when (re-search-forward
7819 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil
'move
)
7820 (goto-char (match-beginning 0))))
7822 ;; Used by Rmail (e.g., rmail-forward).
7823 (defvar mail-encode-mml nil
7824 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7825 the outgoing message before sending it.")
7827 (defun compose-mail (&optional to subject other-headers continue
7828 switch-function yank-action send-actions
7830 "Start composing a mail message to send.
7831 This uses the user's chosen mail composition package
7832 as selected with the variable `mail-user-agent'.
7833 The optional arguments TO and SUBJECT specify recipients
7834 and the initial Subject field, respectively.
7836 OTHER-HEADERS is an alist specifying additional
7837 header fields. Elements look like (HEADER . VALUE) where both
7838 HEADER and VALUE are strings.
7840 CONTINUE, if non-nil, says to continue editing a message already
7841 being composed. Interactively, CONTINUE is the prefix argument.
7843 SWITCH-FUNCTION, if non-nil, is a function to use to
7844 switch to and display the buffer used for mail composition.
7846 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7847 to insert the raw text of the message being replied to.
7848 It has the form (FUNCTION . ARGS). The user agent will apply
7849 FUNCTION to ARGS, to insert the raw text of the original message.
7850 \(The user agent will also run `mail-citation-hook', *after* the
7851 original text has been inserted in this way.)
7853 SEND-ACTIONS is a list of actions to call when the message is sent.
7854 Each action has the form (FUNCTION . ARGS).
7856 RETURN-ACTION, if non-nil, is an action for returning to the
7857 caller. It has the form (FUNCTION . ARGS). The function is
7858 called after the mail has been sent or put aside, and the mail
7861 (list nil nil nil current-prefix-arg
))
7863 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7864 ;; from sendmail-user-agent to message-user-agent. Some users may
7865 ;; encounter incompatibilities. This hack tries to detect problems
7866 ;; and warn about them.
7867 (and compose-mail-user-agent-warnings
7868 (eq mail-user-agent
'message-user-agent
)
7870 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7871 mail-citation-hook mail-archive-file-name
7872 mail-default-reply-to mail-mailing-lists
7876 (push var warn-vars
)))
7878 (display-warning 'mail
7880 The default mail mode is now Message mode.
7881 You have the following Mail mode variable%s customized:
7882 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7883 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7884 (if (> (length warn-vars
) 1) "s" "")
7885 (mapconcat 'symbol-name
7888 (let ((function (get mail-user-agent
'composefunc
)))
7889 (funcall function to subject other-headers continue switch-function
7890 yank-action send-actions return-action
)))
7892 (defun compose-mail-other-window (&optional to subject other-headers continue
7893 yank-action send-actions
7895 "Like \\[compose-mail], but edit the outgoing message in another window."
7896 (interactive (list nil nil nil current-prefix-arg
))
7897 (compose-mail to subject other-headers continue
7898 'switch-to-buffer-other-window yank-action send-actions
7901 (defun compose-mail-other-frame (&optional to subject other-headers continue
7902 yank-action send-actions
7904 "Like \\[compose-mail], but edit the outgoing message in another frame."
7905 (interactive (list nil nil nil current-prefix-arg
))
7906 (compose-mail to subject other-headers continue
7907 'switch-to-buffer-other-frame yank-action send-actions
7911 (defvar set-variable-value-history nil
7912 "History of values entered with `set-variable'.
7914 Maximum length of the history list is determined by the value
7915 of `history-length', which see.")
7917 (defun set-variable (variable value
&optional make-local
)
7918 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7919 VARIABLE should be a user option variable name, a Lisp variable
7920 meant to be customized by users. You should enter VALUE in Lisp syntax,
7921 so if you want VALUE to be a string, you must surround it with doublequotes.
7922 VALUE is used literally, not evaluated.
7924 If VARIABLE has a `variable-interactive' property, that is used as if
7925 it were the arg to `interactive' (which see) to interactively read VALUE.
7927 If VARIABLE has been defined with `defcustom', then the type information
7928 in the definition is used to check that VALUE is valid.
7930 Note that this function is at heart equivalent to the basic `set' function.
7931 For a variable defined with `defcustom', it does not pay attention to
7932 any :set property that the variable might have (if you want that, use
7933 \\[customize-set-variable] instead).
7935 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7937 (let* ((default-var (variable-at-point))
7938 (var (if (custom-variable-p default-var
)
7939 (read-variable (format "Set variable (default %s): " default-var
)
7941 (read-variable "Set variable: ")))
7942 (minibuffer-help-form '(describe-variable var
))
7943 (prop (get var
'variable-interactive
))
7944 (obsolete (car (get var
'byte-obsolete-variable
)))
7945 (prompt (format "Set %s %s to value: " var
7946 (cond ((local-variable-p var
)
7948 ((or current-prefix-arg
7949 (local-variable-if-set-p var
))
7954 (message (concat "`%S' is obsolete; "
7955 (if (symbolp obsolete
) "use `%S' instead" "%s"))
7959 ;; Use VAR's `variable-interactive' property
7960 ;; as an interactive spec for prompting.
7961 (call-interactively `(lambda (arg)
7964 (read-from-minibuffer prompt nil
7965 read-expression-map t
7966 'set-variable-value-history
7967 (format "%S" (symbol-value var
)))))))
7968 (list var val current-prefix-arg
)))
7970 (and (custom-variable-p variable
)
7971 (not (get variable
'custom-type
))
7972 (custom-load-symbol variable
))
7973 (let ((type (get variable
'custom-type
)))
7975 ;; Match with custom type.
7977 (setq type
(widget-convert type
))
7978 (unless (widget-apply type
:match value
)
7979 (user-error "Value `%S' does not match type %S of %S"
7980 value
(car type
) variable
))))
7983 (make-local-variable variable
))
7985 (set variable value
)
7987 ;; Force a thorough redisplay for the case that the variable
7988 ;; has an effect on the display, like `tab-width' has.
7989 (force-mode-line-update))
7991 ;; Define the major mode for lists of completions.
7993 (defvar completion-list-mode-map
7994 (let ((map (make-sparse-keymap)))
7995 (define-key map
[mouse-2
] 'choose-completion
)
7996 (define-key map
[follow-link
] 'mouse-face
)
7997 (define-key map
[down-mouse-2
] nil
)
7998 (define-key map
"\C-m" 'choose-completion
)
7999 (define-key map
"\e\e\e" 'delete-completion-window
)
8000 (define-key map
[left] 'previous-completion)
8001 (define-key map [right] 'next-completion)
8002 (define-key map [?\t] 'next-completion)
8003 (define-key map [backtab] 'previous-completion)
8004 (define-key map "q" 'quit-window)
8005 (define-key map "z" 'kill-current-buffer)
8007 "Local map for completion list buffers.")
8009 ;; Completion mode is suitable only for specially formatted data.
8010 (put 'completion-list-mode 'mode-class 'special)
8012 (defvar completion-reference-buffer nil
8013 "Record the buffer that was current when the completion list was requested.
8014 This is a local variable in the completion list buffer.
8015 Initial value is nil to avoid some compiler warnings.")
8017 (defvar completion-no-auto-exit nil
8018 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8019 This also applies to other functions such as `choose-completion'.")
8021 (defvar completion-base-position nil
8022 "Position of the base of the text corresponding to the shown completions.
8023 This variable is used in the *Completions* buffers.
8024 Its value is a list of the form (START END) where START is the place
8025 where the completion should be inserted and END (if non-nil) is the end
8026 of the text to replace. If END is nil, point is used instead.")
8028 (defvar completion-list-insert-choice-function #'completion--replace
8029 "Function to use to insert the text chosen in *Completions*.
8030 Called with three arguments (BEG END TEXT), it should replace the text
8031 between BEG and END with TEXT. Expected to be set buffer-locally
8032 in the *Completions* buffer.")
8034 (defvar completion-base-size nil
8035 "Number of chars before point not involved in completion.
8036 This is a local variable in the completion list buffer.
8037 It refers to the chars in the minibuffer if completing in the
8038 minibuffer, or in `completion-reference-buffer' otherwise.
8039 Only characters in the field at point are included.
8041 If nil, Emacs determines which part of the tail end of the
8042 buffer's text is involved in completion by comparing the text
8044 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8046 (defun delete-completion-window ()
8047 "Delete the completion list window.
8048 Go to the window from which completion was requested."
8050 (let ((buf completion-reference-buffer))
8051 (if (one-window-p t)
8052 (if (window-dedicated-p) (delete-frame))
8053 (delete-window (selected-window))
8054 (if (get-buffer-window buf)
8055 (select-window (get-buffer-window buf))))))
8057 (defun previous-completion (n)
8058 "Move to the previous item in the completion list."
8060 (next-completion (- n)))
8062 (defun next-completion (n)
8063 "Move to the next item in the completion list.
8064 With prefix argument N, move N items (negative N means move backward)."
8066 (let ((beg (point-min)) (end (point-max)))
8067 (while (and (> n 0) (not (eobp)))
8068 ;; If in a completion, move to the end of it.
8069 (when (get-text-property (point) 'mouse-face)
8070 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8071 ;; Move to start of next one.
8072 (unless (get-text-property (point) 'mouse-face)
8073 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8075 (while (and (< n 0) (not (bobp)))
8076 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8077 ;; If in a completion, move to the start of it.
8078 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8079 (goto-char (previous-single-property-change
8080 (point) 'mouse-face nil beg)))
8081 ;; Move to end of the previous completion.
8082 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8083 (goto-char (previous-single-property-change
8084 (point) 'mouse-face nil beg)))
8085 ;; Move to the start of that one.
8086 (goto-char (previous-single-property-change
8087 (point) 'mouse-face nil beg))
8090 (defun choose-completion (&optional event)
8091 "Choose the completion at point.
8092 If EVENT, use EVENT's position to determine the starting position."
8093 (interactive (list last-nonmenu-event))
8094 ;; In case this is run via the mouse, give temporary modes such as
8095 ;; isearch a chance to turn off.
8096 (run-hooks 'mouse-leave-buffer-hook)
8097 (with-current-buffer (window-buffer (posn-window (event-start event)))
8098 (let ((buffer completion-reference-buffer)
8099 (base-size completion-base-size)
8100 (base-position completion-base-position)
8101 (insert-function completion-list-insert-choice-function)
8104 (goto-char (posn-point (event-start event)))
8107 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8108 (setq end (point) beg (1+ (point))))
8110 (get-text-property (1- (point)) 'mouse-face))
8111 (setq end (1- (point)) beg (point)))
8112 (t (error "No completion here")))
8113 (setq beg (previous-single-property-change beg 'mouse-face))
8114 (setq end (or (next-single-property-change end 'mouse-face)
8116 (buffer-substring-no-properties beg end)))))
8118 (unless (buffer-live-p buffer)
8119 (error "Destination buffer is dead"))
8120 (quit-window nil (posn-window (event-start event)))
8122 (with-current-buffer buffer
8123 (choose-completion-string
8127 ;; Someone's using old completion code that doesn't know
8128 ;; about base-position yet.
8129 (list (+ base-size (field-beginning))))
8130 ;; If all else fails, just guess.
8131 (list (choose-completion-guess-base-position choice)))
8132 insert-function)))))
8134 ;; Delete the longest partial match for STRING
8135 ;; that can be found before POINT.
8136 (defun choose-completion-guess-base-position (string)
8138 (let ((opoint (point))
8140 ;; Try moving back by the length of the string.
8141 (goto-char (max (- (point) (length string))
8142 (minibuffer-prompt-end)))
8143 ;; See how far back we were actually able to move. That is the
8144 ;; upper bound on how much we can match and delete.
8145 (setq len (- opoint (point)))
8146 (if completion-ignore-case
8147 (setq string (downcase string)))
8148 (while (and (> len 0)
8149 (let ((tail (buffer-substring (point) opoint)))
8150 (if completion-ignore-case
8151 (setq tail (downcase tail)))
8152 (not (string= tail (substring string 0 len)))))
8157 (defun choose-completion-delete-max-match (string)
8158 (declare (obsolete choose-completion-guess-base-position "23.2"))
8159 (delete-region (choose-completion-guess-base-position string) (point)))
8161 (defvar choose-completion-string-functions nil
8162 "Functions that may override the normal insertion of a completion choice.
8163 These functions are called in order with three arguments:
8164 CHOICE - the string to insert in the buffer,
8165 BUFFER - the buffer in which the choice should be inserted,
8166 BASE-POSITION - where to insert the completion.
8168 If a function in the list returns non-nil, that function is supposed
8169 to have inserted the CHOICE in the BUFFER, and possibly exited
8170 the minibuffer; no further functions will be called.
8172 If all functions in the list return nil, that means to use
8173 the default method of inserting the completion in BUFFER.")
8175 (defun choose-completion-string (choice &optional
8176 buffer base-position insert-function)
8177 "Switch to BUFFER and insert the completion choice CHOICE.
8178 BASE-POSITION says where to insert the completion.
8179 INSERT-FUNCTION says how to insert the completion and falls
8180 back on `completion-list-insert-choice-function' when nil."
8182 ;; If BUFFER is the minibuffer, exit the minibuffer
8183 ;; unless it is reading a file name and CHOICE is a directory,
8184 ;; or completion-no-auto-exit is non-nil.
8186 ;; Some older code may call us passing `base-size' instead of
8187 ;; `base-position'. It's difficult to make any use of `base-size',
8188 ;; so we just ignore it.
8189 (unless (consp base-position)
8190 (message "Obsolete `base-size' passed to choose-completion-string")
8191 (setq base-position nil))
8193 (let* ((buffer (or buffer completion-reference-buffer))
8194 (mini-p (minibufferp buffer)))
8195 ;; If BUFFER is a minibuffer, barf unless it's the currently
8196 ;; active minibuffer.
8198 (not (and (active-minibuffer-window)
8200 (window-buffer (active-minibuffer-window))))))
8201 (error "Minibuffer is not active for completion")
8202 ;; Set buffer so buffer-local choose-completion-string-functions works.
8204 (unless (run-hook-with-args-until-success
8205 'choose-completion-string-functions
8206 ;; The fourth arg used to be `mini-p' but was useless
8207 ;; (since minibufferp can be used on the `buffer' arg)
8208 ;; and indeed unused. The last used to be `base-size', so we
8209 ;; keep it to try and avoid breaking old code.
8210 choice buffer base-position nil)
8211 ;; This remove-text-properties should be unnecessary since `choice'
8212 ;; comes from buffer-substring-no-properties.
8213 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8214 ;; Insert the completion into the buffer where it was requested.
8215 (funcall (or insert-function completion-list-insert-choice-function)
8216 (or (car base-position) (point))
8217 (or (cadr base-position) (point))
8219 ;; Update point in the window that BUFFER is showing in.
8220 (let ((window (get-buffer-window buffer t)))
8221 (set-window-point window (point)))
8222 ;; If completing for the minibuffer, exit it with this choice.
8223 (and (not completion-no-auto-exit)
8224 (minibufferp buffer)
8225 minibuffer-completion-table
8226 ;; If this is reading a file name, and the file name chosen
8227 ;; is a directory, don't exit the minibuffer.
8228 (let* ((result (buffer-substring (field-beginning) (point)))
8230 (completion-boundaries result minibuffer-completion-table
8231 minibuffer-completion-predicate
8233 (if (eq (car bounds) (length result))
8234 ;; The completion chosen leads to a new set of completions
8235 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8236 (let ((mini (active-minibuffer-window)))
8237 (select-window mini)
8238 (when minibuffer-auto-raise
8239 (raise-frame (window-frame mini))))
8240 (exit-minibuffer))))))))
8242 (define-derived-mode completion-list-mode nil "Completion List"
8243 "Major mode for buffers showing lists of possible completions.
8244 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8245 to select the completion near point.
8246 Or click to select one with the mouse.
8248 \\{completion-list-mode-map}"
8249 (set (make-local-variable 'completion-base-size) nil))
8251 (defun completion-list-mode-finish ()
8252 "Finish setup of the completions buffer.
8253 Called from `temp-buffer-show-hook'."
8254 (when (eq major-mode 'completion-list-mode)
8255 (setq buffer-read-only t)))
8257 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8260 ;; Variables and faces used in `completion-setup-function'.
8262 (defcustom completion-show-help t
8263 "Non-nil means show help message in *Completions* buffer."
8268 ;; This function goes in completion-setup-hook, so that it is called
8269 ;; after the text of the completion list buffer is written.
8270 (defun completion-setup-function ()
8271 (let* ((mainbuf (current-buffer))
8273 ;; FIXME: This is a bad hack. We try to set the default-directory
8274 ;; in the *Completions* buffer so that the relative file names
8275 ;; displayed there can be treated as valid file names, independently
8276 ;; from the completion context. But this suffers from many problems:
8277 ;; - It's not clear when the completions are file names. With some
8278 ;; completion tables (e.g. bzr revision specs), the listed
8279 ;; completions can mix file names and other things.
8280 ;; - It doesn't pay attention to possible quoting.
8281 ;; - With fancy completion styles, the code below will not always
8282 ;; find the right base directory.
8283 (if minibuffer-completing-file-name
8284 (file-name-as-directory
8286 (buffer-substring (minibuffer-prompt-end)
8287 (- (point) (or completion-base-size 0))))))))
8288 (with-current-buffer standard-output
8289 (let ((base-size completion-base-size) ;Read before killing localvars.
8290 (base-position completion-base-position)
8291 (insert-fun completion-list-insert-choice-function))
8292 (completion-list-mode)
8293 (set (make-local-variable 'completion-base-size) base-size)
8294 (set (make-local-variable 'completion-base-position) base-position)
8295 (set (make-local-variable 'completion-list-insert-choice-function)
8297 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8298 (if base-dir (setq default-directory base-dir))
8299 ;; Maybe insert help string.
8300 (when completion-show-help
8301 (goto-char (point-min))
8302 (if (display-mouse-p)
8303 (insert "Click on a completion to select it.\n"))
8304 (insert (substitute-command-keys
8305 "In this buffer, type \\[choose-completion] to \
8306 select the completion near point.\n\n"))))))
8308 (add-hook 'completion-setup-hook 'completion-setup-function)
8310 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8311 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8313 (defun switch-to-completions ()
8314 "Select the completion list window."
8316 (let ((window (or (get-buffer-window "*Completions*" 0)
8317 ;; Make sure we have a completions window.
8318 (progn (minibuffer-completion-help)
8319 (get-buffer-window "*Completions*" 0)))))
8321 (select-window window)
8322 ;; In the new buffer, go to the first completion.
8323 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8325 (next-completion 1)))))
8327 ;;; Support keyboard commands to turn on various modifiers.
8329 ;; These functions -- which are not commands -- each add one modifier
8330 ;; to the following event.
8332 (defun event-apply-alt-modifier (_ignore-prompt)
8333 "\\<function-key-map>Add the Alt modifier to the following event.
8334 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8335 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8336 (defun event-apply-super-modifier (_ignore-prompt)
8337 "\\<function-key-map>Add the Super modifier to the following event.
8338 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8339 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8340 (defun event-apply-hyper-modifier (_ignore-prompt)
8341 "\\<function-key-map>Add the Hyper modifier to the following event.
8342 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8343 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8344 (defun event-apply-shift-modifier (_ignore-prompt)
8345 "\\<function-key-map>Add the Shift modifier to the following event.
8346 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8347 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8348 (defun event-apply-control-modifier (_ignore-prompt)
8349 "\\<function-key-map>Add the Ctrl modifier to the following event.
8350 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8351 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8352 (defun event-apply-meta-modifier (_ignore-prompt)
8353 "\\<function-key-map>Add the Meta modifier to the following event.
8354 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8355 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8357 (defun event-apply-modifier (event symbol lshiftby prefix)
8358 "Apply a modifier flag to event EVENT.
8359 SYMBOL is the name of this modifier, as a symbol.
8360 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8361 PREFIX is the string that represents this modifier in an event type symbol."
8363 (cond ((eq symbol 'control)
8364 (if (and (<= (downcase event) ?z)
8365 (>= (downcase event) ?a))
8366 (- (downcase event) ?a -1)
8367 (if (and (<= (downcase event) ?Z)
8368 (>= (downcase event) ?A))
8369 (- (downcase event) ?A -1)
8370 (logior (lsh 1 lshiftby) event))))
8372 (if (and (<= (downcase event) ?z)
8373 (>= (downcase event) ?a))
8375 (logior (lsh 1 lshiftby) event)))
8377 (logior (lsh 1 lshiftby) event)))
8378 (if (memq symbol (event-modifiers event))
8380 (let ((event-type (if (symbolp event) event (car event))))
8381 (setq event-type (intern (concat prefix (symbol-name event-type))))
8384 (cons event-type (cdr event)))))))
8386 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8387 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8388 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8389 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8390 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8391 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8393 ;;;; Keypad support.
8395 ;; Make the keypad keys act like ordinary typing keys. If people add
8396 ;; bindings for the function key symbols, then those bindings will
8397 ;; override these, so this shouldn't interfere with any existing
8400 ;; Also tell read-char how to handle these keys.
8402 (lambda (keypad-normal)
8403 (let ((keypad (nth 0 keypad-normal))
8404 (normal (nth 1 keypad-normal)))
8405 (put keypad 'ascii-character normal)
8406 (define-key function-key-map (vector keypad) (vector normal))))
8407 ;; See also kp-keys bound in bindings.el.
8413 ;; Do the same for various keys that are represented as symbols under
8414 ;; GUIs but naturally correspond to characters.
8425 ;;;; forking a twin copy of a buffer.
8428 (defvar clone-buffer-hook nil
8429 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8431 (defvar clone-indirect-buffer-hook nil
8432 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8434 (defun clone-process (process &optional newname)
8435 "Create a twin copy of PROCESS.
8436 If NEWNAME is nil, it defaults to PROCESS' name;
8437 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8438 If PROCESS is associated with a buffer, the new process will be associated
8439 with the current buffer instead.
8440 Returns nil if PROCESS has already terminated."
8441 (setq newname (or newname (process-name process)))
8442 (if (string-match "<[0-9]+>\\'" newname)
8443 (setq newname (substring newname 0 (match-beginning 0))))
8444 (when (memq (process-status process) '(run stop open))
8445 (let* ((process-connection-type (process-tty-name process))
8447 (if (memq (process-status process) '(open))
8448 (let ((args (process-contact process t)))
8449 (setq args (plist-put args :name newname))
8450 (setq args (plist-put args :buffer
8451 (if (process-buffer process)
8453 (apply 'make-network-process args))
8454 (apply 'start-process newname
8455 (if (process-buffer process) (current-buffer))
8456 (process-command process)))))
8457 (set-process-query-on-exit-flag
8458 new-process (process-query-on-exit-flag process))
8459 (set-process-inherit-coding-system-flag
8460 new-process (process-inherit-coding-system-flag process))
8461 (set-process-filter new-process (process-filter process))
8462 (set-process-sentinel new-process (process-sentinel process))
8463 (set-process-plist new-process (copy-sequence (process-plist process)))
8466 ;; things to maybe add (currently partly covered by `funcall mode'):
8469 (defun clone-buffer (&optional newname display-flag)
8470 "Create and return a twin copy of the current buffer.
8471 Unlike an indirect buffer, the new buffer can be edited
8472 independently of the old one (if it is not read-only).
8473 NEWNAME is the name of the new buffer. It may be modified by
8474 adding or incrementing <N> at the end as necessary to create a
8475 unique buffer name. If nil, it defaults to the name of the
8476 current buffer, with the proper suffix. If DISPLAY-FLAG is
8477 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8478 clone a file-visiting buffer, or a buffer whose major mode symbol
8479 has a non-nil `no-clone' property, results in an error.
8481 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8482 current buffer with appropriate suffix. However, if a prefix
8483 argument is given, then the command prompts for NEWNAME in the
8486 This runs the normal hook `clone-buffer-hook' in the new buffer
8487 after it has been set up properly in other respects."
8490 (if buffer-file-name
8491 (error "Cannot clone a file-visiting buffer"))
8492 (if (get major-mode 'no-clone)
8493 (error "Cannot clone a buffer in %s mode" mode-name))
8494 (list (if current-prefix-arg
8495 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8497 (if buffer-file-name
8498 (error "Cannot clone a file-visiting buffer"))
8499 (if (get major-mode 'no-clone)
8500 (error "Cannot clone a buffer in %s mode" mode-name))
8501 (setq newname (or newname (buffer-name)))
8502 (if (string-match "<[0-9]+>\\'" newname)
8503 (setq newname (substring newname 0 (match-beginning 0))))
8504 (let ((buf (current-buffer))
8508 (mk (if mark-active (mark t)))
8509 (modified (buffer-modified-p))
8511 (lvars (buffer-local-variables))
8512 (process (get-buffer-process (current-buffer)))
8513 (new (generate-new-buffer (or newname (buffer-name)))))
8516 (with-current-buffer new
8517 (insert-buffer-substring buf)))
8518 (with-current-buffer new
8519 (narrow-to-region ptmin ptmax)
8521 (if mk (set-mark mk))
8522 (set-buffer-modified-p modified)
8524 ;; Clone the old buffer's process, if any.
8525 (when process (clone-process process))
8527 ;; Now set up the major mode.
8530 ;; Set up other local variables.
8535 (set (make-local-variable (car v)) (cdr v)))
8536 (setting-constant nil))) ;E.g. for enable-multibyte-characters.
8539 (setq mark-ring (mapcar (lambda (mk) (copy-marker (marker-position mk)))
8542 ;; Run any hooks (typically set up by the major mode
8543 ;; for cloning to work properly).
8544 (run-hooks 'clone-buffer-hook))
8546 ;; Presumably the current buffer is shown in the selected frame, so
8547 ;; we want to display the clone elsewhere.
8548 (let ((same-window-regexps nil)
8549 (same-window-buffer-names))
8550 (pop-to-buffer new)))
8554 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8555 "Create an indirect buffer that is a twin copy of the current buffer.
8557 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8558 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8559 or if not called with a prefix arg, NEWNAME defaults to the current
8560 buffer's name. The name is modified by adding a `<N>' suffix to it
8561 or by incrementing the N in an existing suffix. Trying to clone a
8562 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8563 property results in an error.
8565 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8566 This is always done when called interactively.
8568 Optional third arg NORECORD non-nil means do not put this buffer at the
8569 front of the list of recently selected ones.
8571 Returns the newly created indirect buffer."
8574 (if (get major-mode 'no-clone-indirect)
8575 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8576 (list (if current-prefix-arg
8577 (read-buffer "Name of indirect buffer: " (current-buffer)))
8579 (if (get major-mode 'no-clone-indirect)
8580 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8581 (setq newname (or newname (buffer-name)))
8582 (if (string-match "<[0-9]+>\\'" newname)
8583 (setq newname (substring newname 0 (match-beginning 0))))
8584 (let* ((name (generate-new-buffer-name newname))
8585 (buffer (make-indirect-buffer (current-buffer) name t)))
8586 (with-current-buffer buffer
8587 (run-hooks 'clone-indirect-buffer-hook))
8589 (pop-to-buffer buffer nil norecord))
8593 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8594 "Like `clone-indirect-buffer' but display in another window."
8597 (if (get major-mode 'no-clone-indirect)
8598 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8599 (list (if current-prefix-arg
8600 (read-buffer "Name of indirect buffer: " (current-buffer)))
8602 (let ((pop-up-windows t))
8603 (clone-indirect-buffer newname display-flag norecord)))
8606 ;;; Handling of Backspace and Delete keys.
8608 (defcustom normal-erase-is-backspace 'maybe
8609 "Set the default behavior of the Delete and Backspace keys.
8611 If set to t, Delete key deletes forward and Backspace key deletes
8614 If set to nil, both Delete and Backspace keys delete backward.
8616 If set to `maybe' (which is the default), Emacs automatically
8617 selects a behavior. On window systems, the behavior depends on
8618 the keyboard used. If the keyboard has both a Backspace key and
8619 a Delete key, and both are mapped to their usual meanings, the
8620 option's default value is set to t, so that Backspace can be used
8621 to delete backward, and Delete can be used to delete forward.
8623 If not running under a window system, customizing this option
8624 accomplishes a similar effect by mapping C-h, which is usually
8625 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8626 via `keyboard-translate'. The former functionality of C-h is
8627 available on the F1 key. You should probably not use this
8628 setting if you don't have both Backspace, Delete and F1 keys.
8630 Setting this variable with setq doesn't take effect. Programmatically,
8631 call `normal-erase-is-backspace-mode' (which see) instead."
8632 :type '(choice (const :tag "Off" nil)
8633 (const :tag "Maybe" maybe)
8634 (other :tag "On" t))
8635 :group 'editing-basics
8637 :set (lambda (symbol value)
8638 ;; The fboundp is because of a problem with :set when
8639 ;; dumping Emacs. It doesn't really matter.
8640 (if (fboundp 'normal-erase-is-backspace-mode)
8641 (normal-erase-is-backspace-mode (or value 0))
8642 (set-default symbol value))))
8644 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8645 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8646 (unless frame (setq frame (selected-frame)))
8647 (with-selected-frame frame
8648 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8649 (normal-erase-is-backspace-mode
8650 (if (if (eq normal-erase-is-backspace 'maybe)
8651 (and (not noninteractive)
8652 (or (memq system-type '(ms-dos windows-nt))
8653 (memq window-system '(w32 ns))
8654 (and (memq window-system '(x))
8655 (fboundp 'x-backspace-delete-keys-p)
8656 (x-backspace-delete-keys-p))
8657 ;; If the terminal Emacs is running on has erase char
8658 ;; set to ^H, use the Backspace key for deleting
8659 ;; backward, and the Delete key for deleting forward.
8660 (and (null window-system)
8661 (eq tty-erase-char ?\^H))))
8662 normal-erase-is-backspace)
8665 (define-minor-mode normal-erase-is-backspace-mode
8666 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8667 With a prefix argument ARG, enable this feature if ARG is
8668 positive, and disable it otherwise. If called from Lisp, enable
8669 the mode if ARG is omitted or nil.
8671 On window systems, when this mode is on, Delete is mapped to C-d
8672 and Backspace is mapped to DEL; when this mode is off, both
8673 Delete and Backspace are mapped to DEL. (The remapping goes via
8674 `local-function-key-map', so binding Delete or Backspace in the
8675 global or local keymap will override that.)
8677 In addition, on window systems, the bindings of C-Delete, M-Delete,
8678 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8679 the global keymap in accordance with the functionality of Delete and
8680 Backspace. For example, if Delete is remapped to C-d, which deletes
8681 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8682 to DEL, which deletes backward, C-Delete is bound to
8683 `backward-kill-word'.
8685 If not running on a window system, a similar effect is accomplished by
8686 remapping C-h (normally produced by the Backspace key) and DEL via
8687 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8688 to C-d; if it's off, the keys are not remapped.
8690 When not running on a window system, and this mode is turned on, the
8691 former functionality of C-h is available on the F1 key. You should
8692 probably not turn on this mode on a text-only terminal if you don't
8693 have both Backspace, Delete and F1 keys.
8695 See also `normal-erase-is-backspace'."
8696 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8698 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8700 (let ((enabled (eq 1 (terminal-parameter
8701 nil 'normal-erase-is-backspace))))
8703 (cond ((or (memq window-system '(x w32 ns pc))
8704 (memq system-type '(ms-dos windows-nt)))
8706 `(([M-delete] [M-backspace])
8707 ([C-M-delete] [C-M-backspace])
8708 ([?\e C-delete] [?\e C-backspace]))))
8712 (define-key local-function-key-map [delete] [deletechar])
8713 (define-key local-function-key-map [kp-delete] [deletechar])
8714 (define-key local-function-key-map [backspace] [?\C-?])
8715 (dolist (b bindings)
8716 ;; Not sure if input-decode-map is really right, but
8717 ;; keyboard-translate-table (used below) only works
8718 ;; for integer events, and key-translation-table is
8719 ;; global (like the global-map, used earlier).
8720 (define-key input-decode-map (car b) nil)
8721 (define-key input-decode-map (cadr b) nil)))
8722 (define-key local-function-key-map [delete] [?\C-?])
8723 (define-key local-function-key-map [kp-delete] [?\C-?])
8724 (define-key local-function-key-map [backspace] [?\C-?])
8725 (dolist (b bindings)
8726 (define-key input-decode-map (car b) (cadr b))
8727 (define-key input-decode-map (cadr b) (car b))))))
8731 (keyboard-translate ?\C-h ?\C-?)
8732 (keyboard-translate ?\C-? ?\C-d))
8733 (keyboard-translate ?\C-h ?\C-h)
8734 (keyboard-translate ?\C-? ?\C-?))))
8736 (if (called-interactively-p 'interactive)
8737 (message "Delete key deletes %s"
8738 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8739 "forward" "backward")))))
8741 (defvar vis-mode-saved-buffer-invisibility-spec nil
8742 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8744 (define-minor-mode read-only-mode
8745 "Change whether the current buffer is read-only.
8746 With prefix argument ARG, make the buffer read-only if ARG is
8747 positive, otherwise make it writable. If buffer is read-only
8748 and `view-read-only' is non-nil, enter view mode.
8750 Do not call this from a Lisp program unless you really intend to
8751 do the same thing as the \\[read-only-mode] command, including
8752 possibly enabling or disabling View mode. Also, note that this
8753 command works by setting the variable `buffer-read-only', which
8754 does not affect read-only regions caused by text properties. To
8755 ignore read-only status in a Lisp program (whether due to text
8756 properties or buffer state), bind `inhibit-read-only' temporarily
8757 to a non-nil value."
8758 :variable buffer-read-only
8760 ((and (not buffer-read-only) view-mode)
8761 (View-exit-and-edit)
8762 (make-local-variable 'view-read-only)
8763 (setq view-read-only t)) ; Must leave view mode.
8764 ((and buffer-read-only view-read-only
8765 ;; If view-mode is already active, `view-mode-enter' is a nop.
8767 (not (eq (get major-mode 'mode-class) 'special)))
8768 (view-mode-enter))))
8770 (define-minor-mode visible-mode
8771 "Toggle making all invisible text temporarily visible (Visible mode).
8772 With a prefix argument ARG, enable Visible mode if ARG is
8773 positive, and disable it otherwise. If called from Lisp, enable
8774 the mode if ARG is omitted or nil.
8776 This mode works by saving the value of `buffer-invisibility-spec'
8777 and setting it to nil."
8779 :group 'editing-basics
8780 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8781 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8782 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8784 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8785 buffer-invisibility-spec)
8786 (setq buffer-invisibility-spec nil)))
8788 (defvar messages-buffer-mode-map
8789 (let ((map (make-sparse-keymap)))
8790 (set-keymap-parent map special-mode-map)
8791 (define-key map "g" nil) ; nothing to revert
8794 (define-derived-mode messages-buffer-mode special-mode "Messages"
8795 "Major mode used in the \"*Messages*\" buffer.")
8797 (defun messages-buffer ()
8798 "Return the \"*Messages*\" buffer.
8799 If it does not exist, create and it switch it to `messages-buffer-mode'."
8800 (or (get-buffer "*Messages*")
8801 (with-current-buffer (get-buffer-create "*Messages*")
8802 (messages-buffer-mode)
8806 ;; Minibuffer prompt stuff.
8808 ;;(defun minibuffer-prompt-modification (start end)
8809 ;; (error "You cannot modify the prompt"))
8812 ;;(defun minibuffer-prompt-insertion (start end)
8813 ;; (let ((inhibit-modification-hooks t))
8814 ;; (delete-region start end)
8815 ;; ;; Discard undo information for the text insertion itself
8816 ;; ;; and for the text deletion.above.
8817 ;; (when (consp buffer-undo-list)
8818 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8819 ;; (message "You cannot modify the prompt")))
8822 ;;(setq minibuffer-prompt-properties
8823 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8824 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8827 ;;;; Problematic external packages.
8829 ;; rms says this should be done by specifying symbols that define
8830 ;; versions together with bad values. This is therefore not as
8831 ;; flexible as it could be. See the thread:
8832 ;; https://lists.gnu.org/r/emacs-devel/2007-08/msg00300.html
8833 (defconst bad-packages-alist
8834 ;; Not sure exactly which semantic versions have problems.
8835 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8836 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8837 "The version of `semantic' loaded does not work in Emacs 22.
8838 It can cause constant high CPU load.
8839 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8840 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8841 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8842 ;; provided the `CUA-mode' feature. Since this is no longer true,
8843 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8845 "CUA-mode is now part of the standard GNU Emacs distribution,
8846 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8848 You have loaded an older version of CUA-mode which does not work
8849 correctly with this version of Emacs. You should remove the old
8850 version and use the one distributed with Emacs."))
8851 "Alist of packages known to cause problems in this version of Emacs.
8852 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8853 PACKAGE is either a regular expression to match file names, or a
8854 symbol (a feature name), like for `with-eval-after-load'.
8855 SYMBOL is either the name of a string variable, or t. Upon
8856 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8857 warning using STRING as the message.")
8859 (defun bad-package-check (package)
8860 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8862 (let* ((list (assoc package bad-packages-alist))
8863 (symbol (nth 1 list)))
8867 (and (stringp (setq symbol (eval symbol)))
8868 (string-match-p (nth 2 list) symbol)))
8869 (display-warning package (nth 3 list) :warning)))
8872 (dolist (elem bad-packages-alist)
8873 (let ((pkg (car elem)))
8874 (with-eval-after-load pkg
8875 (bad-package-check pkg))))
8878 ;;; Generic dispatcher commands
8880 ;; Macro `define-alternatives' is used to create generic commands.
8881 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8882 ;; that can have different alternative implementations where choosing
8883 ;; among them is exclusively a matter of user preference.
8885 ;; (define-alternatives COMMAND) creates a new interactive command
8886 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8887 ;; Typically, the user will not need to customize this variable; packages
8888 ;; wanting to add alternative implementations should use
8890 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8892 (defmacro define-alternatives (command &rest customizations)
8893 "Define the new command `COMMAND'.
8895 The argument `COMMAND' should be a symbol.
8897 Running `M-x COMMAND RET' for the first time prompts for which
8898 alternative to use and records the selected command as a custom
8901 Running `C-u M-x COMMAND RET' prompts again for an alternative
8902 and overwrites the previous choice.
8904 The variable `COMMAND-alternatives' contains an alist with
8905 alternative implementations of COMMAND. `define-alternatives'
8906 does not have any effect until this variable is set.
8908 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8909 `defcustom' keywords and values to add to the declaration of
8910 `COMMAND-alternatives' (typically :group and :version)."
8911 (let* ((command-name (symbol-name command))
8912 (varalt-name (concat command-name "-alternatives"))
8913 (varalt-sym (intern varalt-name))
8914 (varimp-sym (intern (concat command-name "--implementation"))))
8917 (defcustom ,varalt-sym nil
8918 ,(format "Alist of alternative implementations for the `%s' command.
8920 Each entry must be a pair (ALTNAME . ALTFUN), where:
8921 ALTNAME - The name shown at user to describe the alternative implementation.
8922 ALTFUN - The function called to implement this alternative."
8924 :type '(alist :key-type string :value-type function)
8927 (put ',varalt-sym 'definition-name ',command)
8928 (defvar ,varimp-sym nil "Internal use only.")
8930 (defun ,command (&optional arg)
8931 ,(format "Run generic command `%s'.
8932 If used for the first time, or with interactive ARG, ask the user which
8933 implementation to use for `%s'. The variable `%s'
8934 contains the list of implementations currently supported for this command."
8935 command-name command-name varalt-name)
8937 (when (or arg (null ,varimp-sym))
8938 (let ((val (completing-read
8940 "Select implementation for command `%s': "
8942 ,varalt-sym nil t)))
8943 (unless (string-equal val "")
8944 (when (null ,varimp-sym)
8946 "Use C-u M-x %s RET`to select another implementation"
8949 (customize-save-variable ',varimp-sym
8950 (cdr (assoc-string val ,varalt-sym))))))
8952 (call-interactively ,varimp-sym)
8953 (message "%s" ,(format-message
8954 "No implementation selected for command `%s'"
8958 ;;; Functions for changing capitalization that Do What I Mean
8959 (defun upcase-dwim (arg)
8960 "Upcase words in the region, if active; if not, upcase word at point.
8961 If the region is active, this function calls `upcase-region'.
8962 Otherwise, it calls `upcase-word', with prefix argument passed to it
8963 to upcase ARG words."
8966 (upcase-region (region-beginning) (region-end))
8969 (defun downcase-dwim (arg)
8970 "Downcase words in the region, if active; if not, downcase word at point.
8971 If the region is active, this function calls `downcase-region'.
8972 Otherwise, it calls `downcase-word', with prefix argument passed to it
8973 to downcase ARG words."
8976 (downcase-region (region-beginning) (region-end))
8977 (downcase-word arg)))
8979 (defun capitalize-dwim (arg)
8980 "Capitalize words in the region, if active; if not, capitalize word at point.
8981 If the region is active, this function calls `capitalize-region'.
8982 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8983 to capitalize ARG words."
8986 (capitalize-region (region-beginning) (region-end))
8987 (capitalize-word arg)))
8993 ;;; simple.el ends here