1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2015 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
31 (eval-when-compile (require 'cl-lib))
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
37 (defvar compilation-current-error)
38 (defvar compilation-context-lines)
40 (defcustom idle-update-delay 0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
49 "Killing and yanking commands."
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
56 ;;; next-error support framework
58 (defgroup next-error nil
59 "`next-error' support framework."
64 '((t (:inherit region)))
65 "Face used to highlight next error locus."
69 (defcustom next-error-highlight 0.5
70 "Highlighting of locations in selected source buffers.
71 If a number, highlight the locus in `next-error' face for the given time
72 in seconds, or until the next command is executed.
73 If t, highlight the locus until the next command is executed, or until
74 some other locus replaces it.
75 If nil, don't highlight the locus in the source buffer.
76 If `fringe-arrow', indicate the locus by the fringe arrow
77 indefinitely until some other locus replaces it."
78 :type '(choice (number :tag "Highlight for specified time")
79 (const :tag "Semipermanent highlighting" t)
80 (const :tag "No highlighting" nil)
81 (const :tag "Fringe arrow" fringe-arrow))
85 (defcustom next-error-highlight-no-select 0.5
86 "Highlighting of locations in `next-error-no-select'.
87 If number, highlight the locus in `next-error' face for given time in seconds.
88 If t, highlight the locus indefinitely until some other locus replaces it.
89 If nil, don't highlight the locus in the source buffer.
90 If `fringe-arrow', indicate the locus by the fringe arrow
91 indefinitely until some other locus replaces it."
92 :type '(choice (number :tag "Highlight for specified time")
93 (const :tag "Semipermanent highlighting" t)
94 (const :tag "No highlighting" nil)
95 (const :tag "Fringe arrow" fringe-arrow))
99 (defcustom next-error-recenter nil
100 "Display the line in the visited source file recentered as specified.
101 If non-nil, the value is passed directly to `recenter'."
102 :type '(choice (integer :tag "Line to recenter to")
103 (const :tag "Center of window" (4))
104 (const :tag "No recentering" nil))
108 (defcustom next-error-hook nil
109 "List of hook functions run by `next-error' after visiting source file."
113 (defvar next-error-highlight-timer nil)
115 (defvar next-error-overlay-arrow-position nil)
116 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
117 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
119 (defvar next-error-last-buffer nil
120 "The most recent `next-error' buffer.
121 A buffer becomes most recent when its compilation, grep, or
122 similar mode is started, or when it is used with \\[next-error]
123 or \\[compile-goto-error].")
125 (defvar next-error-function nil
126 "Function to use to find the next error in the current buffer.
127 The function is called with 2 parameters:
128 ARG is an integer specifying by how many errors to move.
129 RESET is a boolean which, if non-nil, says to go back to the beginning
130 of the errors before moving.
131 Major modes providing compile-like functionality should set this variable
132 to indicate to `next-error' that this is a candidate buffer and how
134 (make-variable-buffer-local 'next-error-function)
136 (defvar next-error-move-function nil
137 "Function to use to move to an error locus.
138 It takes two arguments, a buffer position in the error buffer
139 and a buffer position in the error locus buffer.
140 The buffer for the error locus should already be current.
141 nil means use goto-char using the second argument position.")
142 (make-variable-buffer-local 'next-error-move-function)
144 (defsubst next-error-buffer-p (buffer
145 &optional avoid-current
147 extra-test-exclusive)
148 "Test if BUFFER is a `next-error' capable buffer.
150 If AVOID-CURRENT is non-nil, treat the current buffer
151 as an absolute last resort only.
153 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
154 that normally would not qualify. If it returns t, the buffer
155 in question is treated as usable.
157 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
158 that would normally be considered usable. If it returns nil,
159 that buffer is rejected."
160 (and (buffer-name buffer) ;First make sure it's live.
161 (not (and avoid-current (eq buffer (current-buffer))))
162 (with-current-buffer buffer
163 (if next-error-function ; This is the normal test.
164 ;; Optionally reject some buffers.
165 (if extra-test-exclusive
166 (funcall extra-test-exclusive)
168 ;; Optionally accept some other buffers.
169 (and extra-test-inclusive
170 (funcall extra-test-inclusive))))))
172 (defun next-error-find-buffer (&optional avoid-current
174 extra-test-exclusive)
175 "Return a `next-error' capable buffer.
177 If AVOID-CURRENT is non-nil, treat the current buffer
178 as an absolute last resort only.
180 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
181 that normally would not qualify. If it returns t, the buffer
182 in question is treated as usable.
184 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
185 that would normally be considered usable. If it returns nil,
186 that buffer is rejected."
188 ;; 1. If one window on the selected frame displays such buffer, return it.
189 (let ((window-buffers
191 (delq nil (mapcar (lambda (w)
192 (if (next-error-buffer-p
195 extra-test-inclusive extra-test-exclusive)
198 (if (eq (length window-buffers) 1)
199 (car window-buffers)))
200 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
201 (if (and next-error-last-buffer
202 (next-error-buffer-p next-error-last-buffer avoid-current
203 extra-test-inclusive extra-test-exclusive))
204 next-error-last-buffer)
205 ;; 3. If the current buffer is acceptable, choose it.
206 (if (next-error-buffer-p (current-buffer) avoid-current
207 extra-test-inclusive extra-test-exclusive)
209 ;; 4. Look for any acceptable buffer.
210 (let ((buffers (buffer-list)))
212 (not (next-error-buffer-p
213 (car buffers) avoid-current
214 extra-test-inclusive extra-test-exclusive)))
215 (setq buffers (cdr buffers)))
217 ;; 5. Use the current buffer as a last resort if it qualifies,
218 ;; even despite AVOID-CURRENT.
220 (next-error-buffer-p (current-buffer) nil
221 extra-test-inclusive extra-test-exclusive)
223 (message "This is the only buffer with error message locations")
226 (error "No buffers contain error message locations")))
228 (defun next-error (&optional arg reset)
229 "Visit next `next-error' message and corresponding source code.
231 If all the error messages parsed so far have been processed already,
232 the message buffer is checked for new ones.
234 A prefix ARG specifies how many error messages to move;
235 negative means move back to previous error messages.
236 Just \\[universal-argument] as a prefix means reparse the error message buffer
237 and start at the first error.
239 The RESET argument specifies that we should restart from the beginning.
241 \\[next-error] normally uses the most recently started
242 compilation, grep, or occur buffer. It can also operate on any
243 buffer with output from the \\[compile], \\[grep] commands, or,
244 more generally, on any buffer in Compilation mode or with
245 Compilation Minor mode enabled, or any buffer in which
246 `next-error-function' is bound to an appropriate function.
247 To specify use of a particular buffer for error messages, type
248 \\[next-error] in that buffer when it is the only one displayed
249 in the current frame.
251 Once \\[next-error] has chosen the buffer for error messages, it
252 runs `next-error-hook' with `run-hooks', and stays with that buffer
253 until you use it in some other buffer which uses Compilation mode
254 or Compilation Minor mode.
256 To control which errors are matched, customize the variable
257 `compilation-error-regexp-alist'."
259 (if (consp arg) (setq reset t arg nil))
260 (when (setq next-error-last-buffer (next-error-find-buffer))
261 ;; we know here that next-error-function is a valid symbol we can funcall
262 (with-current-buffer next-error-last-buffer
263 (funcall next-error-function (prefix-numeric-value arg) reset)
264 (when next-error-recenter
265 (recenter next-error-recenter))
266 (run-hooks 'next-error-hook))))
268 (defun next-error-internal ()
269 "Visit the source code corresponding to the `next-error' message at point."
270 (setq next-error-last-buffer (current-buffer))
271 ;; we know here that next-error-function is a valid symbol we can funcall
272 (with-current-buffer next-error-last-buffer
273 (funcall next-error-function 0 nil)
274 (when next-error-recenter
275 (recenter next-error-recenter))
276 (run-hooks 'next-error-hook)))
278 (defalias 'goto-next-locus 'next-error)
279 (defalias 'next-match 'next-error)
281 (defun previous-error (&optional n)
282 "Visit previous `next-error' message and corresponding source code.
284 Prefix arg N says how many error messages to move backwards (or
285 forwards, if negative).
287 This operates on the output from the \\[compile] and \\[grep] commands."
289 (next-error (- (or n 1))))
291 (defun first-error (&optional n)
292 "Restart at the first error.
293 Visit corresponding source code.
294 With prefix arg N, visit the source code of the Nth error.
295 This operates on the output from the \\[compile] command, for instance."
299 (defun next-error-no-select (&optional n)
300 "Move point to the next error in the `next-error' buffer and highlight match.
301 Prefix arg N says how many error messages to move forwards (or
302 backwards, if negative).
303 Finds and highlights the source line like \\[next-error], but does not
304 select the source buffer."
306 (let ((next-error-highlight next-error-highlight-no-select))
308 (pop-to-buffer next-error-last-buffer))
310 (defun previous-error-no-select (&optional n)
311 "Move point to the previous error in the `next-error' buffer and highlight match.
312 Prefix arg N says how many error messages to move backwards (or
313 forwards, if negative).
314 Finds and highlights the source line like \\[previous-error], but does not
315 select the source buffer."
317 (next-error-no-select (- (or n 1))))
319 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
320 (defvar next-error-follow-last-line nil)
322 (define-minor-mode next-error-follow-minor-mode
323 "Minor mode for compilation, occur and diff modes.
324 With a prefix argument ARG, enable mode if ARG is positive, and
325 disable it otherwise. If called from Lisp, enable mode if ARG is
327 When turned on, cursor motion in the compilation, grep, occur or diff
328 buffer causes automatic display of the corresponding source code location."
329 :group 'next-error :init-value nil :lighter " Fol"
330 (if (not next-error-follow-minor-mode)
331 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
332 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
333 (make-local-variable 'next-error-follow-last-line)))
335 ;; Used as a `post-command-hook' by `next-error-follow-mode'
336 ;; for the *Compilation* *grep* and *Occur* buffers.
337 (defun next-error-follow-mode-post-command-hook ()
338 (unless (equal next-error-follow-last-line (line-number-at-pos))
339 (setq next-error-follow-last-line (line-number-at-pos))
341 (let ((compilation-context-lines nil))
342 (setq compilation-current-error (point))
343 (next-error-no-select 0))
349 (defun fundamental-mode ()
350 "Major mode not specialized for anything in particular.
351 Other major modes are defined by comparison with this one."
353 (kill-all-local-variables)
356 ;; Special major modes to view specially formatted data rather than files.
358 (defvar special-mode-map
359 (let ((map (make-sparse-keymap)))
360 (suppress-keymap map)
361 (define-key map "q" 'quit-window)
362 (define-key map " " 'scroll-up-command)
363 (define-key map [?\S-\ ] 'scroll-down-command)
364 (define-key map "\C-?" 'scroll-down-command)
365 (define-key map "?" 'describe-mode)
366 (define-key map "h" 'describe-mode)
367 (define-key map ">" 'end-of-buffer)
368 (define-key map "<" 'beginning-of-buffer)
369 (define-key map "g" 'revert-buffer)
372 (put 'special-mode 'mode-class 'special)
373 (define-derived-mode special-mode nil "Special"
374 "Parent major mode from which special major modes should inherit."
375 (setq buffer-read-only t))
377 ;; Making and deleting lines.
379 (defvar self-insert-uses-region-functions nil
380 "Special hook to tell if `self-insert-command' will use the region.
381 It must be called via `run-hook-with-args-until-success' with no arguments.
382 Any `post-self-insert-command' which consumes the region should
383 register a function on this hook so that things like `delete-selection-mode'
384 can refrain from consuming the region.")
386 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
387 "Propertized string representing a hard newline character.")
389 (defun newline (&optional arg interactive)
390 "Insert a newline, and move to left margin of the new line if it's blank.
391 If option `use-hard-newlines' is non-nil, the newline is marked with the
392 text-property `hard'.
393 With ARG, insert that many newlines.
395 If `electric-indent-mode' is enabled, this indents the final new line
396 that it adds, and reindents the preceding line. To just insert
397 a newline, use \\[electric-indent-just-newline].
399 Calls `auto-fill-function' if the current column number is greater
400 than the value of `fill-column' and ARG is nil.
401 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
402 (interactive "*P\np")
403 (barf-if-buffer-read-only)
404 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
405 ;; Set last-command-event to tell self-insert what to insert.
406 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
408 (last-command-event ?\n)
409 ;; Don't auto-fill if we have a numeric argument.
410 (auto-fill-function (if arg nil auto-fill-function))
412 ;; Do the rest in post-self-insert-hook, because we want to do it
413 ;; *before* other functions on that hook.
415 (cl-assert (eq ?\n (char-before)))
416 ;; Mark the newline(s) `hard'.
417 (if use-hard-newlines
418 (set-hard-newline-properties
419 (- (point) (prefix-numeric-value arg)) (point)))
420 ;; If the newline leaves the previous line blank, and we
421 ;; have a left margin, delete that from the blank line.
423 (goto-char beforepos)
425 (and (looking-at "[ \t]$")
426 (> (current-left-margin) 0)
427 (delete-region (point)
428 (line-end-position))))
429 ;; Indent the line after the newline, except in one case:
430 ;; when we added the newline at the beginning of a line which
433 (move-to-left-margin nil t)))))
435 (if (not interactive)
436 ;; FIXME: For non-interactive uses, many calls actually just want
437 ;; (insert "\n"), so maybe we should do just that, so as to avoid
438 ;; the risk of filling or running abbrevs unexpectedly.
439 (let ((post-self-insert-hook (list postproc)))
440 (self-insert-command (prefix-numeric-value arg)))
443 (add-hook 'post-self-insert-hook postproc nil t)
444 (self-insert-command (prefix-numeric-value arg)))
445 ;; We first used let-binding to protect the hook, but that was naive
446 ;; since add-hook affects the symbol-default value of the variable,
447 ;; whereas the let-binding might only protect the buffer-local value.
448 (remove-hook 'post-self-insert-hook postproc t)))
449 (cl-assert (not (member postproc post-self-insert-hook)))
450 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
453 (defun set-hard-newline-properties (from to)
454 (let ((sticky (get-text-property from 'rear-nonsticky)))
455 (put-text-property from to 'hard 't)
456 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
457 (if (and (listp sticky) (not (memq 'hard sticky)))
458 (put-text-property from (point) 'rear-nonsticky
459 (cons 'hard sticky)))))
462 "Insert a newline and leave point before it.
463 If there is a fill prefix and/or a `left-margin', insert them on
464 the new line if the line would have been blank.
465 With arg N, insert N newlines."
467 (let* ((do-fill-prefix (and fill-prefix (bolp)))
468 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
470 ;; Don't expand an abbrev before point.
476 (if do-left-margin (indent-to (current-left-margin)))
477 (if do-fill-prefix (insert-and-inherit fill-prefix))))
481 ;; Necessary in case a margin or prefix was inserted.
484 (defun split-line (&optional arg)
485 "Split current line, moving portion beyond point vertically down.
486 If the current line starts with `fill-prefix', insert it on the new
487 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
489 When called from Lisp code, ARG may be a prefix string to copy."
491 (skip-chars-forward " \t")
492 (let* ((col (current-column))
494 ;; What prefix should we check for (nil means don't).
495 (prefix (cond ((stringp arg) arg)
498 ;; Does this line start with it?
499 (have-prfx (and prefix
502 (looking-at (regexp-quote prefix))))))
504 (if have-prfx (insert-and-inherit prefix))
508 (defun delete-indentation (&optional arg)
509 "Join this line to previous and fix up whitespace at join.
510 If there is a fill prefix, delete it from the beginning of this line.
511 With argument, join this line to following line."
514 (if arg (forward-line 1))
515 (if (eq (preceding-char) ?\n)
517 (delete-region (point) (1- (point)))
518 ;; If the second line started with the fill prefix,
519 ;; delete the prefix.
521 (<= (+ (point) (length fill-prefix)) (point-max))
523 (buffer-substring (point)
524 (+ (point) (length fill-prefix)))))
525 (delete-region (point) (+ (point) (length fill-prefix))))
526 (fixup-whitespace))))
528 (defalias 'join-line #'delete-indentation) ; easier to find
530 (defun delete-blank-lines ()
531 "On blank line, delete all surrounding blank lines, leaving just one.
532 On isolated blank line, delete that one.
533 On nonblank line, delete any immediately following blank lines."
535 (let (thisblank singleblank)
538 (setq thisblank (looking-at "[ \t]*$"))
539 ;; Set singleblank if there is just one blank line here.
542 (not (looking-at "[ \t]*\n[ \t]*$"))
544 (progn (forward-line -1)
545 (not (looking-at "[ \t]*$")))))))
546 ;; Delete preceding blank lines, and this one too if it's the only one.
550 (if singleblank (forward-line 1))
551 (delete-region (point)
552 (if (re-search-backward "[^ \t\n]" nil t)
553 (progn (forward-line 1) (point))
555 ;; Delete following blank lines, unless the current line is blank
556 ;; and there are no following blank lines.
557 (if (not (and thisblank singleblank))
561 (delete-region (point)
562 (if (re-search-forward "[^ \t\n]" nil t)
563 (progn (beginning-of-line) (point))
565 ;; Handle the special case where point is followed by newline and eob.
566 ;; Delete the line, leaving point at eob.
567 (if (looking-at "^[ \t]*\n\\'")
568 (delete-region (point) (point-max)))))
570 (defcustom delete-trailing-lines t
571 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
572 Trailing lines are deleted only if `delete-trailing-whitespace'
573 is called on the entire buffer (rather than an active region)."
578 (defun delete-trailing-whitespace (&optional start end)
579 "Delete trailing whitespace between START and END.
580 If called interactively, START and END are the start/end of the
581 region if the mark is active, or of the buffer's accessible
582 portion if the mark is inactive.
584 This command deletes whitespace characters after the last
585 non-whitespace character in each line between START and END. It
586 does not consider formfeed characters to be whitespace.
588 If this command acts on the entire buffer (i.e. if called
589 interactively with the mark inactive, or called from Lisp with
590 END nil), it also deletes all trailing lines at the end of the
591 buffer if the variable `delete-trailing-lines' is non-nil."
593 (barf-if-buffer-read-only)
595 (list (region-beginning) (region-end))
599 (let ((end-marker (copy-marker (or end (point-max))))
600 (start (or start (point-min))))
602 (while (re-search-forward "\\s-$" end-marker t)
603 (skip-syntax-backward "-" (line-beginning-position))
604 ;; Don't delete formfeeds, even if they are considered whitespace.
605 (if (looking-at-p ".*\f")
606 (goto-char (match-end 0)))
607 (delete-region (point) (match-end 0)))
608 ;; Delete trailing empty lines.
609 (goto-char end-marker)
611 delete-trailing-lines
612 ;; Really the end of buffer.
613 (= (point-max) (1+ (buffer-size)))
614 (<= (skip-chars-backward "\n") -2))
615 (delete-region (1+ (point)) end-marker))
616 (set-marker end-marker nil))))
617 ;; Return nil for the benefit of `write-file-functions'.
620 (defun newline-and-indent ()
621 "Insert a newline, then indent according to major mode.
622 Indentation is done using the value of `indent-line-function'.
623 In programming language modes, this is the same as TAB.
624 In some text modes, where TAB inserts a tab, this command indents to the
625 column specified by the function `current-left-margin'."
627 (delete-horizontal-space t)
629 (indent-according-to-mode))
631 (defun reindent-then-newline-and-indent ()
632 "Reindent current line, insert newline, then indent the new line.
633 Indentation of both lines is done according to the current major mode,
634 which means calling the current value of `indent-line-function'.
635 In programming language modes, this is the same as TAB.
636 In some text modes, where TAB inserts a tab, this indents to the
637 column specified by the function `current-left-margin'."
640 ;; Be careful to insert the newline before indenting the line.
641 ;; Otherwise, the indentation might be wrong.
645 ;; We are at EOL before the call to indent-according-to-mode, and
646 ;; after it we usually are as well, but not always. We tried to
647 ;; address it with `save-excursion' but that uses a normal marker
648 ;; whereas we need `move after insertion', so we do the save/restore
650 (setq pos (copy-marker pos t))
651 (indent-according-to-mode)
653 ;; Remove the trailing white-space after indentation because
654 ;; indentation may introduce the whitespace.
655 (delete-horizontal-space t))
656 (indent-according-to-mode)))
658 (defcustom read-quoted-char-radix 8
659 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
660 Legitimate radix values are 8, 10 and 16."
661 :type '(choice (const 8) (const 10) (const 16))
662 :group 'editing-basics)
664 (defun read-quoted-char (&optional prompt)
665 "Like `read-char', but do not allow quitting.
666 Also, if the first character read is an octal digit,
667 we read any number of octal digits and return the
668 specified character code. Any nondigit terminates the sequence.
669 If the terminator is RET, it is discarded;
670 any other terminator is used itself as input.
672 The optional argument PROMPT specifies a string to use to prompt the user.
673 The variable `read-quoted-char-radix' controls which radix to use
675 (let ((message-log-max nil)
676 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
678 done (first t) (code 0) translated)
680 (let ((inhibit-quit first)
681 ;; Don't let C-h or other help chars get the help
682 ;; message--only help function keys. See bug#16617.
684 (help-event-list help-events)
686 "Type the special character you want to use,
687 or the octal character code.
688 RET terminates the character code and is discarded;
689 any other non-digit terminates the character code and is then used as input."))
690 (setq translated (read-key (and prompt (format "%s-" prompt))))
691 (if inhibit-quit (setq quit-flag nil)))
692 (if (integerp translated)
693 (setq translated (char-resolve-modifiers translated)))
694 (cond ((null translated))
695 ((not (integerp translated))
696 (setq unread-command-events
697 (nconc (listify-key-sequence (this-single-command-raw-keys))
698 unread-command-events)
700 ((/= (logand translated ?\M-\^@) 0)
701 ;; Turn a meta-character into a character with the 0200 bit set.
702 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
704 ((and (<= ?0 translated)
705 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
706 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
707 (and prompt (setq prompt (message "%s %c" prompt translated))))
708 ((and (<= ?a (downcase translated))
709 (< (downcase translated)
710 (+ ?a -10 (min 36 read-quoted-char-radix))))
711 (setq code (+ (* code read-quoted-char-radix)
712 (+ 10 (- (downcase translated) ?a))))
713 (and prompt (setq prompt (message "%s %c" prompt translated))))
714 ((and (not first) (eq translated ?\C-m))
717 (setq unread-command-events
718 (nconc (listify-key-sequence (this-single-command-raw-keys))
719 unread-command-events)
721 (t (setq code translated
726 (defun quoted-insert (arg)
727 "Read next input character and insert it.
728 This is useful for inserting control characters.
729 With argument, insert ARG copies of the character.
731 If the first character you type after this command is an octal digit,
732 you should type a sequence of octal digits which specify a character code.
733 Any nondigit terminates the sequence. If the terminator is a RET,
734 it is discarded; any other terminator is used itself as input.
735 The variable `read-quoted-char-radix' specifies the radix for this feature;
736 set it to 10 or 16 to use decimal or hex instead of octal.
738 In overwrite mode, this function inserts the character anyway, and
739 does not handle octal digits specially. This means that if you use
740 overwrite as your normal editing mode, you can use this function to
741 insert characters when necessary.
743 In binary overwrite mode, this function does overwrite, and octal
744 digits are interpreted as a character code. This is intended to be
745 useful for editing binary files."
748 ;; Avoid "obsolete" warnings for translation-table-for-input.
750 (let (translation-table-for-input input-method-function)
751 (if (or (not overwrite-mode)
752 (eq overwrite-mode 'overwrite-mode-binary))
755 ;; This used to assume character codes 0240 - 0377 stand for
756 ;; characters in some single-byte character set, and converted them
757 ;; to Emacs characters. But in 23.1 this feature is deprecated
758 ;; in favor of inserting the corresponding Unicode characters.
759 ;; (if (and enable-multibyte-characters
762 ;; (setq char (unibyte-char-to-multibyte char)))
763 (unless (characterp char)
764 (user-error "%s is not a valid character"
765 (key-description (vector char))))
767 (if (eq overwrite-mode 'overwrite-mode-binary)
770 (insert-and-inherit char)
771 (setq arg (1- arg)))))
773 (defun forward-to-indentation (&optional arg)
774 "Move forward ARG lines and position at first nonblank character."
776 (forward-line (or arg 1))
777 (skip-chars-forward " \t"))
779 (defun backward-to-indentation (&optional arg)
780 "Move backward ARG lines and position at first nonblank character."
782 (forward-line (- (or arg 1)))
783 (skip-chars-forward " \t"))
785 (defun back-to-indentation ()
786 "Move point to the first non-whitespace character on this line."
788 (beginning-of-line 1)
789 (skip-syntax-forward " " (line-end-position))
790 ;; Move back over chars that have whitespace syntax but have the p flag.
791 (backward-prefix-chars))
793 (defun fixup-whitespace ()
794 "Fixup white space between objects around point.
795 Leave one space or none, according to the context."
798 (delete-horizontal-space)
799 (if (or (looking-at "^\\|\\s)")
800 (save-excursion (forward-char -1)
801 (looking-at "$\\|\\s(\\|\\s'")))
805 (defun delete-horizontal-space (&optional backward-only)
806 "Delete all spaces and tabs around point.
807 If BACKWARD-ONLY is non-nil, only delete them before point."
809 (let ((orig-pos (point)))
814 (skip-chars-forward " \t")
815 (constrain-to-field nil orig-pos t)))
817 (skip-chars-backward " \t")
818 (constrain-to-field nil orig-pos)))))
820 (defun just-one-space (&optional n)
821 "Delete all spaces and tabs around point, leaving one space (or N spaces).
822 If N is negative, delete newlines as well, leaving -N spaces.
823 See also `cycle-spacing'."
825 (cycle-spacing n nil 'single-shot))
827 (defvar cycle-spacing--context nil
828 "Store context used in consecutive calls to `cycle-spacing' command.
829 The first time `cycle-spacing' runs, it saves in this variable:
830 its N argument, the original point position, and the original spacing
833 (defun cycle-spacing (&optional n preserve-nl-back mode)
834 "Manipulate whitespace around point in a smart way.
835 In interactive use, this function behaves differently in successive
838 The first call in a sequence acts like `just-one-space'.
839 It deletes all spaces and tabs around point, leaving one space
840 \(or N spaces). N is the prefix argument. If N is negative,
841 it deletes newlines as well, leaving -N spaces.
842 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
844 The second call in a sequence deletes all spaces.
846 The third call in a sequence restores the original whitespace (and point).
848 If MODE is `single-shot', it only performs the first step in the sequence.
849 If MODE is `fast' and the first step would not result in any change
850 \(i.e., there are exactly (abs N) spaces around point),
851 the function goes straight to the second step.
853 Repeatedly calling the function with different values of N starts a
854 new sequence each time."
856 (let ((orig-pos (point))
857 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
858 (num (abs (or n 1))))
859 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
860 (constrain-to-field nil orig-pos)
862 ;; Command run for the first time, single-shot mode or different argument
863 ((or (eq 'single-shot mode)
864 (not (equal last-command this-command))
865 (not cycle-spacing--context)
866 (not (eq (car cycle-spacing--context) n)))
867 (let* ((start (point))
868 (num (- num (skip-chars-forward " " (+ num (point)))))
871 (skip-chars-forward skip-characters)
872 (constrain-to-field nil orig-pos t))))
873 (setq cycle-spacing--context ;; Save for later.
874 ;; Special handling for case where there was no space at all.
875 (unless (= start end)
876 (cons n (cons orig-pos (buffer-substring start (point))))))
877 ;; If this run causes no change in buffer content, delete all spaces,
878 ;; otherwise delete all excess spaces.
879 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
881 (insert (make-string num ?\s))))
883 ;; Command run for the second time.
884 ((not (equal orig-pos (point)))
885 (delete-region (point) orig-pos))
887 ;; Command run for the third time.
889 (insert (cddr cycle-spacing--context))
890 (goto-char (cadr cycle-spacing--context))
891 (setq cycle-spacing--context nil)))))
893 (defun beginning-of-buffer (&optional arg)
894 "Move point to the beginning of the buffer.
895 With numeric arg N, put point N/10 of the way from the beginning.
896 If the buffer is narrowed, this command uses the beginning of the
897 accessible part of the buffer.
899 Push mark at previous position, unless either a \\[universal-argument] prefix
900 is supplied, or Transient Mark mode is enabled and the mark is active."
901 (declare (interactive-only "use `(goto-char (point-min))' instead."))
906 (let ((size (- (point-max) (point-min))))
907 (goto-char (if (and arg (not (consp arg)))
910 ;; Avoid overflow for large buffer sizes!
911 (* (prefix-numeric-value arg)
913 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
915 (if (and arg (not (consp arg))) (forward-line 1)))
917 (defun end-of-buffer (&optional arg)
918 "Move point to the end of the buffer.
919 With numeric arg N, put point N/10 of the way from the end.
920 If the buffer is narrowed, this command uses the end of the
921 accessible part of the buffer.
923 Push mark at previous position, unless either a \\[universal-argument] prefix
924 is supplied, or Transient Mark mode is enabled and the mark is active."
925 (declare (interactive-only "use `(goto-char (point-max))' instead."))
927 (or (consp arg) (region-active-p) (push-mark))
928 (let ((size (- (point-max) (point-min))))
929 (goto-char (if (and arg (not (consp arg)))
932 ;; Avoid overflow for large buffer sizes!
933 (* (prefix-numeric-value arg)
935 (/ (* size (prefix-numeric-value arg)) 10)))
937 ;; If we went to a place in the middle of the buffer,
938 ;; adjust it to the beginning of a line.
939 (cond ((and arg (not (consp arg))) (forward-line 1))
940 ((and (eq (current-buffer) (window-buffer))
941 (> (point) (window-end nil t)))
942 ;; If the end of the buffer is not already on the screen,
943 ;; then scroll specially to put it near, but not at, the bottom.
944 (overlay-recenter (point))
947 (defcustom delete-active-region t
948 "Whether single-char deletion commands delete an active region.
949 This has an effect only if Transient Mark mode is enabled, and
950 affects `delete-forward-char' and `delete-backward-char', though
953 If the value is the symbol `kill', the active region is killed
955 :type '(choice (const :tag "Delete active region" t)
956 (const :tag "Kill active region" kill)
957 (const :tag "Do ordinary deletion" nil))
961 (defvar region-extract-function
963 (when (region-beginning)
966 (list (cons (region-beginning) (region-end))))
967 ((eq delete 'delete-only)
968 (delete-region (region-beginning) (region-end)))
970 (filter-buffer-substring (region-beginning) (region-end) delete)))))
971 "Function to get the region's content.
972 Called with one argument DELETE.
973 If DELETE is `delete-only', then only delete the region and the return value
974 is undefined. If DELETE is nil, just return the content as a string.
975 If DELETE is `bounds', then don't delete, but just return the
976 boundaries of the region as a list of (START . END) positions.
977 If anything else, delete the region and return its content as a string.")
979 (defvar region-insert-function
985 (insert-for-yank (car lines))
986 (setq lines (cdr lines)
988 "Function to insert the region's content.
989 Called with one argument LINES.
990 Insert the region as a list of lines.")
992 (defun delete-backward-char (n &optional killflag)
993 "Delete the previous N characters (following if N is negative).
994 If Transient Mark mode is enabled, the mark is active, and N is 1,
995 delete the text in the region and deactivate the mark instead.
996 To disable this, set option `delete-active-region' to nil.
998 Optional second arg KILLFLAG, if non-nil, means to kill (save in
999 kill ring) instead of delete. Interactively, N is the prefix
1000 arg, and KILLFLAG is set if N is explicitly specified.
1002 In Overwrite mode, single character backward deletion may replace
1003 tabs with spaces so as to back over columns, unless point is at
1004 the end of the line."
1005 (declare (interactive-only delete-char))
1006 (interactive "p\nP")
1007 (unless (integerp n)
1008 (signal 'wrong-type-argument (list 'integerp n)))
1009 (cond ((and (use-region-p)
1010 delete-active-region
1012 ;; If a region is active, kill or delete it.
1013 (if (eq delete-active-region 'kill)
1014 (kill-region (region-beginning) (region-end) 'region)
1015 (funcall region-extract-function 'delete-only)))
1016 ;; In Overwrite mode, maybe untabify while deleting
1017 ((null (or (null overwrite-mode)
1019 (memq (char-before) '(?\t ?\n))
1021 (eq (char-after) ?\n)))
1022 (let ((ocol (current-column)))
1023 (delete-char (- n) killflag)
1025 (insert-char ?\s (- ocol (current-column)) nil))))
1026 ;; Otherwise, do simple deletion.
1027 (t (delete-char (- n) killflag))))
1029 (defun delete-forward-char (n &optional killflag)
1030 "Delete the following N characters (previous if N is negative).
1031 If Transient Mark mode is enabled, the mark is active, and N is 1,
1032 delete the text in the region and deactivate the mark instead.
1033 To disable this, set variable `delete-active-region' to nil.
1035 Optional second arg KILLFLAG non-nil means to kill (save in kill
1036 ring) instead of delete. Interactively, N is the prefix arg, and
1037 KILLFLAG is set if N was explicitly specified."
1038 (declare (interactive-only delete-char))
1039 (interactive "p\nP")
1040 (unless (integerp n)
1041 (signal 'wrong-type-argument (list 'integerp n)))
1042 (cond ((and (use-region-p)
1043 delete-active-region
1045 ;; If a region is active, kill or delete it.
1046 (if (eq delete-active-region 'kill)
1047 (kill-region (region-beginning) (region-end) 'region)
1048 (funcall region-extract-function 'delete-only)))
1050 ;; Otherwise, do simple deletion.
1051 (t (delete-char n killflag))))
1053 (defun mark-whole-buffer ()
1054 "Put point at beginning and mark at end of buffer.
1055 If narrowing is in effect, only uses the accessible part of the buffer.
1056 You probably should not use this function in Lisp programs;
1057 it is usually a mistake for a Lisp function to use any subroutine
1058 that uses or sets the mark."
1059 (declare (interactive-only t))
1062 (push-mark (point-max) nil t)
1063 (goto-char (point-min)))
1066 ;; Counting lines, one way or another.
1068 (defun goto-line (line &optional buffer)
1069 "Go to LINE, counting from line 1 at beginning of buffer.
1070 If called interactively, a numeric prefix argument specifies
1071 LINE; without a numeric prefix argument, read LINE from the
1074 If optional argument BUFFER is non-nil, switch to that buffer and
1075 move to line LINE there. If called interactively with \\[universal-argument]
1076 as argument, BUFFER is the most recently selected other buffer.
1078 Prior to moving point, this function sets the mark (without
1079 activating it), unless Transient Mark mode is enabled and the
1080 mark is already active.
1082 This function is usually the wrong thing to use in a Lisp program.
1083 What you probably want instead is something like:
1084 (goto-char (point-min))
1085 (forward-line (1- N))
1086 If at all possible, an even better solution is to use char counts
1087 rather than line counts."
1088 (declare (interactive-only forward-line))
1090 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1091 (list (prefix-numeric-value current-prefix-arg))
1092 ;; Look for a default, a number in the buffer at point.
1095 (skip-chars-backward "0-9")
1096 (if (looking-at "[0-9]")
1098 (buffer-substring-no-properties
1100 (progn (skip-chars-forward "0-9")
1102 ;; Decide if we're switching buffers.
1104 (if (consp current-prefix-arg)
1105 (other-buffer (current-buffer) t)))
1108 (concat " in " (buffer-name buffer))
1110 ;; Read the argument, offering that number (if any) as default.
1111 (list (read-number (format "Goto line%s: " buffer-prompt)
1112 (list default (line-number-at-pos)))
1114 ;; Switch to the desired buffer, one way or another.
1116 (let ((window (get-buffer-window buffer)))
1117 (if window (select-window window)
1118 (switch-to-buffer-other-window buffer))))
1119 ;; Leave mark at previous position
1120 (or (region-active-p) (push-mark))
1121 ;; Move to the specified line number in that buffer.
1124 (goto-char (point-min))
1125 (if (eq selective-display t)
1126 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1127 (forward-line (1- line)))))
1129 (defun count-words-region (start end &optional arg)
1130 "Count the number of words in the region.
1131 If called interactively, print a message reporting the number of
1132 lines, words, and characters in the region (whether or not the
1133 region is active); with prefix ARG, report for the entire buffer
1134 rather than the region.
1136 If called from Lisp, return the number of words between positions
1138 (interactive (if current-prefix-arg
1139 (list nil nil current-prefix-arg)
1140 (list (region-beginning) (region-end) nil)))
1141 (cond ((not (called-interactively-p 'any))
1142 (count-words start end))
1144 (count-words--buffer-message))
1146 (count-words--message "Region" start end))))
1148 (defun count-words (start end)
1149 "Count words between START and END.
1150 If called interactively, START and END are normally the start and
1151 end of the buffer; but if the region is active, START and END are
1152 the start and end of the region. Print a message reporting the
1153 number of lines, words, and chars.
1155 If called from Lisp, return the number of words between START and
1156 END, without printing any message."
1157 (interactive (list nil nil))
1158 (cond ((not (called-interactively-p 'any))
1162 (narrow-to-region start end)
1163 (goto-char (point-min))
1164 (while (forward-word 1)
1165 (setq words (1+ words)))))
1168 (call-interactively 'count-words-region))
1170 (count-words--buffer-message))))
1172 (defun count-words--buffer-message ()
1173 (count-words--message
1174 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1175 (point-min) (point-max)))
1177 (defun count-words--message (str start end)
1178 (let ((lines (count-lines start end))
1179 (words (count-words start end))
1180 (chars (- end start)))
1181 (message "%s has %d line%s, %d word%s, and %d character%s."
1183 lines (if (= lines 1) "" "s")
1184 words (if (= words 1) "" "s")
1185 chars (if (= chars 1) "" "s"))))
1187 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1190 "Print the current buffer line number and narrowed line number of point."
1192 (let ((start (point-min))
1193 (n (line-number-at-pos)))
1195 (message "Line %d" n)
1199 (message "line %d (narrowed line %d)"
1200 (+ n (line-number-at-pos start) -1) n))))))
1202 (defun count-lines (start end)
1203 "Return number of lines between START and END.
1204 This is usually the number of newlines between them,
1205 but can be one more if START is not equal to END
1206 and the greater of them is not at the start of a line."
1209 (narrow-to-region start end)
1210 (goto-char (point-min))
1211 (if (eq selective-display t)
1214 (while (re-search-forward "[\n\C-m]" nil t 40)
1215 (setq done (+ 40 done)))
1216 (while (re-search-forward "[\n\C-m]" nil t 1)
1217 (setq done (+ 1 done)))
1218 (goto-char (point-max))
1219 (if (and (/= start end)
1223 (- (buffer-size) (forward-line (buffer-size)))))))
1225 (defun line-number-at-pos (&optional pos)
1226 "Return (narrowed) buffer line number at position POS.
1227 If POS is nil, use current buffer location.
1228 Counting starts at (point-min), so the value refers
1229 to the contents of the accessible portion of the buffer."
1230 (let ((opoint (or pos (point))) start)
1232 (goto-char (point-min))
1233 (setq start (point))
1236 (1+ (count-lines start (point))))))
1238 (defun what-cursor-position (&optional detail)
1239 "Print info on cursor position (on screen and within buffer).
1240 Also describe the character after point, and give its character code
1241 in octal, decimal and hex.
1243 For a non-ASCII multibyte character, also give its encoding in the
1244 buffer's selected coding system if the coding system encodes the
1245 character safely. If the character is encoded into one byte, that
1246 code is shown in hex. If the character is encoded into more than one
1247 byte, just \"...\" is shown.
1249 In addition, with prefix argument, show details about that character
1250 in *Help* buffer. See also the command `describe-char'."
1252 (let* ((char (following-char))
1254 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1255 ;; start a directional embedding, which could completely
1256 ;; disrupt the rest of the line (e.g., RLO will display the
1257 ;; rest of the line right-to-left). So we put an invisible
1258 ;; PDF character after these characters, to end the
1259 ;; embedding, which eliminates any effects on the rest of
1260 ;; the line. For RLE and RLO we also append an invisible
1261 ;; LRM, to avoid reordering the following numerical
1262 ;; characters. For LRI/RLI/FSI we append a PDI.
1263 (cond ((memq char '(?\x202a ?\x202d))
1264 (propertize (string ?\x202c) 'invisible t))
1265 ((memq char '(?\x202b ?\x202e))
1266 (propertize (string ?\x202c ?\x200e) 'invisible t))
1267 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1268 (propertize (string ?\x2069) 'invisible t))
1269 ;; Strong right-to-left characters cause reordering of
1270 ;; the following numerical characters which show the
1271 ;; codepoint, so append LRM to countermand that.
1272 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1273 (propertize (string ?\x200e) 'invisible t))
1279 (total (buffer-size))
1280 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1281 (hscroll (if (= (window-hscroll) 0)
1283 (format " Hscroll=%d" (window-hscroll))))
1284 (col (current-column)))
1286 (if (or (/= beg 1) (/= end (1+ total)))
1287 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1288 pos total percent beg end col hscroll)
1289 (message "point=%d of %d (EOB) column=%d%s"
1290 pos total col hscroll))
1291 (let ((coding buffer-file-coding-system)
1292 encoded encoding-msg display-prop under-display)
1293 (if (or (not coding)
1294 (eq (coding-system-type coding) t))
1295 (setq coding (default-value 'buffer-file-coding-system)))
1296 (if (eq (char-charset char) 'eight-bit)
1298 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1299 ;; Check if the character is displayed with some `display'
1300 ;; text property. In that case, set under-display to the
1301 ;; buffer substring covered by that property.
1302 (setq display-prop (get-char-property pos 'display))
1304 (let ((to (or (next-single-char-property-change pos 'display)
1306 (if (< to (+ pos 4))
1307 (setq under-display "")
1308 (setq under-display "..."
1311 (concat (buffer-substring-no-properties pos to)
1313 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1316 (if (not (stringp display-prop))
1317 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1318 char char char under-display)
1319 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1320 char char char under-display display-prop))
1322 (format "(%d, #o%o, #x%x, file %s)"
1324 (if (> (length encoded) 1)
1326 (encoded-string-description encoded coding)))
1327 (format "(%d, #o%o, #x%x)" char char char)))))
1329 ;; We show the detailed information about CHAR.
1330 (describe-char (point)))
1331 (if (or (/= beg 1) (/= end (1+ total)))
1332 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1334 (single-key-description char)
1335 (buffer-substring-no-properties (point) (1+ (point))))
1337 encoding-msg pos total percent beg end col hscroll)
1338 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1339 (if enable-multibyte-characters
1341 (single-key-description char)
1342 (buffer-substring-no-properties (point) (1+ (point))))
1343 (single-key-description char))
1344 bidi-fixer encoding-msg pos total percent col hscroll))))))
1346 ;; Initialize read-expression-map. It is defined at C level.
1347 (defvar read-expression-map
1348 (let ((m (make-sparse-keymap)))
1349 (define-key m "\M-\t" 'completion-at-point)
1350 ;; Might as well bind TAB to completion, since inserting a TAB char is
1351 ;; much too rarely useful.
1352 (define-key m "\t" 'completion-at-point)
1353 (set-keymap-parent m minibuffer-local-map)
1356 (defun read-minibuffer (prompt &optional initial-contents)
1357 "Return a Lisp object read using the minibuffer, unevaluated.
1358 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1359 is a string to insert in the minibuffer before reading.
1360 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1361 Such arguments are used as in `read-from-minibuffer'.)"
1362 ;; Used for interactive spec `x'.
1363 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1364 t 'minibuffer-history))
1366 (defun eval-minibuffer (prompt &optional initial-contents)
1367 "Return value of Lisp expression read using the minibuffer.
1368 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1369 is a string to insert in the minibuffer before reading.
1370 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1371 Such arguments are used as in `read-from-minibuffer'.)"
1372 ;; Used for interactive spec `X'.
1373 (eval (read--expression prompt initial-contents)))
1375 (defvar minibuffer-completing-symbol nil
1376 "Non-nil means completing a Lisp symbol in the minibuffer.")
1377 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1379 (defvar minibuffer-default nil
1380 "The current default value or list of default values in the minibuffer.
1381 The functions `read-from-minibuffer' and `completing-read' bind
1382 this variable locally.")
1384 (defcustom eval-expression-print-level 4
1385 "Value for `print-level' while printing value in `eval-expression'.
1386 A value of nil means no limit."
1388 :type '(choice (const :tag "No Limit" nil) integer)
1391 (defcustom eval-expression-print-length 12
1392 "Value for `print-length' while printing value in `eval-expression'.
1393 A value of nil means no limit."
1395 :type '(choice (const :tag "No Limit" nil) integer)
1398 (defcustom eval-expression-debug-on-error t
1399 "If non-nil set `debug-on-error' to t in `eval-expression'.
1400 If nil, don't change the value of `debug-on-error'."
1405 (defun eval-expression-print-format (value)
1406 "Format VALUE as a result of evaluated expression.
1407 Return a formatted string which is displayed in the echo area
1408 in addition to the value printed by prin1 in functions which
1409 display the result of expression evaluation."
1410 (if (and (integerp value)
1411 (or (eq standard-output t)
1412 (zerop (prefix-numeric-value current-prefix-arg))))
1414 (if (and (characterp value)
1415 (char-displayable-p value))
1416 (prin1-char value))))
1418 (format " (#o%o, #x%x, %s)" value value char-string)
1419 (format " (#o%o, #x%x)" value value)))))
1421 (defvar eval-expression-minibuffer-setup-hook nil
1422 "Hook run by `eval-expression' when entering the minibuffer.")
1424 (defun read--expression (prompt &optional initial-contents)
1425 (let ((minibuffer-completing-symbol t))
1426 (minibuffer-with-setup-hook
1428 ;; FIXME: call emacs-lisp-mode?
1429 (add-function :before-until (local 'eldoc-documentation-function)
1430 #'elisp-eldoc-documentation-function)
1431 (add-hook 'completion-at-point-functions
1432 #'elisp-completion-at-point nil t)
1433 (run-hooks 'eval-expression-minibuffer-setup-hook))
1434 (read-from-minibuffer prompt initial-contents
1435 read-expression-map t
1436 'read-expression-history))))
1438 ;; We define this, rather than making `eval' interactive,
1439 ;; for the sake of completion of names like eval-region, eval-buffer.
1440 (defun eval-expression (exp &optional insert-value)
1441 "Evaluate EXP and print value in the echo area.
1442 When called interactively, read an Emacs Lisp expression and evaluate it.
1443 Value is also consed on to front of the variable `values'.
1444 Optional argument INSERT-VALUE non-nil (interactively, with prefix
1445 argument) means insert the result into the current buffer instead of
1446 printing it in the echo area.
1448 Normally, this function truncates long output according to the value
1449 of the variables `eval-expression-print-length' and
1450 `eval-expression-print-level'. With a prefix argument of zero,
1451 however, there is no such truncation. Such a prefix argument
1452 also causes integers to be printed in several additional formats
1453 \(octal, hexadecimal, and character).
1455 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1458 If `eval-expression-debug-on-error' is non-nil, which is the default,
1459 this command arranges for all errors to enter the debugger."
1461 (list (read--expression "Eval: ")
1462 current-prefix-arg))
1464 (if (null eval-expression-debug-on-error)
1465 (push (eval exp lexical-binding) values)
1466 (let ((old-value (make-symbol "t")) new-value)
1467 ;; Bind debug-on-error to something unique so that we can
1468 ;; detect when evalled code changes it.
1469 (let ((debug-on-error old-value))
1470 (push (eval (macroexpand-all exp) lexical-binding) values)
1471 (setq new-value debug-on-error))
1472 ;; If evalled code has changed the value of debug-on-error,
1473 ;; propagate that change to the global binding.
1474 (unless (eq old-value new-value)
1475 (setq debug-on-error new-value))))
1477 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1478 eval-expression-print-length))
1479 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1480 eval-expression-print-level))
1484 (let ((standard-output (current-buffer)))
1486 (prin1 (car values))
1487 (when (zerop (prefix-numeric-value insert-value))
1488 (let ((str (eval-expression-print-format (car values))))
1489 (if str (princ str)))))))
1491 (prin1 (car values) t)
1492 (let ((str (eval-expression-print-format (car values))))
1493 (if str (princ str t)))))))
1495 (defun edit-and-eval-command (prompt command)
1496 "Prompting with PROMPT, let user edit COMMAND and eval result.
1497 COMMAND is a Lisp expression. Let user edit that expression in
1498 the minibuffer, then read and evaluate the result."
1500 (let ((print-level nil)
1501 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1503 (read-from-minibuffer prompt
1504 (prin1-to-string command)
1505 read-expression-map t
1507 ;; If command was added to command-history as a string,
1508 ;; get rid of that. We want only evaluable expressions there.
1509 (if (stringp (car command-history))
1510 (setq command-history (cdr command-history)))))))
1512 ;; If command to be redone does not match front of history,
1513 ;; add it to the history.
1514 (or (equal command (car command-history))
1515 (setq command-history (cons command command-history)))
1518 (defun repeat-complex-command (arg)
1519 "Edit and re-evaluate last complex command, or ARGth from last.
1520 A complex command is one which used the minibuffer.
1521 The command is placed in the minibuffer as a Lisp form for editing.
1522 The result is executed, repeating the command as changed.
1523 If the command has been changed or is not the most recent previous
1524 command it is added to the front of the command history.
1525 You can use the minibuffer history commands \
1526 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1527 to get different commands to edit and resubmit."
1529 (let ((elt (nth (1- arg) command-history))
1534 (let ((print-level nil)
1535 (minibuffer-history-position arg)
1536 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1538 (read-from-minibuffer
1539 "Redo: " (prin1-to-string elt) read-expression-map t
1540 (cons 'command-history arg))
1542 ;; If command was added to command-history as a
1543 ;; string, get rid of that. We want only
1544 ;; evaluable expressions there.
1545 (if (stringp (car command-history))
1546 (setq command-history (cdr command-history))))))
1548 ;; If command to be redone does not match front of history,
1549 ;; add it to the history.
1550 (or (equal newcmd (car command-history))
1551 (setq command-history (cons newcmd command-history)))
1552 (apply #'funcall-interactively
1554 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1556 (error "Argument %d is beyond length of command history" arg)
1557 (error "There are no previous complex commands to repeat")))))
1560 (defvar extended-command-history nil)
1561 (defvar execute-extended-command--last-typed nil)
1563 (defun read-extended-command ()
1564 "Read command name to invoke in `execute-extended-command'."
1565 (minibuffer-with-setup-hook
1567 (add-hook 'post-self-insert-hook
1569 (setq execute-extended-command--last-typed
1570 (minibuffer-contents)))
1572 (set (make-local-variable 'minibuffer-default-add-function)
1574 ;; Get a command name at point in the original buffer
1575 ;; to propose it after M-n.
1576 (with-current-buffer (window-buffer (minibuffer-selected-window))
1577 (and (commandp (function-called-at-point))
1578 (format "%S" (function-called-at-point)))))))
1579 ;; Read a string, completing from and restricting to the set of
1580 ;; all defined commands. Don't provide any initial input.
1581 ;; Save the command read on the extended-command history list.
1584 ((eq current-prefix-arg '-) "- ")
1585 ((and (consp current-prefix-arg)
1586 (eq (car current-prefix-arg) 4)) "C-u ")
1587 ((and (consp current-prefix-arg)
1588 (integerp (car current-prefix-arg)))
1589 (format "%d " (car current-prefix-arg)))
1590 ((integerp current-prefix-arg)
1591 (format "%d " current-prefix-arg)))
1592 ;; This isn't strictly correct if `execute-extended-command'
1593 ;; is bound to anything else (e.g. [menu]).
1594 ;; It could use (key-description (this-single-command-keys)),
1595 ;; but actually a prompt other than "M-x" would be confusing,
1596 ;; because "M-x" is a well-known prompt to read a command
1597 ;; and it serves as a shorthand for "Extended command: ".
1599 (lambda (string pred action)
1601 (if (memq action '(nil t))
1602 ;; Exclude obsolete commands from completions.
1604 (and (funcall pred sym)
1605 (or (equal string (symbol-name sym))
1606 (not (get sym 'byte-obsolete-info)))))
1608 (complete-with-action action obarray string pred)))
1609 #'commandp t nil 'extended-command-history)))
1611 (defcustom suggest-key-bindings t
1612 "Non-nil means show the equivalent key-binding when M-x command has one.
1613 The value can be a length of time to show the message for.
1614 If the value is non-nil and not a number, we wait 2 seconds."
1616 :type '(choice (const :tag "off" nil)
1617 (integer :tag "time" 2)
1620 (defun execute-extended-command--shorter-1 (name length)
1622 ((zerop length) (list ""))
1623 ((equal name "") nil)
1625 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1626 (execute-extended-command--shorter-1
1627 (substring name 1) (1- length)))
1628 (when (string-match "\\`\\(-\\)?[^-]*" name)
1629 (execute-extended-command--shorter-1
1630 (substring name (match-end 0)) length))))))
1632 (defun execute-extended-command--shorter (name typed)
1633 (let ((candidates '())
1634 (max (length typed))
1637 (while (and (not binding)
1641 (setq candidates (execute-extended-command--shorter-1
1643 ;; Don't show the help message if the binding isn't
1644 ;; significantly shorter than the M-x command the user typed.
1646 (let ((candidate (pop candidates)))
1648 (car-safe (completion-try-completion
1649 candidate obarray 'commandp len)))
1650 (setq binding candidate))))
1653 (defun execute-extended-command (prefixarg &optional command-name typed)
1654 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1655 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1656 "Read a command name, then read the arguments and call the command.
1657 To pass a prefix argument to the command you are
1658 invoking, give a prefix argument to `execute-extended-command'."
1659 (declare (interactive-only command-execute))
1660 ;; FIXME: Remember the actual text typed by the user before completion,
1661 ;; so that we don't later on suggest the same shortening.
1663 (let ((execute-extended-command--last-typed nil))
1664 (list current-prefix-arg
1665 (read-extended-command)
1666 execute-extended-command--last-typed)))
1667 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1668 (unless command-name
1669 (let ((current-prefix-arg prefixarg) ; for prompt
1670 (execute-extended-command--last-typed nil))
1671 (setq command-name (read-extended-command))
1672 (setq typed execute-extended-command--last-typed)))
1673 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1674 (binding (and suggest-key-bindings
1675 (not executing-kbd-macro)
1676 (where-is-internal function overriding-local-map t))))
1677 (unless (commandp function)
1678 (error "`%s' is not a valid command name" command-name))
1679 (setq this-command function)
1680 ;; Normally `real-this-command' should never be changed, but here we really
1681 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1682 ;; binding" for <cmd>, so the command the user really wanted to run is
1683 ;; `function' and not `execute-extended-command'. The difference is
1684 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1685 (setq real-this-command function)
1686 (let ((prefix-arg prefixarg))
1687 (command-execute function 'record))
1688 ;; If enabled, show which key runs this command.
1689 ;; But first wait, and skip the message if there is input.
1691 ;; If this command displayed something in the echo area;
1692 ;; wait a few seconds, then display our suggestion message.
1693 ;; FIXME: Wait *after* running post-command-hook!
1694 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1695 ;; find a better answer anyway!
1696 (when suggest-key-bindings
1698 ((zerop (length (current-message))) 0)
1699 ((numberp suggest-key-bindings) suggest-key-bindings)
1701 (when (and waited (not (consp unread-command-events)))
1702 (unless (or binding executing-kbd-macro (not (symbolp function))
1703 (<= (length (symbol-name function)) 2))
1704 ;; There's no binding for CMD. Let's try and find the shortest
1705 ;; string to use in M-x.
1706 ;; FIXME: Can be slow. Cache it maybe?
1708 (setq binding (execute-extended-command--shorter
1709 (symbol-name function) typed))))
1712 (format-message "You can run the command `%s' with %s"
1714 (if (stringp binding)
1715 (concat "M-x " binding " RET")
1716 (key-description binding)))
1717 (sit-for (if (numberp suggest-key-bindings)
1718 suggest-key-bindings
1721 (defun command-execute (cmd &optional record-flag keys special)
1722 ;; BEWARE: Called directly from the C code.
1723 "Execute CMD as an editor command.
1724 CMD must be a symbol that satisfies the `commandp' predicate.
1725 Optional second arg RECORD-FLAG non-nil
1726 means unconditionally put this command in the variable `command-history'.
1727 Otherwise, that is done only if an arg is read using the minibuffer.
1728 The argument KEYS specifies the value to use instead of (this-command-keys)
1729 when reading the arguments; if it is nil, (this-command-keys) is used.
1730 The argument SPECIAL, if non-nil, means that this command is executing
1731 a special event, so ignore the prefix argument and don't clear it."
1732 (setq debug-on-next-call nil)
1733 (let ((prefixarg (unless special
1734 ;; FIXME: This should probably be done around
1735 ;; pre-command-hook rather than here!
1737 (setq current-prefix-arg prefix-arg)
1738 (setq prefix-arg nil)
1739 (when current-prefix-arg
1740 (prefix-command-update))))))
1741 (if (and (symbolp cmd)
1743 disabled-command-function)
1744 ;; FIXME: Weird calling convention!
1745 (run-hooks 'disabled-command-function)
1749 (setq final (indirect-function final))
1750 (if (autoloadp final)
1751 (setq final (autoload-do-load final cmd)))))
1754 ;; If requested, place the macro in the command history. For
1755 ;; other sorts of commands, call-interactively takes care of this.
1757 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1758 ;; Don't keep command history around forever.
1759 (when (and (numberp history-length) (> history-length 0))
1760 (let ((cell (nthcdr history-length command-history)))
1761 (if (consp cell) (setcdr cell nil)))))
1762 (execute-kbd-macro final prefixarg))
1764 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1765 (prog1 (call-interactively cmd record-flag keys)
1766 (when (and (symbolp cmd)
1767 (get cmd 'byte-obsolete-info)
1768 (not (get cmd 'command-execute-obsolete-warned)))
1769 (put cmd 'command-execute-obsolete-warned t)
1770 (message "%s" (macroexp--obsolete-warning
1771 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1773 (defvar minibuffer-history nil
1774 "Default minibuffer history list.
1775 This is used for all minibuffer input
1776 except when an alternate history list is specified.
1778 Maximum length of the history list is determined by the value
1779 of `history-length', which see.")
1780 (defvar minibuffer-history-sexp-flag nil
1781 "Control whether history list elements are expressions or strings.
1782 If the value of this variable equals current minibuffer depth,
1783 they are expressions; otherwise they are strings.
1784 \(That convention is designed to do the right thing for
1785 recursive uses of the minibuffer.)")
1786 (setq minibuffer-history-variable 'minibuffer-history)
1787 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1788 (defvar minibuffer-history-search-history nil)
1790 (defvar minibuffer-text-before-history nil
1791 "Text that was in this minibuffer before any history commands.
1792 This is nil if there have not yet been any history commands
1793 in this use of the minibuffer.")
1795 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1797 (defun minibuffer-history-initialize ()
1798 (setq minibuffer-text-before-history nil))
1800 (defun minibuffer-avoid-prompt (_new _old)
1801 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1802 (declare (obsolete cursor-intangible-mode "25.1"))
1803 (constrain-to-field nil (point-max)))
1805 (defcustom minibuffer-history-case-insensitive-variables nil
1806 "Minibuffer history variables for which matching should ignore case.
1807 If a history variable is a member of this list, then the
1808 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1809 commands ignore case when searching it, regardless of `case-fold-search'."
1810 :type '(repeat variable)
1813 (defun previous-matching-history-element (regexp n)
1814 "Find the previous history element that matches REGEXP.
1815 \(Previous history elements refer to earlier actions.)
1816 With prefix argument N, search for Nth previous match.
1817 If N is negative, find the next or Nth next match.
1818 Normally, history elements are matched case-insensitively if
1819 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1820 makes the search case-sensitive.
1821 See also `minibuffer-history-case-insensitive-variables'."
1823 (let* ((enable-recursive-minibuffers t)
1824 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1826 minibuffer-local-map
1828 'minibuffer-history-search-history
1829 (car minibuffer-history-search-history))))
1830 ;; Use the last regexp specified, by default, if input is empty.
1831 (list (if (string= regexp "")
1832 (if minibuffer-history-search-history
1833 (car minibuffer-history-search-history)
1834 (user-error "No previous history search regexp"))
1836 (prefix-numeric-value current-prefix-arg))))
1838 (if (and (zerop minibuffer-history-position)
1839 (null minibuffer-text-before-history))
1840 (setq minibuffer-text-before-history
1841 (minibuffer-contents-no-properties)))
1842 (let ((history (symbol-value minibuffer-history-variable))
1844 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1845 ;; On some systems, ignore case for file names.
1846 (if (memq minibuffer-history-variable
1847 minibuffer-history-case-insensitive-variables)
1849 ;; Respect the user's setting for case-fold-search:
1855 (pos minibuffer-history-position))
1858 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1859 (when (= pos prevpos)
1860 (user-error (if (= pos 1)
1861 "No later matching history item"
1862 "No earlier matching history item")))
1864 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1865 (let ((print-level nil))
1866 (prin1-to-string (nth (1- pos) history)))
1867 (nth (1- pos) history)))
1870 (and (string-match regexp match-string)
1872 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1873 (match-beginning 1))))
1875 (setq n (+ n (if (< n 0) 1 -1)))))
1876 (setq minibuffer-history-position pos)
1877 (goto-char (point-max))
1878 (delete-minibuffer-contents)
1879 (insert match-string)
1880 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1881 (if (memq (car (car command-history)) '(previous-matching-history-element
1882 next-matching-history-element))
1883 (setq command-history (cdr command-history))))
1885 (defun next-matching-history-element (regexp n)
1886 "Find the next history element that matches REGEXP.
1887 \(The next history element refers to a more recent action.)
1888 With prefix argument N, search for Nth next match.
1889 If N is negative, find the previous or Nth previous match.
1890 Normally, history elements are matched case-insensitively if
1891 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1892 makes the search case-sensitive."
1894 (let* ((enable-recursive-minibuffers t)
1895 (regexp (read-from-minibuffer "Next element matching (regexp): "
1897 minibuffer-local-map
1899 'minibuffer-history-search-history
1900 (car minibuffer-history-search-history))))
1901 ;; Use the last regexp specified, by default, if input is empty.
1902 (list (if (string= regexp "")
1903 (if minibuffer-history-search-history
1904 (car minibuffer-history-search-history)
1905 (user-error "No previous history search regexp"))
1907 (prefix-numeric-value current-prefix-arg))))
1908 (previous-matching-history-element regexp (- n)))
1910 (defvar minibuffer-temporary-goal-position nil)
1912 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1913 "Function run by `goto-history-element' before consuming default values.
1914 This is useful to dynamically add more elements to the list of default values
1915 when `goto-history-element' reaches the end of this list.
1916 Before calling this function `goto-history-element' sets the variable
1917 `minibuffer-default-add-done' to t, so it will call this function only
1918 once. In special cases, when this function needs to be called more
1919 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1920 overriding the setting of this variable to t in `goto-history-element'.")
1922 (defvar minibuffer-default-add-done nil
1923 "When nil, add more elements to the end of the list of default values.
1924 The value nil causes `goto-history-element' to add more elements to
1925 the list of defaults when it reaches the end of this list. It does
1926 this by calling a function defined by `minibuffer-default-add-function'.")
1928 (make-variable-buffer-local 'minibuffer-default-add-done)
1930 (defun minibuffer-default-add-completions ()
1931 "Return a list of all completions without the default value.
1932 This function is used to add all elements of the completion table to
1933 the end of the list of defaults just after the default value."
1934 (let ((def minibuffer-default)
1935 (all (all-completions ""
1936 minibuffer-completion-table
1937 minibuffer-completion-predicate)))
1940 (cons def (delete def all)))))
1942 (defun goto-history-element (nabs)
1943 "Puts element of the minibuffer history in the minibuffer.
1944 The argument NABS specifies the absolute history position."
1946 (when (and (not minibuffer-default-add-done)
1947 (functionp minibuffer-default-add-function)
1948 (< nabs (- (if (listp minibuffer-default)
1949 (length minibuffer-default)
1951 (setq minibuffer-default-add-done t
1952 minibuffer-default (funcall minibuffer-default-add-function)))
1953 (let ((minimum (if minibuffer-default
1954 (- (if (listp minibuffer-default)
1955 (length minibuffer-default)
1958 elt minibuffer-returned-to-present)
1959 (if (and (zerop minibuffer-history-position)
1960 (null minibuffer-text-before-history))
1961 (setq minibuffer-text-before-history
1962 (minibuffer-contents-no-properties)))
1963 (if (< nabs minimum)
1964 (user-error (if minibuffer-default
1965 "End of defaults; no next item"
1966 "End of history; no default available")))
1967 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
1968 (length (symbol-value minibuffer-history-variable))
1970 (user-error "Beginning of history; no preceding item"))
1971 (unless (memq last-command '(next-history-element
1972 previous-history-element))
1973 (let ((prompt-end (minibuffer-prompt-end)))
1974 (set (make-local-variable 'minibuffer-temporary-goal-position)
1975 (cond ((<= (point) prompt-end) prompt-end)
1978 (goto-char (point-max))
1979 (delete-minibuffer-contents)
1980 (setq minibuffer-history-position nabs)
1982 (setq elt (if (listp minibuffer-default)
1983 (nth (1- (abs nabs)) minibuffer-default)
1984 minibuffer-default)))
1986 (setq elt (or minibuffer-text-before-history ""))
1987 (setq minibuffer-returned-to-present t)
1988 (setq minibuffer-text-before-history nil))
1989 (t (setq elt (nth (1- minibuffer-history-position)
1990 (symbol-value minibuffer-history-variable)))))
1992 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1993 (not minibuffer-returned-to-present))
1994 (let ((print-level nil))
1995 (prin1-to-string elt))
1997 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
1999 (defun next-history-element (n)
2000 "Puts next element of the minibuffer history in the minibuffer.
2001 With argument N, it uses the Nth following element."
2004 (goto-history-element (- minibuffer-history-position n))))
2006 (defun previous-history-element (n)
2007 "Puts previous element of the minibuffer history in the minibuffer.
2008 With argument N, it uses the Nth previous element."
2011 (goto-history-element (+ minibuffer-history-position n))))
2013 (defun next-line-or-history-element (&optional arg)
2014 "Move cursor vertically down ARG lines, or to the next history element.
2015 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2016 next element of the minibuffer history in the minibuffer."
2018 (or arg (setq arg 1))
2019 (let* ((old-point (point))
2020 ;; Remember the original goal column of possibly multi-line input
2021 ;; excluding the length of the prompt on the first line.
2022 (prompt-end (minibuffer-prompt-end))
2023 (old-column (unless (and (eolp) (> (point) prompt-end))
2024 (if (= (line-number-at-pos) 1)
2025 (max (- (current-column) (1- prompt-end)) 0)
2026 (current-column)))))
2031 ;; Restore old position since `line-move-visual' moves point to
2032 ;; the end of the line when it fails to go to the next line.
2033 (goto-char old-point)
2034 (next-history-element arg)
2035 ;; Restore the original goal column on the last line
2036 ;; of possibly multi-line input.
2037 (goto-char (point-max))
2039 (if (= (line-number-at-pos) 1)
2040 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2041 (move-to-column old-column)))))))
2043 (defun previous-line-or-history-element (&optional arg)
2044 "Move cursor vertically up ARG lines, or to the previous history element.
2045 When point moves over the top line of multi-line minibuffer, puts ARGth
2046 previous element of the minibuffer history in the minibuffer."
2048 (or arg (setq arg 1))
2049 (let* ((old-point (point))
2050 ;; Remember the original goal column of possibly multi-line input
2051 ;; excluding the length of the prompt on the first line.
2052 (prompt-end (minibuffer-prompt-end))
2053 (old-column (unless (and (eolp) (> (point) prompt-end))
2054 (if (= (line-number-at-pos) 1)
2055 (max (- (current-column) (1- prompt-end)) 0)
2056 (current-column)))))
2059 (previous-line arg))
2060 (beginning-of-buffer
2061 ;; Restore old position since `line-move-visual' moves point to
2062 ;; the beginning of the line when it fails to go to the previous line.
2063 (goto-char old-point)
2064 (previous-history-element arg)
2065 ;; Restore the original goal column on the first line
2066 ;; of possibly multi-line input.
2067 (goto-char (minibuffer-prompt-end))
2069 (if (= (line-number-at-pos) 1)
2070 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2071 (move-to-column old-column))
2072 (goto-char (line-end-position)))))))
2074 (defun next-complete-history-element (n)
2075 "Get next history element which completes the minibuffer before the point.
2076 The contents of the minibuffer after the point are deleted, and replaced
2077 by the new completion."
2079 (let ((point-at-start (point)))
2080 (next-matching-history-element
2082 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2084 ;; next-matching-history-element always puts us at (point-min).
2085 ;; Move to the position we were at before changing the buffer contents.
2086 ;; This is still sensible, because the text before point has not changed.
2087 (goto-char point-at-start)))
2089 (defun previous-complete-history-element (n)
2091 Get previous history element which completes the minibuffer before the point.
2092 The contents of the minibuffer after the point are deleted, and replaced
2093 by the new completion."
2095 (next-complete-history-element (- n)))
2097 ;; For compatibility with the old subr of the same name.
2098 (defun minibuffer-prompt-width ()
2099 "Return the display width of the minibuffer prompt.
2100 Return 0 if current buffer is not a minibuffer."
2101 ;; Return the width of everything before the field at the end of
2102 ;; the buffer; this should be 0 for normal buffers.
2103 (1- (minibuffer-prompt-end)))
2105 ;; isearch minibuffer history
2106 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2108 (defvar minibuffer-history-isearch-message-overlay)
2109 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2111 (defun minibuffer-history-isearch-setup ()
2112 "Set up a minibuffer for using isearch to search the minibuffer history.
2113 Intended to be added to `minibuffer-setup-hook'."
2114 (set (make-local-variable 'isearch-search-fun-function)
2115 'minibuffer-history-isearch-search)
2116 (set (make-local-variable 'isearch-message-function)
2117 'minibuffer-history-isearch-message)
2118 (set (make-local-variable 'isearch-wrap-function)
2119 'minibuffer-history-isearch-wrap)
2120 (set (make-local-variable 'isearch-push-state-function)
2121 'minibuffer-history-isearch-push-state)
2122 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2124 (defun minibuffer-history-isearch-end ()
2125 "Clean up the minibuffer after terminating isearch in the minibuffer."
2126 (if minibuffer-history-isearch-message-overlay
2127 (delete-overlay minibuffer-history-isearch-message-overlay)))
2129 (defun minibuffer-history-isearch-search ()
2130 "Return the proper search function, for isearch in minibuffer history."
2131 (lambda (string bound noerror)
2133 ;; Use standard functions to search within minibuffer text
2134 (isearch-search-fun-default))
2136 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2137 ;; searching forward. Lazy-highlight calls this lambda with the
2138 ;; bound arg, so skip the minibuffer prompt.
2139 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2140 (goto-char (minibuffer-prompt-end)))
2142 ;; 1. First try searching in the initial minibuffer text
2143 (funcall search-fun string
2144 (if isearch-forward bound (minibuffer-prompt-end))
2146 ;; 2. If the above search fails, start putting next/prev history
2147 ;; elements in the minibuffer successively, and search the string
2148 ;; in them. Do this only when bound is nil (i.e. not while
2149 ;; lazy-highlighting search strings in the current minibuffer text).
2154 (cond (isearch-forward
2155 (next-history-element 1)
2156 (goto-char (minibuffer-prompt-end)))
2158 (previous-history-element 1)
2159 (goto-char (point-max))))
2160 (setq isearch-barrier (point) isearch-opoint (point))
2161 ;; After putting the next/prev history element, search
2162 ;; the string in them again, until next-history-element
2163 ;; or previous-history-element raises an error at the
2164 ;; beginning/end of history.
2165 (setq found (funcall search-fun string
2166 (unless isearch-forward
2167 ;; For backward search, don't search
2168 ;; in the minibuffer prompt
2169 (minibuffer-prompt-end))
2171 ;; Return point of the new search result
2173 ;; Return nil when next(prev)-history-element fails
2176 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2177 "Display the minibuffer history search prompt.
2178 If there are no search errors, this function displays an overlay with
2179 the isearch prompt which replaces the original minibuffer prompt.
2180 Otherwise, it displays the standard isearch message returned from
2181 the function `isearch-message'."
2182 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2183 ;; Use standard function `isearch-message' when not in the minibuffer,
2184 ;; or search fails, or has an error (like incomplete regexp).
2185 ;; This function overwrites minibuffer text with isearch message,
2186 ;; so it's possible to see what is wrong in the search string.
2187 (isearch-message c-q-hack ellipsis)
2188 ;; Otherwise, put the overlay with the standard isearch prompt over
2189 ;; the initial minibuffer prompt.
2190 (if (overlayp minibuffer-history-isearch-message-overlay)
2191 (move-overlay minibuffer-history-isearch-message-overlay
2192 (point-min) (minibuffer-prompt-end))
2193 (setq minibuffer-history-isearch-message-overlay
2194 (make-overlay (point-min) (minibuffer-prompt-end)))
2195 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2196 (overlay-put minibuffer-history-isearch-message-overlay
2197 'display (isearch-message-prefix c-q-hack ellipsis))
2198 ;; And clear any previous isearch message.
2201 (defun minibuffer-history-isearch-wrap ()
2202 "Wrap the minibuffer history search when search fails.
2203 Move point to the first history element for a forward search,
2204 or to the last history element for a backward search."
2205 ;; When `minibuffer-history-isearch-search' fails on reaching the
2206 ;; beginning/end of the history, wrap the search to the first/last
2207 ;; minibuffer history element.
2209 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2210 (goto-history-element 0))
2211 (setq isearch-success t)
2212 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2214 (defun minibuffer-history-isearch-push-state ()
2215 "Save a function restoring the state of minibuffer history search.
2216 Save `minibuffer-history-position' to the additional state parameter
2217 in the search status stack."
2218 (let ((pos minibuffer-history-position))
2220 (minibuffer-history-isearch-pop-state cmd pos))))
2222 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2223 "Restore the minibuffer history search state.
2224 Go to the history element by the absolute history position HIST-POS."
2225 (goto-history-element hist-pos))
2228 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2229 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2231 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2232 "Table mapping redo records to the corresponding undo one.
2233 A redo record for undo-in-region maps to t.
2234 A redo record for ordinary undo maps to the following (earlier) undo.")
2236 (defvar undo-in-region nil
2237 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2239 (defvar undo-no-redo nil
2240 "If t, `undo' doesn't go through redo entries.")
2242 (defvar pending-undo-list nil
2243 "Within a run of consecutive undo commands, list remaining to be undone.
2244 If t, we undid all the way to the end of it.")
2246 (defun undo (&optional arg)
2247 "Undo some previous changes.
2248 Repeat this command to undo more changes.
2249 A numeric ARG serves as a repeat count.
2251 In Transient Mark mode when the mark is active, only undo changes within
2252 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2253 as an argument limits undo to changes within the current region."
2255 ;; Make last-command indicate for the next command that this was an undo.
2256 ;; That way, another undo will undo more.
2257 ;; If we get to the end of the undo history and get an error,
2258 ;; another undo command will find the undo history empty
2259 ;; and will get another error. To begin undoing the undos,
2260 ;; you must type some other command.
2261 (let* ((modified (buffer-modified-p))
2262 ;; For an indirect buffer, look in the base buffer for the
2264 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2265 (recent-save (with-current-buffer base-buffer
2266 (recent-auto-save-p)))
2268 ;; If we get an error in undo-start,
2269 ;; the next command should not be a "consecutive undo".
2270 ;; So set `this-command' to something other than `undo'.
2271 (setq this-command 'undo-start)
2273 (unless (and (eq last-command 'undo)
2274 (or (eq pending-undo-list t)
2275 ;; If something (a timer or filter?) changed the buffer
2276 ;; since the previous command, don't continue the undo seq.
2277 (let ((list buffer-undo-list))
2278 (while (eq (car list) nil)
2279 (setq list (cdr list)))
2280 ;; If the last undo record made was made by undo
2281 ;; it shows nothing else happened in between.
2282 (gethash list undo-equiv-table))))
2283 (setq undo-in-region
2284 (or (region-active-p) (and arg (not (numberp arg)))))
2286 (undo-start (region-beginning) (region-end))
2288 ;; get rid of initial undo boundary
2290 ;; If we got this far, the next command should be a consecutive undo.
2291 (setq this-command 'undo)
2292 ;; Check to see whether we're hitting a redo record, and if
2293 ;; so, ask the user whether she wants to skip the redo/undo pair.
2294 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2295 (or (eq (selected-window) (minibuffer-window))
2296 (setq message (format "%s%s!"
2297 (if (or undo-no-redo (not equiv))
2299 (if undo-in-region " in region" ""))))
2300 (when (and (consp equiv) undo-no-redo)
2301 ;; The equiv entry might point to another redo record if we have done
2302 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2303 (while (let ((next (gethash equiv undo-equiv-table)))
2304 (if next (setq equiv next))))
2305 (setq pending-undo-list equiv)))
2308 (prefix-numeric-value arg)
2310 ;; Record the fact that the just-generated undo records come from an
2311 ;; undo operation--that is, they are redo records.
2312 ;; In the ordinary case (not within a region), map the redo
2313 ;; record to the following undos.
2314 ;; I don't know how to do that in the undo-in-region case.
2315 (let ((list buffer-undo-list))
2316 ;; Strip any leading undo boundaries there might be, like we do
2317 ;; above when checking.
2318 (while (eq (car list) nil)
2319 (setq list (cdr list)))
2321 ;; Prevent identity mapping. This can happen if
2322 ;; consecutive nils are erroneously in undo list.
2323 (if (or undo-in-region (eq list pending-undo-list))
2327 ;; Don't specify a position in the undo record for the undo command.
2328 ;; Instead, undoing this should move point to where the change is.
2329 (let ((tail buffer-undo-list)
2332 (when (integerp (car tail))
2333 (let ((pos (car tail)))
2335 (setcdr prev (cdr tail))
2336 (setq buffer-undo-list (cdr tail)))
2337 (setq tail (cdr tail))
2339 (if (eq pos (car tail))
2341 (setcdr prev (cdr tail))
2342 (setq buffer-undo-list (cdr tail)))
2344 (setq tail (cdr tail)))
2346 (setq prev tail tail (cdr tail))))
2347 ;; Record what the current undo list says,
2348 ;; so the next command can tell if the buffer was modified in between.
2349 (and modified (not (buffer-modified-p))
2350 (with-current-buffer base-buffer
2351 (delete-auto-save-file-if-necessary recent-save)))
2352 ;; Display a message announcing success.
2354 (message "%s" message))))
2356 (defun buffer-disable-undo (&optional buffer)
2357 "Make BUFFER stop keeping undo information.
2358 No argument or nil as argument means do this for the current buffer."
2360 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2361 (setq buffer-undo-list t)))
2363 (defun undo-only (&optional arg)
2364 "Undo some previous changes.
2365 Repeat this command to undo more changes.
2366 A numeric ARG serves as a repeat count.
2367 Contrary to `undo', this will not redo a previous undo."
2369 (let ((undo-no-redo t)) (undo arg)))
2371 (defvar undo-in-progress nil
2372 "Non-nil while performing an undo.
2373 Some change-hooks test this variable to do something different.")
2375 (defun undo-more (n)
2376 "Undo back N undo-boundaries beyond what was already undone recently.
2377 Call `undo-start' to get ready to undo recent changes,
2378 then call `undo-more' one or more times to undo them."
2379 (or (listp pending-undo-list)
2380 (user-error (concat "No further undo information"
2381 (and undo-in-region " for region"))))
2382 (let ((undo-in-progress t))
2383 ;; Note: The following, while pulling elements off
2384 ;; `pending-undo-list' will call primitive change functions which
2385 ;; will push more elements onto `buffer-undo-list'.
2386 (setq pending-undo-list (primitive-undo n pending-undo-list))
2387 (if (null pending-undo-list)
2388 (setq pending-undo-list t))))
2390 (defun primitive-undo (n list)
2391 "Undo N records from the front of the list LIST.
2392 Return what remains of the list."
2394 ;; This is a good feature, but would make undo-start
2395 ;; unable to do what is expected.
2396 ;;(when (null (car (list)))
2397 ;; ;; If the head of the list is a boundary, it is the boundary
2398 ;; ;; preceding this command. Get rid of it and don't count it.
2399 ;; (setq list (cdr list))))
2402 ;; In a writable buffer, enable undoing read-only text that is
2403 ;; so because of text properties.
2404 (inhibit-read-only t)
2405 ;; Don't let `intangible' properties interfere with undo.
2406 (inhibit-point-motion-hooks t)
2407 ;; We use oldlist only to check for EQ. ++kfs
2408 (oldlist buffer-undo-list)
2412 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2413 ;; Handle an integer by setting point to that value.
2415 ((pred integerp) (goto-char next))
2416 ;; Element (t . TIME) records previous modtime.
2417 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2418 ;; UNKNOWN_MODTIME_NSECS.
2420 ;; If this records an obsolete save
2421 ;; (not matching the actual disk file)
2422 ;; then don't mark unmodified.
2423 (when (or (equal time (visited-file-modtime))
2425 (equal (list (car time) (cdr time))
2426 (visited-file-modtime))))
2427 (when (fboundp 'unlock-buffer)
2429 (set-buffer-modified-p nil)))
2430 ;; Element (nil PROP VAL BEG . END) is property change.
2431 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2432 (when (or (> (point-min) beg) (< (point-max) end))
2433 (error "Changes to be undone are outside visible portion of buffer"))
2434 (put-text-property beg end prop val))
2435 ;; Element (BEG . END) means range was inserted.
2436 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2437 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2438 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2439 (when (or (> (point-min) beg) (< (point-max) end))
2440 (error "Changes to be undone are outside visible portion of buffer"))
2441 ;; Set point first thing, so that undoing this undo
2442 ;; does not send point back to where it is now.
2444 (delete-region beg end))
2445 ;; Element (apply FUN . ARGS) means call FUN to undo.
2446 (`(apply . ,fun-args)
2447 (let ((currbuff (current-buffer)))
2448 (if (integerp (car fun-args))
2449 ;; Long format: (apply DELTA START END FUN . ARGS).
2450 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2451 (start-mark (copy-marker start nil))
2452 (end-mark (copy-marker end t)))
2453 (when (or (> (point-min) start) (< (point-max) end))
2454 (error "Changes to be undone are outside visible portion of buffer"))
2455 (apply fun args) ;; Use `save-current-buffer'?
2456 ;; Check that the function did what the entry
2457 ;; said it would do.
2458 (unless (and (= start start-mark)
2459 (= (+ delta end) end-mark))
2460 (error "Changes to be undone by function different than announced"))
2461 (set-marker start-mark nil)
2462 (set-marker end-mark nil))
2464 (unless (eq currbuff (current-buffer))
2465 (error "Undo function switched buffer"))
2466 (setq did-apply t)))
2467 ;; Element (STRING . POS) means STRING was deleted.
2468 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2469 (when (let ((apos (abs pos)))
2470 (or (< apos (point-min)) (> apos (point-max))))
2471 (error "Changes to be undone are outside visible portion of buffer"))
2472 (let (valid-marker-adjustments)
2473 ;; Check that marker adjustments which were recorded
2474 ;; with the (STRING . POS) record are still valid, ie
2475 ;; the markers haven't moved. We check their validity
2476 ;; before reinserting the string so as we don't need to
2477 ;; mind marker insertion-type.
2478 (while (and (markerp (car-safe (car list)))
2479 (integerp (cdr-safe (car list))))
2480 (let* ((marker-adj (pop list))
2481 (m (car marker-adj)))
2482 (and (eq (marker-buffer m) (current-buffer))
2484 (push marker-adj valid-marker-adjustments))))
2485 ;; Insert string and adjust point
2493 ;; Adjust the valid marker adjustments
2494 (dolist (adj valid-marker-adjustments)
2495 (set-marker (car adj)
2496 (- (car adj) (cdr adj))))))
2497 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2498 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2499 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2501 ;; Even though these elements are not expected in the undo
2502 ;; list, adjust them to be conservative for the 24.4
2503 ;; release. (Bug#16818)
2504 (when (marker-buffer marker)
2507 (marker-buffer marker))))
2508 (_ (error "Unrecognized entry in undo list %S" next))))
2509 (setq arg (1- arg)))
2510 ;; Make sure an apply entry produces at least one undo entry,
2511 ;; so the test in `undo' for continuing an undo series
2514 (eq oldlist buffer-undo-list))
2515 (setq buffer-undo-list
2516 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2519 ;; Deep copy of a list
2520 (defun undo-copy-list (list)
2521 "Make a copy of undo list LIST."
2522 (mapcar 'undo-copy-list-1 list))
2524 (defun undo-copy-list-1 (elt)
2526 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2529 (defun undo-start (&optional beg end)
2530 "Set `pending-undo-list' to the front of the undo list.
2531 The next call to `undo-more' will undo the most recently made change.
2532 If BEG and END are specified, then only undo elements
2533 that apply to text between BEG and END are used; other undo elements
2534 are ignored. If BEG and END are nil, all undo elements are used."
2535 (if (eq buffer-undo-list t)
2536 (user-error "No undo information in this buffer"))
2537 (setq pending-undo-list
2538 (if (and beg end (not (= beg end)))
2539 (undo-make-selective-list (min beg end) (max beg end))
2542 ;; The positions given in elements of the undo list are the positions
2543 ;; as of the time that element was recorded to undo history. In
2544 ;; general, subsequent buffer edits render those positions invalid in
2545 ;; the current buffer, unless adjusted according to the intervening
2548 ;; Undo in region is a use case that requires adjustments to undo
2549 ;; elements. It must adjust positions of elements in the region based
2550 ;; on newer elements not in the region so as they may be correctly
2551 ;; applied in the current buffer. undo-make-selective-list
2552 ;; accomplishes this with its undo-deltas list of adjustments. An
2553 ;; example undo history from oldest to newest:
2556 ;; 123456789 buffer-undo-list undo-deltas
2557 ;; --------- ---------------- -----------
2558 ;; aaa (1 . 4) (1 . -3)
2559 ;; aaba (3 . 4) N/A (in region)
2560 ;; ccaaba (1 . 3) (1 . -2)
2561 ;; ccaabaddd (7 . 10) (7 . -3)
2562 ;; ccaabdd ("ad" . 6) (6 . 2)
2563 ;; ccaabaddd (6 . 8) (6 . -2)
2564 ;; | |<-- region: "caab", from 2 to 6
2566 ;; When the user starts a run of undos in region,
2567 ;; undo-make-selective-list is called to create the full list of in
2568 ;; region elements. Each element is adjusted forward chronologically
2569 ;; through undo-deltas to determine if it is in the region.
2571 ;; In the above example, the insertion of "b" is (3 . 4) in the
2572 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2573 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2574 ;; . 6) is assessed as in the region and placed in the selective list.
2575 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2576 ;; due to the selected element. The "b" insertion is the only element
2577 ;; fully in the region, so in this example undo-make-selective-list
2578 ;; returns (nil (5 . 6)).
2580 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2581 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2582 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2583 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2584 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2586 ;; More interesting is how to adjust the "ddd" insertion due to the
2587 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2588 ;; If the reinsertion was a manual retyping of "ad", then the total
2589 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2590 ;; the reinsertion was due to undo, one might expect the first "d"
2591 ;; character would again be a part of the "ddd" text, meaning its
2592 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2594 ;; undo-make-selective-list assumes in this situation that "ad" was a
2595 ;; new edit, even if it was inserted because of an undo.
2596 ;; Consequently, if the user undos in region "8 to 10" of the
2597 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2598 ;; "ccaabad", as though the first "d" became detached from the
2599 ;; original "ddd" insertion. This quirk is a FIXME.
2601 (defun undo-make-selective-list (start end)
2602 "Return a list of undo elements for the region START to END.
2603 The elements come from `buffer-undo-list', but we keep only the
2604 elements inside this region, and discard those outside this
2605 region. The elements' positions are adjusted so as the returned
2606 list can be applied to the current buffer."
2607 (let ((ulist buffer-undo-list)
2608 ;; A list of position adjusted undo elements in the region.
2609 (selective-list (list nil))
2610 ;; A list of undo-deltas for out of region undo elements.
2615 (while (gethash ulist undo-equiv-table)
2616 (setq ulist (gethash ulist undo-equiv-table))))
2617 (setq undo-elt (car ulist))
2620 ;; Don't put two nils together in the list
2621 (when (car selective-list)
2622 (push nil selective-list)))
2623 ((and (consp undo-elt) (eq (car undo-elt) t))
2624 ;; This is a "was unmodified" element. Keep it
2625 ;; if we have kept everything thus far.
2626 (when (not undo-deltas)
2627 (push undo-elt selective-list)))
2628 ;; Skip over marker adjustments, instead relying
2629 ;; on finding them after (TEXT . POS) elements
2630 ((markerp (car-safe undo-elt))
2633 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2635 (if (undo-elt-in-region adjusted-undo-elt start end)
2637 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2638 (push adjusted-undo-elt selective-list)
2639 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2640 ;; kept. primitive-undo may discard them later.
2641 (when (and (stringp (car-safe adjusted-undo-elt))
2642 (integerp (cdr-safe adjusted-undo-elt)))
2643 (let ((list-i (cdr ulist)))
2644 (while (markerp (car-safe (car list-i)))
2645 (push (pop list-i) selective-list)))))
2646 (let ((delta (undo-delta undo-elt)))
2647 (when (/= 0 (cdr delta))
2648 (push delta undo-deltas)))))))
2650 (nreverse selective-list)))
2652 (defun undo-elt-in-region (undo-elt start end)
2653 "Determine whether UNDO-ELT falls inside the region START ... END.
2654 If it crosses the edge, we return nil.
2656 Generally this function is not useful for determining
2657 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2658 because markers can be arbitrarily relocated. Instead, pass the
2659 marker adjustment's corresponding (TEXT . POS) element."
2660 (cond ((integerp undo-elt)
2661 (and (>= undo-elt start)
2667 ((stringp (car undo-elt))
2668 ;; (TEXT . POSITION)
2669 (and (>= (abs (cdr undo-elt)) start)
2670 (<= (abs (cdr undo-elt)) end)))
2671 ((and (consp undo-elt) (markerp (car undo-elt)))
2672 ;; (MARKER . ADJUSTMENT)
2673 (<= start (car undo-elt) end))
2674 ((null (car undo-elt))
2675 ;; (nil PROPERTY VALUE BEG . END)
2676 (let ((tail (nthcdr 3 undo-elt)))
2677 (and (>= (car tail) start)
2678 (<= (cdr tail) end))))
2679 ((integerp (car undo-elt))
2681 (and (>= (car undo-elt) start)
2682 (<= (cdr undo-elt) end)))))
2684 (defun undo-elt-crosses-region (undo-elt start end)
2685 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2686 This assumes we have already decided that UNDO-ELT
2687 is not *inside* the region START...END."
2688 (declare (obsolete nil "25.1"))
2689 (cond ((atom undo-elt) nil)
2690 ((null (car undo-elt))
2691 ;; (nil PROPERTY VALUE BEG . END)
2692 (let ((tail (nthcdr 3 undo-elt)))
2693 (and (< (car tail) end)
2694 (> (cdr tail) start))))
2695 ((integerp (car undo-elt))
2697 (and (< (car undo-elt) end)
2698 (> (cdr undo-elt) start)))))
2700 (defun undo-adjust-elt (elt deltas)
2701 "Return adjustment of undo element ELT by the undo DELTAS
2706 (undo-adjust-pos elt deltas))
2708 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2709 (undo-adjust-beg-end beg end deltas))
2710 ;; (TEXT . POSITION)
2711 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2712 (cons text (* (if (< pos 0) -1 1)
2713 (undo-adjust-pos (abs pos) deltas))))
2714 ;; (nil PROPERTY VALUE BEG . END)
2715 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2716 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2717 ;; (apply DELTA START END FUN . ARGS)
2719 ;; All others return same elt
2722 ;; (BEG . END) can adjust to the same positions, commonly when an
2723 ;; insertion was undone and they are out of region, for example:
2726 ;; 123456789 buffer-undo-list undo-deltas
2727 ;; --------- ---------------- -----------
2729 ;; abbaa (2 . 4) (2 . -2)
2730 ;; aaa ("bb" . 2) (2 . 2)
2733 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2734 ;; undo. Further adjustments to such an element should be the same as
2735 ;; for (TEXT . POSITION) elements. The options are:
2737 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2738 ;; analogous to marker insertion-type t.
2740 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2741 ;; marker insertion-type nil.
2743 ;; There was no strong reason to prefer one or the other, except that
2744 ;; the first is more consistent with prior undo in region behavior.
2745 (defun undo-adjust-beg-end (beg end deltas)
2746 "Return cons of adjustments to BEG and END by the undo DELTAS
2748 (let ((adj-beg (undo-adjust-pos beg deltas)))
2749 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2751 (max adj-beg (undo-adjust-pos end deltas t)))))
2753 (defun undo-adjust-pos (pos deltas &optional use-<)
2754 "Return adjustment of POS by the undo DELTAS list, comparing
2755 with < or <= based on USE-<."
2756 (dolist (d deltas pos)
2761 ;; Don't allow pos to become less than the undo-delta
2762 ;; position. This edge case is described in the overview
2764 (max (car d) (- pos (cdr d)))))))
2766 ;; Return the first affected buffer position and the delta for an undo element
2767 ;; delta is defined as the change in subsequent buffer positions if we *did*
2769 (defun undo-delta (undo-elt)
2770 (if (consp undo-elt)
2771 (cond ((stringp (car undo-elt))
2772 ;; (TEXT . POSITION)
2773 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2774 ((integerp (car undo-elt))
2776 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2781 ;;; Default undo-boundary addition
2783 ;; This section adds a new undo-boundary at either after a command is
2784 ;; called or in some cases on a timer called after a change is made in
2786 (defvar-local undo-auto--last-boundary-cause nil
2787 "Describe the cause of the last undo-boundary.
2789 If `explicit', the last boundary was caused by an explicit call to
2790 `undo-boundary', that is one not called by the code in this
2793 If it is equal to `timer', then the last boundary was inserted
2794 by `undo-auto--boundary-timer'.
2796 If it is equal to `command', then the last boundary was inserted
2797 automatically after a command, that is by the code defined in
2800 If it is equal to a list, then the last boundary was inserted by
2801 an amalgamating command. The car of the list is the number of
2802 times an amalgamating command has been called, and the cdr are the
2803 buffers that were changed during the last command.")
2805 (defvar undo-auto--current-boundary-timer nil
2806 "Current timer which will run `undo-auto--boundary-timer' or nil.
2808 If set to non-nil, this will effectively disable the timer.")
2810 (defvar undo-auto--this-command-amalgamating nil
2811 "Non-nil if `this-command' should be amalgamated.
2812 This variable is set to nil by `undo-auto--boundaries' and is set
2813 by `undo-auto--amalgamate'." )
2815 (defun undo-auto--needs-boundary-p ()
2816 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2817 (car-safe buffer-undo-list))
2819 (defun undo-auto--last-boundary-amalgamating-number ()
2820 "Return the number of amalgamating last commands or nil.
2821 Amalgamating commands are, by default, either
2822 `self-insert-command' and `delete-char', but can be any command
2823 that calls `undo-auto--amalgamate'."
2824 (car-safe undo-auto--last-boundary-cause))
2826 (defun undo-auto--ensure-boundary (cause)
2827 "Add an `undo-boundary' to the current buffer if needed.
2828 REASON describes the reason that the boundary is being added; see
2829 `undo-auto--last-boundary' for more information."
2831 (undo-auto--needs-boundary-p))
2832 (let ((last-amalgamating
2833 (undo-auto--last-boundary-amalgamating-number)))
2835 (setq undo-auto--last-boundary-cause
2836 (if (eq 'amalgamate cause)
2838 (if last-amalgamating (1+ last-amalgamating) 0)
2839 undo-auto--undoably-changed-buffers)
2842 (defun undo-auto--boundaries (cause)
2843 "Check recently changed buffers and add a boundary if necessary.
2844 REASON describes the reason that the boundary is being added; see
2845 `undo-last-boundary' for more information."
2846 (dolist (b undo-auto--undoably-changed-buffers)
2847 (when (buffer-live-p b)
2848 (with-current-buffer b
2849 (undo-auto--ensure-boundary cause))))
2850 (setq undo-auto--undoably-changed-buffers nil))
2852 (defun undo-auto--boundary-timer ()
2853 "Timer which will run `undo--auto-boundary-timer'."
2854 (setq undo-auto--current-boundary-timer nil)
2855 (undo-auto--boundaries 'timer))
2857 (defun undo-auto--boundary-ensure-timer ()
2858 "Ensure that the `undo-auto-boundary-timer' is set."
2859 (unless undo-auto--current-boundary-timer
2860 (setq undo-auto--current-boundary-timer
2861 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2863 (defvar undo-auto--undoably-changed-buffers nil
2864 "List of buffers that have changed recently.
2866 This list is maintained by `undo-auto--undoable-change' and
2867 `undo-auto--boundaries' and can be affected by changes to their
2870 See also `undo-auto--buffer-undoably-changed'.")
2872 (defun undo-auto--add-boundary ()
2873 "Add an `undo-boundary' in appropriate buffers."
2874 (undo-auto--boundaries
2875 (let ((amal undo-auto--this-command-amalgamating))
2876 (setq undo-auto--this-command-amalgamating nil)
2881 (defun undo-auto--amalgamate ()
2882 "Amalgamate undo if necessary.
2883 This function can be called after an amalgamating command. It
2884 removes the previous `undo-boundary' if a series of such calls
2885 have been made. By default `self-insert-command' and
2886 `delete-char' are the only amalgamating commands, although this
2887 function could be called by any command wishing to have this
2889 (let ((last-amalgamating-count
2890 (undo-auto--last-boundary-amalgamating-number)))
2891 (setq undo-auto--this-command-amalgamating t)
2893 last-amalgamating-count
2896 (< last-amalgamating-count 20)
2897 (eq this-command last-command))
2898 ;; Amalgamate all buffers that have changed.
2899 (dolist (b (cdr undo-auto--last-boundary-cause))
2900 (when (buffer-live-p b)
2901 (with-current-buffer
2904 ;; The head of `buffer-undo-list' is nil.
2905 ;; `car-safe' doesn't work because
2906 ;; `buffer-undo-list' need not be a list!
2907 (and (listp buffer-undo-list)
2908 (not (car buffer-undo-list)))
2909 (setq buffer-undo-list
2910 (cdr buffer-undo-list))))))
2911 (setq undo-auto--last-boundary-cause 0)))))
2913 (defun undo-auto--undoable-change ()
2914 "Called after every undoable buffer change."
2915 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
2916 (undo-auto--boundary-ensure-timer))
2917 ;; End auto-boundary section
2919 (defcustom undo-ask-before-discard nil
2920 "If non-nil ask about discarding undo info for the current command.
2921 Normally, Emacs discards the undo info for the current command if
2922 it exceeds `undo-outer-limit'. But if you set this option
2923 non-nil, it asks in the echo area whether to discard the info.
2924 If you answer no, there is a slight risk that Emacs might crash, so
2925 only do it if you really want to undo the command.
2927 This option is mainly intended for debugging. You have to be
2928 careful if you use it for other purposes. Garbage collection is
2929 inhibited while the question is asked, meaning that Emacs might
2930 leak memory. So you should make sure that you do not wait
2931 excessively long before answering the question."
2936 (defvar undo-extra-outer-limit nil
2937 "If non-nil, an extra level of size that's ok in an undo item.
2938 We don't ask the user about truncating the undo list until the
2939 current item gets bigger than this amount.
2941 This variable only matters if `undo-ask-before-discard' is non-nil.")
2942 (make-variable-buffer-local 'undo-extra-outer-limit)
2944 ;; When the first undo batch in an undo list is longer than
2945 ;; undo-outer-limit, this function gets called to warn the user that
2946 ;; the undo info for the current command was discarded. Garbage
2947 ;; collection is inhibited around the call, so it had better not do a
2949 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2950 (defun undo-outer-limit-truncate (size)
2951 (if undo-ask-before-discard
2952 (when (or (null undo-extra-outer-limit)
2953 (> size undo-extra-outer-limit))
2954 ;; Don't ask the question again unless it gets even bigger.
2955 ;; This applies, in particular, if the user quits from the question.
2956 ;; Such a quit quits out of GC, but something else will call GC
2957 ;; again momentarily. It will call this function again,
2958 ;; but we don't want to ask the question again.
2959 (setq undo-extra-outer-limit (+ size 50000))
2960 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2961 (yes-or-no-p (format-message
2962 "Buffer `%s' undo info is %d bytes long; discard it? "
2963 (buffer-name) size)))
2964 (progn (setq buffer-undo-list nil)
2965 (setq undo-extra-outer-limit nil)
2968 (display-warning '(undo discard-info)
2971 "Buffer `%s' undo info was %d bytes long.\n"
2973 "The undo info was discarded because it exceeded \
2976 This is normal if you executed a command that made a huge change
2977 to the buffer. In that case, to prevent similar problems in the
2978 future, set `undo-outer-limit' to a value that is large enough to
2979 cover the maximum size of normal changes you expect a single
2980 command to make, but not so large that it might exceed the
2981 maximum memory allotted to Emacs.
2983 If you did not execute any such command, the situation is
2984 probably due to a bug and you should report it.
2986 You can disable the popping up of this buffer by adding the entry
2987 \(undo discard-info) to the user option `warning-suppress-types',
2988 which is defined in the `warnings' library.\n")
2990 (setq buffer-undo-list nil)
2993 (defcustom password-word-equivalents
2994 '("password" "passcode" "passphrase" "pass phrase"
2995 ; These are sorted according to the GNU en_US locale.
2998 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3024 "пароль" ; kk, ru, uk
3039 "List of words equivalent to \"password\".
3040 This is used by Shell mode and other parts of Emacs to recognize
3041 password prompts, including prompts in languages other than
3042 English. Different case choices should not be assumed to be
3043 included; callers should bind `case-fold-search' to t."
3044 :type '(repeat string)
3048 (defvar shell-command-history nil
3049 "History list for some commands that read shell commands.
3051 Maximum length of the history list is determined by the value
3052 of `history-length', which see.")
3054 (defvar shell-command-switch (purecopy "-c")
3055 "Switch used to have the shell execute its command line argument.")
3057 (defvar shell-command-default-error-buffer nil
3058 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3059 This buffer is used when `shell-command' or `shell-command-on-region'
3060 is run interactively. A value of nil means that output to stderr and
3061 stdout will be intermixed in the output stream.")
3063 (declare-function mailcap-file-default-commands "mailcap" (files))
3064 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3066 (defun minibuffer-default-add-shell-commands ()
3067 "Return a list of all commands associated with the current file.
3068 This function is used to add all related commands retrieved by `mailcap'
3069 to the end of the list of defaults just after the default value."
3071 (let* ((filename (if (listp minibuffer-default)
3072 (car minibuffer-default)
3073 minibuffer-default))
3074 (commands (and filename (require 'mailcap nil t)
3075 (mailcap-file-default-commands (list filename)))))
3076 (setq commands (mapcar (lambda (command)
3077 (concat command " " filename))
3079 (if (listp minibuffer-default)
3080 (append minibuffer-default commands)
3081 (cons minibuffer-default commands))))
3083 (declare-function shell-completion-vars "shell" ())
3085 (defvar minibuffer-local-shell-command-map
3086 (let ((map (make-sparse-keymap)))
3087 (set-keymap-parent map minibuffer-local-map)
3088 (define-key map "\t" 'completion-at-point)
3090 "Keymap used for completing shell commands in minibuffer.")
3092 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3093 "Read a shell command from the minibuffer.
3094 The arguments are the same as the ones of `read-from-minibuffer',
3095 except READ and KEYMAP are missing and HIST defaults
3096 to `shell-command-history'."
3098 (minibuffer-with-setup-hook
3100 (shell-completion-vars)
3101 (set (make-local-variable 'minibuffer-default-add-function)
3102 'minibuffer-default-add-shell-commands))
3103 (apply 'read-from-minibuffer prompt initial-contents
3104 minibuffer-local-shell-command-map
3106 (or hist 'shell-command-history)
3109 (defcustom async-shell-command-buffer 'confirm-new-buffer
3110 "What to do when the output buffer is used by another shell command.
3111 This option specifies how to resolve the conflict where a new command
3112 wants to direct its output to the buffer `*Async Shell Command*',
3113 but this buffer is already taken by another running shell command.
3115 The value `confirm-kill-process' is used to ask for confirmation before
3116 killing the already running process and running a new process
3117 in the same buffer, `confirm-new-buffer' for confirmation before running
3118 the command in a new buffer with a name other than the default buffer name,
3119 `new-buffer' for doing the same without confirmation,
3120 `confirm-rename-buffer' for confirmation before renaming the existing
3121 output buffer and running a new command in the default buffer,
3122 `rename-buffer' for doing the same without confirmation."
3123 :type '(choice (const :tag "Confirm killing of running command"
3124 confirm-kill-process)
3125 (const :tag "Confirm creation of a new buffer"
3127 (const :tag "Create a new buffer"
3129 (const :tag "Confirm renaming of existing buffer"
3130 confirm-rename-buffer)
3131 (const :tag "Rename the existing buffer"
3136 (defun async-shell-command (command &optional output-buffer error-buffer)
3137 "Execute string COMMAND asynchronously in background.
3139 Like `shell-command', but adds `&' at the end of COMMAND
3140 to execute it asynchronously.
3142 The output appears in the buffer `*Async Shell Command*'.
3143 That buffer is in shell mode.
3145 You can configure `async-shell-command-buffer' to specify what to do in
3146 case when `*Async Shell Command*' buffer is already taken by another
3147 running shell command. To run COMMAND without displaying the output
3148 in a window you can configure `display-buffer-alist' to use the action
3149 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3151 In Elisp, you will often be better served by calling `start-process'
3152 directly, since it offers more control and does not impose the use of a
3153 shell (with its need to quote arguments)."
3156 (read-shell-command "Async shell command: " nil nil
3160 ((eq major-mode 'dired-mode)
3161 (dired-get-filename nil t)))))
3162 (and filename (file-relative-name filename))))
3164 shell-command-default-error-buffer))
3165 (unless (string-match "&[ \t]*\\'" command)
3166 (setq command (concat command " &")))
3167 (shell-command command output-buffer error-buffer))
3169 (defun shell-command (command &optional output-buffer error-buffer)
3170 "Execute string COMMAND in inferior shell; display output, if any.
3171 With prefix argument, insert the COMMAND's output at point.
3173 If COMMAND ends in `&', execute it asynchronously.
3174 The output appears in the buffer `*Async Shell Command*'.
3175 That buffer is in shell mode. You can also use
3176 `async-shell-command' that automatically adds `&'.
3178 Otherwise, COMMAND is executed synchronously. The output appears in
3179 the buffer `*Shell Command Output*'. If the output is short enough to
3180 display in the echo area (which is determined by the variables
3181 `resize-mini-windows' and `max-mini-window-height'), it is shown
3182 there, but it is nonetheless available in buffer `*Shell Command
3183 Output*' even though that buffer is not automatically displayed.
3185 To specify a coding system for converting non-ASCII characters
3186 in the shell command output, use \\[universal-coding-system-argument] \
3187 before this command.
3189 Noninteractive callers can specify coding systems by binding
3190 `coding-system-for-read' and `coding-system-for-write'.
3192 The optional second argument OUTPUT-BUFFER, if non-nil,
3193 says to put the output in some other buffer.
3194 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
3195 If OUTPUT-BUFFER is not a buffer and not nil,
3196 insert output in current buffer. (This cannot be done asynchronously.)
3197 In either case, the buffer is first erased, and the output is
3198 inserted after point (leaving mark after it).
3200 If the command terminates without error, but generates output,
3201 and you did not specify \"insert it in the current buffer\",
3202 the output can be displayed in the echo area or in its buffer.
3203 If the output is short enough to display in the echo area
3204 \(determined by the variable `max-mini-window-height' if
3205 `resize-mini-windows' is non-nil), it is shown there.
3206 Otherwise,the buffer containing the output is displayed.
3208 If there is output and an error, and you did not specify \"insert it
3209 in the current buffer\", a message about the error goes at the end
3212 If there is no output, or if output is inserted in the current buffer,
3213 then `*Shell Command Output*' is deleted.
3215 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3216 or buffer name to which to direct the command's standard error output.
3217 If it is nil, error output is mingled with regular output.
3218 In an interactive call, the variable `shell-command-default-error-buffer'
3219 specifies the value of ERROR-BUFFER.
3221 In Elisp, you will often be better served by calling `call-process' or
3222 `start-process' directly, since it offers more control and does not impose
3223 the use of a shell (with its need to quote arguments)."
3227 (read-shell-command "Shell command: " nil nil
3231 ((eq major-mode 'dired-mode)
3232 (dired-get-filename nil t)))))
3233 (and filename (file-relative-name filename))))
3235 shell-command-default-error-buffer))
3236 ;; Look for a handler in case default-directory is a remote file name.
3238 (find-file-name-handler (directory-file-name default-directory)
3241 (funcall handler 'shell-command command output-buffer error-buffer)
3242 (if (and output-buffer
3243 (not (or (bufferp output-buffer) (stringp output-buffer))))
3244 ;; Output goes in current buffer.
3248 (expand-file-name "scor"
3249 (or small-temporary-file-directory
3250 temporary-file-directory)))
3252 (barf-if-buffer-read-only)
3254 ;; We do not use -f for csh; we will not support broken use of
3255 ;; .cshrcs. Even the BSD csh manual says to use
3256 ;; "if ($?prompt) exit" before things which are not useful
3257 ;; non-interactively. Besides, if someone wants their other
3258 ;; aliases for shell commands then they can still have them.
3259 (call-process shell-file-name nil
3263 nil shell-command-switch command)
3264 (when (and error-file (file-exists-p error-file))
3265 (if (< 0 (nth 7 (file-attributes error-file)))
3266 (with-current-buffer (get-buffer-create error-buffer)
3267 (let ((pos-from-end (- (point-max) (point))))
3270 ;; Do no formatting while reading error file,
3271 ;; because that can run a shell command, and we
3272 ;; don't want that to cause an infinite recursion.
3273 (format-insert-file error-file nil)
3274 ;; Put point after the inserted errors.
3275 (goto-char (- (point-max) pos-from-end)))
3276 (display-buffer (current-buffer))))
3277 (delete-file error-file))
3278 ;; This is like exchange-point-and-mark, but doesn't
3279 ;; activate the mark. It is cleaner to avoid activation,
3280 ;; even though the command loop would deactivate the mark
3281 ;; because we inserted text.
3282 (goto-char (prog1 (mark t)
3283 (set-marker (mark-marker) (point)
3284 (current-buffer)))))
3285 ;; Output goes in a separate buffer.
3286 ;; Preserve the match data in case called from a program.
3288 (if (string-match "[ \t]*&[ \t]*\\'" command)
3289 ;; Command ending with ampersand means asynchronous.
3290 (let ((buffer (get-buffer-create
3291 (or output-buffer "*Async Shell Command*")))
3292 (directory default-directory)
3294 ;; Remove the ampersand.
3295 (setq command (substring command 0 (match-beginning 0)))
3296 ;; Ask the user what to do with already running process.
3297 (setq proc (get-buffer-process buffer))
3300 ((eq async-shell-command-buffer 'confirm-kill-process)
3301 ;; If will kill a process, query first.
3302 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3304 (error "Shell command in progress")))
3305 ((eq async-shell-command-buffer 'confirm-new-buffer)
3306 ;; If will create a new buffer, query first.
3307 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3308 (setq buffer (generate-new-buffer
3309 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3310 output-buffer "*Async Shell Command*")))
3311 (error "Shell command in progress")))
3312 ((eq async-shell-command-buffer 'new-buffer)
3313 ;; It will create a new buffer.
3314 (setq buffer (generate-new-buffer
3315 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3316 output-buffer "*Async Shell Command*"))))
3317 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3318 ;; If will rename the buffer, query first.
3319 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3321 (with-current-buffer buffer
3323 (setq buffer (get-buffer-create
3324 (or output-buffer "*Async Shell Command*"))))
3325 (error "Shell command in progress")))
3326 ((eq async-shell-command-buffer 'rename-buffer)
3327 ;; It will rename the buffer.
3328 (with-current-buffer buffer
3330 (setq buffer (get-buffer-create
3331 (or output-buffer "*Async Shell Command*"))))))
3332 (with-current-buffer buffer
3333 (setq buffer-read-only nil)
3334 ;; Setting buffer-read-only to nil doesn't suffice
3335 ;; if some text has a non-nil read-only property,
3336 ;; which comint sometimes adds for prompts.
3337 (let ((inhibit-read-only t))
3339 (display-buffer buffer '(nil (allow-no-window . t)))
3340 (setq default-directory directory)
3341 (setq proc (start-process "Shell" buffer shell-file-name
3342 shell-command-switch command))
3343 (setq mode-line-process '(":%s"))
3344 (require 'shell) (shell-mode)
3345 (set-process-sentinel proc 'shell-command-sentinel)
3346 ;; Use the comint filter for proper handling of carriage motion
3347 ;; (see `comint-inhibit-carriage-motion'),.
3348 (set-process-filter proc 'comint-output-filter)
3350 ;; Otherwise, command is executed synchronously.
3351 (shell-command-on-region (point) (point) command
3352 output-buffer nil error-buffer)))))))
3354 (defun display-message-or-buffer (message
3355 &optional buffer-name not-this-window frame)
3356 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3357 MESSAGE may be either a string or a buffer.
3359 A buffer is displayed using `display-buffer' if MESSAGE is too long for
3360 the maximum height of the echo area, as defined by `max-mini-window-height'
3361 if `resize-mini-windows' is non-nil.
3363 Returns either the string shown in the echo area, or when a pop-up
3364 buffer is used, the window used to display it.
3366 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3367 name of the buffer used to display it in the case where a pop-up buffer
3368 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3369 string and it is displayed in the echo area, it is not specified whether
3370 the contents are inserted into the buffer anyway.
3372 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
3373 and only used if a buffer is displayed."
3374 (cond ((and (stringp message) (not (string-match "\n" message)))
3375 ;; Trivial case where we can use the echo area
3376 (message "%s" message))
3377 ((and (stringp message)
3378 (= (string-match "\n" message) (1- (length message))))
3379 ;; Trivial case where we can just remove single trailing newline
3380 (message "%s" (substring message 0 (1- (length message)))))
3383 (with-current-buffer
3384 (if (bufferp message)
3386 (get-buffer-create (or buffer-name "*Message*")))
3388 (unless (bufferp message)
3393 (if (= (buffer-size) 0)
3395 (count-screen-lines nil nil nil (minibuffer-window)))))
3397 ((and (or (<= lines 1)
3399 (if resize-mini-windows
3400 (cond ((floatp max-mini-window-height)
3402 max-mini-window-height))
3403 ((integerp max-mini-window-height)
3404 max-mini-window-height)
3408 ;; Don't use the echo area if the output buffer is
3409 ;; already displayed in the selected frame.
3410 (not (get-buffer-window (current-buffer))))
3412 (goto-char (point-max))
3415 (message "%s" (buffer-substring (point-min) (point))))
3418 (goto-char (point-min))
3419 (display-buffer (current-buffer)
3420 not-this-window frame))))))))
3423 ;; We have a sentinel to prevent insertion of a termination message
3424 ;; in the buffer itself.
3425 (defun shell-command-sentinel (process signal)
3426 (if (memq (process-status process) '(exit signal))
3428 (car (cdr (cdr (process-command process))))
3429 (substring signal 0 -1))))
3431 (defun shell-command-on-region (start end command
3432 &optional output-buffer replace
3433 error-buffer display-error-buffer
3434 region-noncontiguous-p)
3435 "Execute string COMMAND in inferior shell with region as input.
3436 Normally display output (if any) in temp buffer `*Shell Command Output*';
3437 Prefix arg means replace the region with it. Return the exit code of
3440 To specify a coding system for converting non-ASCII characters
3441 in the input and output to the shell command, use \\[universal-coding-system-argument]
3442 before this command. By default, the input (from the current buffer)
3443 is encoded using coding-system specified by `process-coding-system-alist',
3444 falling back to `default-process-coding-system' if no match for COMMAND
3445 is found in `process-coding-system-alist'.
3447 Noninteractive callers can specify coding systems by binding
3448 `coding-system-for-read' and `coding-system-for-write'.
3450 If the command generates output, the output may be displayed
3451 in the echo area or in a buffer.
3452 If the output is short enough to display in the echo area
3453 \(determined by the variable `max-mini-window-height' if
3454 `resize-mini-windows' is non-nil), it is shown there.
3455 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3456 The output is available in that buffer in both cases.
3458 If there is output and an error, a message about the error
3459 appears at the end of the output. If there is no output, or if
3460 output is inserted in the current buffer, the buffer `*Shell
3461 Command Output*' is deleted.
3463 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3464 command's output. If the value is a buffer or buffer name,
3465 put the output there. If the value is nil, use the buffer
3466 `*Shell Command Output*'. Any other value, excluding nil,
3467 means to insert the output in the current buffer. In either case,
3468 the output is inserted after point (leaving mark after it).
3470 Optional fifth arg REPLACE, if non-nil, means to insert the
3471 output in place of text from START to END, putting point and mark
3474 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3475 or buffer name to which to direct the command's standard error
3476 output. If nil, error output is mingled with regular output.
3477 When called interactively, `shell-command-default-error-buffer'
3478 is used for ERROR-BUFFER.
3480 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3481 display the error buffer if there were any errors. When called
3482 interactively, this is t."
3483 (interactive (let (string)
3485 (user-error "The mark is not set now, so there is no region"))
3486 ;; Do this before calling region-beginning
3487 ;; and region-end, in case subprocess output
3488 ;; relocates them while we are in the minibuffer.
3489 (setq string (read-shell-command "Shell command on region: "))
3490 ;; call-interactively recognizes region-beginning and
3491 ;; region-end specially, leaving them in the history.
3492 (list (region-beginning) (region-end)
3496 shell-command-default-error-buffer
3498 (region-noncontiguous-p))))
3502 (expand-file-name "scor"
3503 (or small-temporary-file-directory
3504 temporary-file-directory)))
3507 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3508 (if region-noncontiguous-p
3509 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3513 (call-process-region (point-min) (point-max)
3515 nil shell-command-switch
3517 (setq output (split-string (buffer-string) "\n")))
3519 (funcall region-insert-function output))
3522 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3523 ;; Replace specified region with output from command.
3524 (let ((swap (and replace (< start end))))
3525 ;; Don't muck with mark unless REPLACE says we should.
3527 (and replace (push-mark (point) 'nomsg))
3529 (call-process-region start end shell-file-name replace
3533 nil shell-command-switch command))
3534 ;; It is rude to delete a buffer which the command is not using.
3535 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3536 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3537 ;; (kill-buffer shell-buffer)))
3538 ;; Don't muck with mark unless REPLACE says we should.
3539 (and replace swap (exchange-point-and-mark)))
3540 ;; No prefix argument: put the output in a temp buffer,
3541 ;; replacing its entire contents.
3542 (let ((buffer (get-buffer-create
3543 (or output-buffer "*Shell Command Output*"))))
3545 (if (eq buffer (current-buffer))
3546 ;; If the input is the same buffer as the output,
3547 ;; delete everything but the specified region,
3548 ;; then replace that region with the output.
3549 (progn (setq buffer-read-only nil)
3550 (delete-region (max start end) (point-max))
3551 (delete-region (point-min) (min start end))
3553 (call-process-region (point-min) (point-max)
3558 nil shell-command-switch
3560 ;; Clear the output buffer, then run the command with
3562 (let ((directory default-directory))
3563 (with-current-buffer buffer
3564 (setq buffer-read-only nil)
3565 (if (not output-buffer)
3566 (setq default-directory directory))
3569 (call-process-region start end shell-file-name nil
3571 (list buffer error-file)
3573 nil shell-command-switch command)))
3574 ;; Report the output.
3575 (with-current-buffer buffer
3576 (setq mode-line-process
3577 (cond ((null exit-status)
3579 ((stringp exit-status)
3580 (format " - Signal [%s]" exit-status))
3581 ((not (equal 0 exit-status))
3582 (format " - Exit [%d]" exit-status)))))
3583 (if (with-current-buffer buffer (> (point-max) (point-min)))
3584 ;; There's some output, display it
3585 (display-message-or-buffer buffer)
3586 ;; No output; error?
3589 (< 0 (nth 7 (file-attributes error-file))))
3590 (format "some error output%s"
3591 (if shell-command-default-error-buffer
3592 (format " to the \"%s\" buffer"
3593 shell-command-default-error-buffer)
3596 (cond ((null exit-status)
3597 (message "(Shell command failed with error)"))
3598 ((equal 0 exit-status)
3599 (message "(Shell command succeeded with %s)"
3601 ((stringp exit-status)
3602 (message "(Shell command killed by signal %s)"
3605 (message "(Shell command failed with code %d and %s)"
3606 exit-status output))))
3607 ;; Don't kill: there might be useful info in the undo-log.
3608 ;; (kill-buffer buffer)
3611 (when (and error-file (file-exists-p error-file))
3612 (if (< 0 (nth 7 (file-attributes error-file)))
3613 (with-current-buffer (get-buffer-create error-buffer)
3614 (let ((pos-from-end (- (point-max) (point))))
3617 ;; Do no formatting while reading error file,
3618 ;; because that can run a shell command, and we
3619 ;; don't want that to cause an infinite recursion.
3620 (format-insert-file error-file nil)
3621 ;; Put point after the inserted errors.
3622 (goto-char (- (point-max) pos-from-end)))
3623 (and display-error-buffer
3624 (display-buffer (current-buffer)))))
3625 (delete-file error-file))
3628 (defun shell-command-to-string (command)
3629 "Execute shell command COMMAND and return its output as a string."
3630 (with-output-to-string
3631 (with-current-buffer
3633 (process-file shell-file-name nil t nil shell-command-switch command))))
3635 (defun process-file (program &optional infile buffer display &rest args)
3636 "Process files synchronously in a separate process.
3637 Similar to `call-process', but may invoke a file handler based on
3638 `default-directory'. The current working directory of the
3639 subprocess is `default-directory'.
3641 File names in INFILE and BUFFER are handled normally, but file
3642 names in ARGS should be relative to `default-directory', as they
3643 are passed to the process verbatim. (This is a difference to
3644 `call-process' which does not support file handlers for INFILE
3647 Some file handlers might not support all variants, for example
3648 they might behave as if DISPLAY was nil, regardless of the actual
3650 (let ((fh (find-file-name-handler default-directory 'process-file))
3653 (if fh (apply fh 'process-file program infile buffer display args)
3654 (when infile (setq lc (file-local-copy infile)))
3655 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3656 (make-temp-file "emacs")))
3658 (apply 'call-process program
3660 (if stderr-file (list (car buffer) stderr-file) buffer)
3662 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3663 (when stderr-file (delete-file stderr-file))
3664 (when lc (delete-file lc)))))
3666 (defvar process-file-side-effects t
3667 "Whether a call of `process-file' changes remote files.
3669 By default, this variable is always set to t, meaning that a
3670 call of `process-file' could potentially change any file on a
3671 remote host. When set to nil, a file handler could optimize
3672 its behavior with respect to remote file attribute caching.
3674 You should only ever change this variable with a let-binding;
3675 never with `setq'.")
3677 (defun start-file-process (name buffer program &rest program-args)
3678 "Start a program in a subprocess. Return the process object for it.
3680 Similar to `start-process', but may invoke a file handler based on
3681 `default-directory'. See Info node `(elisp)Magic File Names'.
3683 This handler ought to run PROGRAM, perhaps on the local host,
3684 perhaps on a remote host that corresponds to `default-directory'.
3685 In the latter case, the local part of `default-directory' becomes
3686 the working directory of the process.
3688 PROGRAM and PROGRAM-ARGS might be file names. They are not
3689 objects of file handler invocation. File handlers might not
3690 support pty association, if PROGRAM is nil."
3691 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3692 (if fh (apply fh 'start-file-process name buffer program program-args)
3693 (apply 'start-process name buffer program program-args))))
3697 (defvar tabulated-list-format)
3698 (defvar tabulated-list-entries)
3699 (defvar tabulated-list-sort-key)
3700 (declare-function tabulated-list-init-header "tabulated-list" ())
3701 (declare-function tabulated-list-print "tabulated-list"
3702 (&optional remember-pos update))
3704 (defvar process-menu-query-only nil)
3706 (defvar process-menu-mode-map
3707 (let ((map (make-sparse-keymap)))
3708 (define-key map [?d] 'process-menu-delete-process)
3711 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3712 "Major mode for listing the processes called by Emacs."
3713 (setq tabulated-list-format [("Process" 15 t)
3718 (make-local-variable 'process-menu-query-only)
3719 (setq tabulated-list-sort-key (cons "Process" nil))
3720 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3721 (tabulated-list-init-header))
3723 (defun process-menu-delete-process ()
3724 "Kill process at point in a `list-processes' buffer."
3726 (delete-process (tabulated-list-get-id))
3729 (defun list-processes--refresh ()
3730 "Recompute the list of processes for the Process List buffer.
3731 Also, delete any process that is exited or signaled."
3732 (setq tabulated-list-entries nil)
3733 (dolist (p (process-list))
3734 (cond ((memq (process-status p) '(exit signal closed))
3736 ((or (not process-menu-query-only)
3737 (process-query-on-exit-flag p))
3738 (let* ((buf (process-buffer p))
3739 (type (process-type p))
3740 (name (process-name p))
3741 (status (symbol-name (process-status p)))
3742 (buf-label (if (buffer-live-p buf)
3743 `(,(buffer-name buf)
3745 help-echo ,(format-message
3750 action process-menu-visit-buffer)
3752 (tty (or (process-tty-name p) "--"))
3754 (if (memq type '(network serial))
3755 (let ((contact (process-contact p t)))
3756 (if (eq type 'network)
3758 (if (plist-get contact :type)
3761 (if (plist-get contact :server)
3762 (format "server on %s"
3764 (plist-get contact :host)
3765 (plist-get contact :local)))
3766 (format "connection to %s"
3767 (plist-get contact :host))))
3768 (format "(serial port %s%s)"
3769 (or (plist-get contact :port) "?")
3770 (let ((speed (plist-get contact :speed)))
3772 (format " at %s b/s" speed)
3774 (mapconcat 'identity (process-command p) " "))))
3775 (push (list p (vector name status buf-label tty cmd))
3776 tabulated-list-entries))))))
3778 (defun process-menu-visit-buffer (button)
3779 (display-buffer (button-get button 'process-buffer)))
3781 (defun list-processes (&optional query-only buffer)
3782 "Display a list of all processes that are Emacs sub-processes.
3783 If optional argument QUERY-ONLY is non-nil, only processes with
3784 the query-on-exit flag set are listed.
3785 Any process listed as exited or signaled is actually eliminated
3786 after the listing is made.
3787 Optional argument BUFFER specifies a buffer to use, instead of
3789 The return value is always nil.
3791 This function lists only processes that were launched by Emacs. To
3792 see other processes running on the system, use `list-system-processes'."
3794 (or (fboundp 'process-list)
3795 (error "Asynchronous subprocesses are not supported on this system"))
3796 (unless (bufferp buffer)
3797 (setq buffer (get-buffer-create "*Process List*")))
3798 (with-current-buffer buffer
3800 (setq process-menu-query-only query-only)
3801 (list-processes--refresh)
3802 (tabulated-list-print))
3803 (display-buffer buffer)
3806 ;;;; Prefix commands
3808 (setq prefix-command--needs-update nil)
3809 (setq prefix-command--last-echo nil)
3811 (defun internal-echo-keystrokes-prefix ()
3812 ;; BEWARE: Called directly from the C code.
3813 (if (not prefix-command--needs-update)
3814 prefix-command--last-echo
3815 (setq prefix-command--last-echo
3817 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3818 (lambda (fun) (push (funcall fun) strs)))
3819 (setq strs (delq nil strs))
3820 (when strs (mapconcat #'identity strs " "))))))
3822 (defvar prefix-command-echo-keystrokes-functions nil
3823 "Abnormal hook which constructs the description of the current prefix state.
3824 Each function is called with no argument, should return a string or nil.")
3826 (defun prefix-command-update ()
3827 "Update state of prefix commands.
3828 Call it whenever you change the \"prefix command state\"."
3829 (setq prefix-command--needs-update t))
3831 (defvar prefix-command-preserve-state-hook nil
3832 "Normal hook run when a command needs to preserve the prefix.")
3834 (defun prefix-command-preserve-state ()
3835 "Pass the current prefix command state to the next command.
3836 Should be called by all prefix commands.
3837 Runs `prefix-command-preserve-state-hook'."
3838 (run-hooks 'prefix-command-preserve-state-hook)
3839 ;; If the current command is a prefix command, we don't want the next (real)
3840 ;; command to have `last-command' set to, say, `universal-argument'.
3841 (setq this-command last-command)
3842 (setq real-this-command real-last-command)
3843 (prefix-command-update))
3845 (defun reset-this-command-lengths ()
3846 (declare (obsolete prefix-command-preserve-state "25.1"))
3849 ;;;;; The main prefix command.
3851 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
3853 (add-hook 'prefix-command-echo-keystrokes-functions
3854 #'universal-argument--description)
3855 (defun universal-argument--description ()
3860 (`(,(and (pred integerp) n))
3862 (while (and (> n 4) (= (mod n 4) 0))
3863 (setq str (concat str " C-u"))
3865 (if (= n 4) str (format " %s" prefix-arg))))
3866 (_ (format " %s" prefix-arg))))))
3868 (add-hook 'prefix-command-preserve-state-hook
3869 #'universal-argument--preserve)
3870 (defun universal-argument--preserve ()
3871 (setq prefix-arg current-prefix-arg))
3873 (defvar universal-argument-map
3874 (let ((map (make-sparse-keymap))
3875 (universal-argument-minus
3876 ;; For backward compatibility, minus with no modifiers is an ordinary
3877 ;; command if digits have already been entered.
3878 `(menu-item "" negative-argument
3879 :filter ,(lambda (cmd)
3880 (if (integerp prefix-arg) nil cmd)))))
3881 (define-key map [switch-frame]
3882 (lambda (e) (interactive "e")
3883 (handle-switch-frame e) (universal-argument--mode)))
3884 (define-key map [?\C-u] 'universal-argument-more)
3885 (define-key map [?-] universal-argument-minus)
3886 (define-key map [?0] 'digit-argument)
3887 (define-key map [?1] 'digit-argument)
3888 (define-key map [?2] 'digit-argument)
3889 (define-key map [?3] 'digit-argument)
3890 (define-key map [?4] 'digit-argument)
3891 (define-key map [?5] 'digit-argument)
3892 (define-key map [?6] 'digit-argument)
3893 (define-key map [?7] 'digit-argument)
3894 (define-key map [?8] 'digit-argument)
3895 (define-key map [?9] 'digit-argument)
3896 (define-key map [kp-0] 'digit-argument)
3897 (define-key map [kp-1] 'digit-argument)
3898 (define-key map [kp-2] 'digit-argument)
3899 (define-key map [kp-3] 'digit-argument)
3900 (define-key map [kp-4] 'digit-argument)
3901 (define-key map [kp-5] 'digit-argument)
3902 (define-key map [kp-6] 'digit-argument)
3903 (define-key map [kp-7] 'digit-argument)
3904 (define-key map [kp-8] 'digit-argument)
3905 (define-key map [kp-9] 'digit-argument)
3906 (define-key map [kp-subtract] universal-argument-minus)
3908 "Keymap used while processing \\[universal-argument].")
3910 (defun universal-argument--mode ()
3911 (prefix-command-update)
3912 (set-transient-map universal-argument-map nil))
3914 (defun universal-argument ()
3915 "Begin a numeric argument for the following command.
3916 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3917 \\[universal-argument] following the digits or minus sign ends the argument.
3918 \\[universal-argument] without digits or minus sign provides 4 as argument.
3919 Repeating \\[universal-argument] without digits or minus sign
3920 multiplies the argument by 4 each time.
3921 For some commands, just \\[universal-argument] by itself serves as a flag
3922 which is different in effect from any particular numeric argument.
3923 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3925 (prefix-command-preserve-state)
3926 (setq prefix-arg (list 4))
3927 (universal-argument--mode))
3929 (defun universal-argument-more (arg)
3930 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3931 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3933 (prefix-command-preserve-state)
3934 (setq prefix-arg (if (consp arg)
3935 (list (* 4 (car arg)))
3939 (when (consp prefix-arg) (universal-argument--mode)))
3941 (defun negative-argument (arg)
3942 "Begin a negative numeric argument for the next command.
3943 \\[universal-argument] following digits or minus sign ends the argument."
3945 (prefix-command-preserve-state)
3946 (setq prefix-arg (cond ((integerp arg) (- arg))
3949 (universal-argument--mode))
3951 (defun digit-argument (arg)
3952 "Part of the numeric argument for the next command.
3953 \\[universal-argument] following digits or minus sign ends the argument."
3955 (prefix-command-preserve-state)
3956 (let* ((char (if (integerp last-command-event)
3958 (get last-command-event 'ascii-character)))
3959 (digit (- (logand char ?\177) ?0)))
3960 (setq prefix-arg (cond ((integerp arg)
3962 (if (< arg 0) (- digit) digit)))
3964 ;; Treat -0 as just -, so that -01 will work.
3965 (if (zerop digit) '- (- digit)))
3968 (universal-argument--mode))
3971 (defvar filter-buffer-substring-functions nil
3972 "This variable is a wrapper hook around `buffer-substring--filter'.")
3973 (make-obsolete-variable 'filter-buffer-substring-functions
3974 'filter-buffer-substring-function "24.4")
3976 (defvar filter-buffer-substring-function #'buffer-substring--filter
3977 "Function to perform the filtering in `filter-buffer-substring'.
3978 The function is called with the same 3 arguments (BEG END DELETE)
3979 that `filter-buffer-substring' received. It should return the
3980 buffer substring between BEG and END, after filtering. If DELETE is
3981 non-nil, it should delete the text between BEG and END from the buffer.")
3983 (defvar buffer-substring-filters nil
3984 "List of filter functions for `buffer-substring--filter'.
3985 Each function must accept a single argument, a string, and return a string.
3986 The buffer substring is passed to the first function in the list,
3987 and the return value of each function is passed to the next.
3988 As a special convention, point is set to the start of the buffer text
3989 being operated on (i.e., the first argument of `buffer-substring--filter')
3990 before these functions are called.")
3991 (make-obsolete-variable 'buffer-substring-filters
3992 'filter-buffer-substring-function "24.1")
3994 (defun filter-buffer-substring (beg end &optional delete)
3995 "Return the buffer substring between BEG and END, after filtering.
3996 If DELETE is non-nil, delete the text between BEG and END from the buffer.
3998 This calls the function that `filter-buffer-substring-function' specifies
3999 \(passing the same three arguments that it received) to do the work,
4000 and returns whatever it does. The default function does no filtering,
4001 unless a hook has been set.
4003 Use `filter-buffer-substring' instead of `buffer-substring',
4004 `buffer-substring-no-properties', or `delete-and-extract-region' when
4005 you want to allow filtering to take place. For example, major or minor
4006 modes can use `filter-buffer-substring-function' to extract characters
4007 that are special to a buffer, and should not be copied into other buffers."
4008 (funcall filter-buffer-substring-function beg end delete))
4010 (defun buffer-substring--filter (beg end &optional delete)
4011 "Default function to use for `filter-buffer-substring-function'.
4012 Its arguments and return value are as specified for `filter-buffer-substring'.
4013 This respects the wrapper hook `filter-buffer-substring-functions',
4014 and the abnormal hook `buffer-substring-filters'.
4015 No filtering is done unless a hook says to."
4016 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
4018 ((or delete buffer-substring-filters)
4021 (let ((string (if delete (delete-and-extract-region beg end)
4022 (buffer-substring beg end))))
4023 (dolist (filter buffer-substring-filters)
4024 (setq string (funcall filter string)))
4027 (buffer-substring beg end)))))
4030 ;;;; Window system cut and paste hooks.
4032 (defvar interprogram-cut-function #'gui-select-text
4033 "Function to call to make a killed region available to other programs.
4034 Most window systems provide a facility for cutting and pasting
4035 text between different programs, such as the clipboard on X and
4036 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4038 This variable holds a function that Emacs calls whenever text is
4039 put in the kill ring, to make the new kill available to other
4040 programs. The function takes one argument, TEXT, which is a
4041 string containing the text which should be made available.")
4043 (defvar interprogram-paste-function #'gui-selection-value
4044 "Function to call to get text cut from other programs.
4045 Most window systems provide a facility for cutting and pasting
4046 text between different programs, such as the clipboard on X and
4047 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4049 This variable holds a function that Emacs calls to obtain text
4050 that other programs have provided for pasting. The function is
4051 called with no arguments. If no other program has provided text
4052 to paste, the function should return nil (in which case the
4053 caller, usually `current-kill', should use the top of the Emacs
4054 kill ring). If another program has provided text to paste, the
4055 function should return that text as a string (in which case the
4056 caller should put this string in the kill ring as the latest
4059 The function may also return a list of strings if the window
4060 system supports multiple selections. The first string will be
4061 used as the pasted text, but the other will be placed in the kill
4062 ring for easy access via `yank-pop'.
4064 Note that the function should return a string only if a program
4065 other than Emacs has provided a string for pasting; if Emacs
4066 provided the most recent string, the function should return nil.
4067 If it is difficult to tell whether Emacs or some other program
4068 provided the current string, it is probably good enough to return
4069 nil if the string is equal (according to `string=') to the last
4070 text Emacs provided.")
4074 ;;;; The kill ring data structure.
4076 (defvar kill-ring nil
4077 "List of killed text sequences.
4078 Since the kill ring is supposed to interact nicely with cut-and-paste
4079 facilities offered by window systems, use of this variable should
4080 interact nicely with `interprogram-cut-function' and
4081 `interprogram-paste-function'. The functions `kill-new',
4082 `kill-append', and `current-kill' are supposed to implement this
4083 interaction; you may want to use them instead of manipulating the kill
4086 (defcustom kill-ring-max 60
4087 "Maximum length of kill ring before oldest elements are thrown away."
4091 (defvar kill-ring-yank-pointer nil
4092 "The tail of the kill ring whose car is the last thing yanked.")
4094 (defcustom save-interprogram-paste-before-kill nil
4095 "Save clipboard strings into kill ring before replacing them.
4096 When one selects something in another program to paste it into Emacs,
4097 but kills something in Emacs before actually pasting it,
4098 this selection is gone unless this variable is non-nil,
4099 in which case the other program's selection is saved in the `kill-ring'
4100 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4105 (defcustom kill-do-not-save-duplicates nil
4106 "Do not add a new string to `kill-ring' if it duplicates the last one.
4107 The comparison is done using `equal-including-properties'."
4112 (defun kill-new (string &optional replace)
4113 "Make STRING the latest kill in the kill ring.
4114 Set `kill-ring-yank-pointer' to point to it.
4115 If `interprogram-cut-function' is non-nil, apply it to STRING.
4116 Optional second argument REPLACE non-nil means that STRING will replace
4117 the front of the kill ring, rather than being added to the list.
4119 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4120 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4123 When the yank handler has a non-nil PARAM element, the original STRING
4124 argument is not used by `insert-for-yank'. However, since Lisp code
4125 may access and use elements from the kill ring directly, the STRING
4126 argument should still be a \"useful\" string for such uses."
4127 (unless (and kill-do-not-save-duplicates
4128 ;; Due to text properties such as 'yank-handler that
4129 ;; can alter the contents to yank, comparison using
4130 ;; `equal' is unsafe.
4131 (equal-including-properties string (car kill-ring)))
4132 (if (fboundp 'menu-bar-update-yank-menu)
4133 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4134 (when save-interprogram-paste-before-kill
4135 (let ((interprogram-paste (and interprogram-paste-function
4136 (funcall interprogram-paste-function))))
4137 (when interprogram-paste
4138 (dolist (s (if (listp interprogram-paste)
4139 (nreverse interprogram-paste)
4140 (list interprogram-paste)))
4141 (unless (and kill-do-not-save-duplicates
4142 (equal-including-properties s (car kill-ring)))
4143 (push s kill-ring))))))
4144 (unless (and kill-do-not-save-duplicates
4145 (equal-including-properties string (car kill-ring)))
4146 (if (and replace kill-ring)
4147 (setcar kill-ring string)
4148 (push string kill-ring)
4149 (if (> (length kill-ring) kill-ring-max)
4150 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4151 (setq kill-ring-yank-pointer kill-ring)
4152 (if interprogram-cut-function
4153 (funcall interprogram-cut-function string)))
4155 ;; It has been argued that this should work similar to `self-insert-command'
4156 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4157 (defcustom kill-append-merge-undo nil
4158 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4163 (defun kill-append (string before-p)
4164 "Append STRING to the end of the latest kill in the kill ring.
4165 If BEFORE-P is non-nil, prepend STRING to the kill.
4166 Also removes the last undo boundary in the current buffer,
4167 depending on `kill-append-merge-undo'.
4168 If `interprogram-cut-function' is set, pass the resulting kill to it."
4169 (let* ((cur (car kill-ring)))
4170 (kill-new (if before-p (concat string cur) (concat cur string))
4171 (or (= (length cur) 0)
4172 (equal nil (get-text-property 0 'yank-handler cur))))
4173 (when (and kill-append-merge-undo (not buffer-read-only))
4174 (let ((prev buffer-undo-list)
4175 (next (cdr buffer-undo-list)))
4176 ;; find the next undo boundary
4180 ;; remove this undo boundary
4182 (setcdr prev (cdr next)))))))
4184 (defcustom yank-pop-change-selection nil
4185 "Whether rotating the kill ring changes the window system selection.
4186 If non-nil, whenever the kill ring is rotated (usually via the
4187 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4188 to copy the new kill to the window system selection."
4193 (defun current-kill (n &optional do-not-move)
4194 "Rotate the yanking point by N places, and then return that kill.
4195 If N is zero and `interprogram-paste-function' is set to a
4196 function that returns a string or a list of strings, and if that
4197 function doesn't return nil, then that string (or list) is added
4198 to the front of the kill ring and the string (or first string in
4199 the list) is returned as the latest kill.
4201 If N is not zero, and if `yank-pop-change-selection' is
4202 non-nil, use `interprogram-cut-function' to transfer the
4203 kill at the new yank point into the window system selection.
4205 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4206 move the yanking point; just return the Nth kill forward."
4208 (let ((interprogram-paste (and (= n 0)
4209 interprogram-paste-function
4210 (funcall interprogram-paste-function))))
4211 (if interprogram-paste
4213 ;; Disable the interprogram cut function when we add the new
4214 ;; text to the kill ring, so Emacs doesn't try to own the
4215 ;; selection, with identical text.
4216 (let ((interprogram-cut-function nil))
4217 (if (listp interprogram-paste)
4218 (mapc 'kill-new (nreverse interprogram-paste))
4219 (kill-new interprogram-paste)))
4221 (or kill-ring (error "Kill ring is empty"))
4222 (let ((ARGth-kill-element
4223 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4227 (setq kill-ring-yank-pointer ARGth-kill-element)
4228 (when (and yank-pop-change-selection
4230 interprogram-cut-function)
4231 (funcall interprogram-cut-function (car ARGth-kill-element))))
4232 (car ARGth-kill-element)))))
4236 ;;;; Commands for manipulating the kill ring.
4238 (defcustom kill-read-only-ok nil
4239 "Non-nil means don't signal an error for killing read-only text."
4243 (defun kill-region (beg end &optional region)
4244 "Kill (\"cut\") text between point and mark.
4245 This deletes the text from the buffer and saves it in the kill ring.
4246 The command \\[yank] can retrieve it from there.
4247 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4249 If you want to append the killed region to the last killed text,
4250 use \\[append-next-kill] before \\[kill-region].
4252 If the buffer is read-only, Emacs will beep and refrain from deleting
4253 the text, but put the text in the kill ring anyway. This means that
4254 you can use the killing commands to copy text from a read-only buffer.
4256 Lisp programs should use this function for killing text.
4257 (To delete text, use `delete-region'.)
4258 Supply two arguments, character positions indicating the stretch of text
4260 Any command that calls this function is a \"kill command\".
4261 If the previous command was also a kill command,
4262 the text killed this time appends to the text killed last time
4263 to make one entry in the kill ring.
4265 The optional argument REGION if non-nil, indicates that we're not just killing
4266 some text between BEG and END, but we're killing the region."
4267 ;; Pass mark first, then point, because the order matters when
4268 ;; calling `kill-append'.
4269 (interactive (list (mark) (point) 'region))
4270 (unless (and beg end)
4271 (user-error "The mark is not set now, so there is no region"))
4273 (let ((string (if region
4274 (funcall region-extract-function 'delete)
4275 (filter-buffer-substring beg end 'delete))))
4276 (when string ;STRING is nil if BEG = END
4277 ;; Add that string to the kill ring, one way or another.
4278 (if (eq last-command 'kill-region)
4279 (kill-append string (< end beg))
4281 (when (or string (eq last-command 'kill-region))
4282 (setq this-command 'kill-region))
4283 (setq deactivate-mark t)
4285 ((buffer-read-only text-read-only)
4286 ;; The code above failed because the buffer, or some of the characters
4287 ;; in the region, are read-only.
4288 ;; We should beep, in case the user just isn't aware of this.
4289 ;; However, there's no harm in putting
4290 ;; the region's text in the kill ring, anyway.
4291 (copy-region-as-kill beg end region)
4292 ;; Set this-command now, so it will be set even if we get an error.
4293 (setq this-command 'kill-region)
4294 ;; This should barf, if appropriate, and give us the correct error.
4295 (if kill-read-only-ok
4296 (progn (message "Read only text copied to kill ring") nil)
4297 ;; Signal an error if the buffer is read-only.
4298 (barf-if-buffer-read-only)
4299 ;; If the buffer isn't read-only, the text is.
4300 (signal 'text-read-only (list (current-buffer)))))))
4302 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4303 ;; to get two copies of the text when the user accidentally types M-w and
4304 ;; then corrects it with the intended C-w.
4305 (defun copy-region-as-kill (beg end &optional region)
4306 "Save the region as if killed, but don't kill it.
4307 In Transient Mark mode, deactivate the mark.
4308 If `interprogram-cut-function' is non-nil, also save the text for a window
4309 system cut and paste.
4311 The optional argument REGION if non-nil, indicates that we're not just copying
4312 some text between BEG and END, but we're copying the region.
4314 This command's old key binding has been given to `kill-ring-save'."
4315 ;; Pass mark first, then point, because the order matters when
4316 ;; calling `kill-append'.
4317 (interactive (list (mark) (point)
4318 (prefix-numeric-value current-prefix-arg)))
4319 (let ((str (if region
4320 (funcall region-extract-function nil)
4321 (filter-buffer-substring beg end))))
4322 (if (eq last-command 'kill-region)
4323 (kill-append str (< end beg))
4325 (setq deactivate-mark t)
4328 (defun kill-ring-save (beg end &optional region)
4329 "Save the region as if killed, but don't kill it.
4330 In Transient Mark mode, deactivate the mark.
4331 If `interprogram-cut-function' is non-nil, also save the text for a window
4332 system cut and paste.
4334 If you want to append the killed line to the last killed text,
4335 use \\[append-next-kill] before \\[kill-ring-save].
4337 The optional argument REGION if non-nil, indicates that we're not just copying
4338 some text between BEG and END, but we're copying the region.
4340 This command is similar to `copy-region-as-kill', except that it gives
4341 visual feedback indicating the extent of the region being copied."
4342 ;; Pass mark first, then point, because the order matters when
4343 ;; calling `kill-append'.
4344 (interactive (list (mark) (point)
4345 (prefix-numeric-value current-prefix-arg)))
4346 (copy-region-as-kill beg end region)
4347 ;; This use of called-interactively-p is correct because the code it
4348 ;; controls just gives the user visual feedback.
4349 (if (called-interactively-p 'interactive)
4350 (indicate-copied-region)))
4352 (defun indicate-copied-region (&optional message-len)
4353 "Indicate that the region text has been copied interactively.
4354 If the mark is visible in the selected window, blink the cursor
4355 between point and mark if there is currently no active region
4358 If the mark lies outside the selected window, display an
4359 informative message containing a sample of the copied text. The
4360 optional argument MESSAGE-LEN, if non-nil, specifies the length
4361 of this sample text; it defaults to 40."
4362 (let ((mark (mark t))
4364 ;; Inhibit quitting so we can make a quit here
4365 ;; look like a C-g typed as a command.
4367 (if (pos-visible-in-window-p mark (selected-window))
4368 ;; Swap point-and-mark quickly so as to show the region that
4369 ;; was selected. Don't do it if the region is highlighted.
4370 (unless (and (region-active-p)
4371 (face-background 'region))
4372 ;; Swap point and mark.
4373 (set-marker (mark-marker) (point) (current-buffer))
4375 (sit-for blink-matching-delay)
4377 (set-marker (mark-marker) mark (current-buffer))
4379 ;; If user quit, deactivate the mark
4380 ;; as C-g would as a command.
4381 (and quit-flag (region-active-p)
4383 (let ((len (min (abs (- mark point))
4384 (or message-len 40))))
4386 ;; Don't say "killed"; that is misleading.
4387 (message "Saved text until \"%s\""
4388 (buffer-substring-no-properties (- mark len) mark))
4389 (message "Saved text from \"%s\""
4390 (buffer-substring-no-properties mark (+ mark len))))))))
4392 (defun append-next-kill (&optional interactive)
4393 "Cause following command, if it kills, to add to previous kill.
4394 If the next command kills forward from point, the kill is
4395 appended to the previous killed text. If the command kills
4396 backward, the kill is prepended. Kill commands that act on the
4397 region, such as `kill-region', are regarded as killing forward if
4398 point is after mark, and killing backward if point is before
4401 If the next command is not a kill command, `append-next-kill' has
4404 The argument is used for internal purposes; do not supply one."
4406 ;; We don't use (interactive-p), since that breaks kbd macros.
4409 (setq this-command 'kill-region)
4410 (message "If the next command is a kill, it will append"))
4411 (setq last-command 'kill-region)))
4413 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4414 "Character set that matches bidirectional formatting control characters.")
4416 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4417 "Character set that matches any character except bidirectional controls.")
4419 (defun squeeze-bidi-context-1 (from to category replacement)
4420 "A subroutine of `squeeze-bidi-context'.
4421 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4422 (let ((pt (copy-marker from))
4423 (limit (copy-marker to))
4432 ;; L and R categories include embedding and
4433 ;; override controls, but we don't want to
4434 ;; replace them, because that might change
4435 ;; the visual order. Likewise with PDF and
4436 ;; isolate controls.
4437 (+ pt (skip-chars-forward
4438 bidi-directional-non-controls-chars
4440 ;; Replace any run of non-RTL characters by a single LRM.
4441 (if (null (re-search-forward category lim1 t))
4442 ;; No more characters of CATEGORY, we are done.
4444 (replace-match replacement nil t)
4445 (move-marker pt (point)))
4447 ;; Skip directional controls, if any.
4449 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4451 (defun squeeze-bidi-context (from to)
4452 "Replace characters between FROM and TO while keeping bidi context.
4454 This function replaces the region of text with as few characters
4455 as possible, while preserving the effect that region will have on
4456 bidirectional display before and after the region."
4457 (let ((start (set-marker (make-marker)
4458 (if (> from 0) from (+ (point-max) from))))
4459 (end (set-marker (make-marker) to))
4460 ;; This is for when they copy text with read-only text
4462 (inhibit-read-only t))
4463 (if (null (marker-position end))
4464 (setq end (point-max-marker)))
4465 ;; Replace each run of non-RTL characters with a single LRM.
4466 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4467 ;; Replace each run of non-LTR characters with a single RLM. Note
4468 ;; that the \cR category includes both the Arabic Letter (AL) and
4469 ;; R characters; here we ignore the distinction between them,
4470 ;; because that distinction only affects Arabic Number (AN)
4471 ;; characters, which are weak and don't affect the reordering.
4472 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4474 (defun line-substring-with-bidi-context (start end &optional no-properties)
4475 "Return buffer text between START and END with its bidi context.
4477 START and END are assumed to belong to the same physical line
4478 of buffer text. This function prepends and appends to the text
4479 between START and END bidi control characters that preserve the
4480 visual order of that text when it is inserted at some other place."
4481 (if (or (< start (point-min))
4482 (> end (point-max)))
4483 (signal 'args-out-of-range (list (current-buffer) start end)))
4484 (let ((buf (current-buffer))
4485 substr para-dir from to)
4488 (setq para-dir (current-bidi-paragraph-direction))
4489 (setq from (line-beginning-position)
4490 to (line-end-position))
4492 ;; If we don't have any mixed directional characters in the
4493 ;; entire line, we can just copy the substring without adding
4495 (if (or (looking-at-p "\\CR*$")
4496 (looking-at-p "\\CL*$"))
4497 (setq substr (if no-properties
4498 (buffer-substring-no-properties start end)
4499 (buffer-substring start end)))
4503 (insert-buffer-substring-no-properties buf from to)
4504 (insert-buffer-substring buf from to))
4505 (squeeze-bidi-context 1 (1+ (- start from)))
4506 (squeeze-bidi-context (- end to) nil)
4507 (buffer-substring 1 (point-max)))))
4509 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4510 ;; (1) force the string to have the same base embedding
4511 ;; direction as the paragraph direction at the source, no matter
4512 ;; what is the paragraph direction at destination; and (2) avoid
4513 ;; affecting the visual order of the surrounding text at
4514 ;; destination if there are characters of different
4515 ;; directionality there.
4516 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4519 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4520 "Return portion of current buffer between START and END with bidi context.
4522 This function works similar to `buffer-substring', but it prepends and
4523 appends to the text bidi directional control characters necessary to
4524 preserve the visual appearance of the text if it is inserted at another
4525 place. This is useful when the buffer substring includes bidirectional
4526 text and control characters that cause non-trivial reordering on display.
4527 If copied verbatim, such text can have a very different visual appearance,
4528 and can also change the visual appearance of the surrounding text at the
4529 destination of the copy.
4531 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4532 the text properties."
4533 (let (line-end substr)
4534 (if (or (< start (point-min))
4535 (> end (point-max)))
4536 (signal 'args-out-of-range (list (current-buffer) start end)))
4539 (setq line-end (min end (line-end-position)))
4540 (while (< start end)
4544 (line-substring-with-bidi-context start line-end
4547 (setq start (point))
4548 (setq line-end (min end (line-end-position))))
4553 (defcustom yank-handled-properties
4554 '((font-lock-face . yank-handle-font-lock-face-property)
4555 (category . yank-handle-category-property))
4556 "List of special text property handling conditions for yanking.
4557 Each element should have the form (PROP . FUN), where PROP is a
4558 property symbol and FUN is a function. When the `yank' command
4559 inserts text into the buffer, it scans the inserted text for
4560 stretches of text that have `eq' values of the text property
4561 PROP; for each such stretch of text, FUN is called with three
4562 arguments: the property's value in that text, and the start and
4563 end positions of the text.
4565 This is done prior to removing the properties specified by
4566 `yank-excluded-properties'."
4568 :type '(repeat (cons (symbol :tag "property symbol")
4572 ;; This is actually used in subr.el but defcustom does not work there.
4573 (defcustom yank-excluded-properties
4574 '(category field follow-link fontified font-lock-face help-echo
4575 intangible invisible keymap local-map mouse-face read-only
4577 "Text properties to discard when yanking.
4578 The value should be a list of text properties to discard or t,
4579 which means to discard all text properties.
4581 See also `yank-handled-properties'."
4582 :type '(choice (const :tag "All" t) (repeat symbol))
4586 (defvar yank-window-start nil)
4587 (defvar yank-undo-function nil
4588 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4589 Function is called with two parameters, START and END corresponding to
4590 the value of the mark and point; it is guaranteed that START <= END.
4591 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4593 (defun yank-pop (&optional arg)
4594 "Replace just-yanked stretch of killed text with a different stretch.
4595 This command is allowed only immediately after a `yank' or a `yank-pop'.
4596 At such a time, the region contains a stretch of reinserted
4597 previously-killed text. `yank-pop' deletes that text and inserts in its
4598 place a different stretch of killed text.
4600 With no argument, the previous kill is inserted.
4601 With argument N, insert the Nth previous kill.
4602 If N is negative, this is a more recent kill.
4604 The sequence of kills wraps around, so that after the oldest one
4605 comes the newest one.
4607 When this command inserts killed text into the buffer, it honors
4608 `yank-excluded-properties' and `yank-handler' as described in the
4609 doc string for `insert-for-yank-1', which see."
4611 (if (not (eq last-command 'yank))
4612 (user-error "Previous command was not a yank"))
4613 (setq this-command 'yank)
4614 (unless arg (setq arg 1))
4615 (let ((inhibit-read-only t)
4616 (before (< (point) (mark t))))
4618 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4619 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4620 (setq yank-undo-function nil)
4621 (set-marker (mark-marker) (point) (current-buffer))
4622 (insert-for-yank (current-kill arg))
4623 ;; Set the window start back where it was in the yank command,
4625 (set-window-start (selected-window) yank-window-start t)
4627 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4628 ;; It is cleaner to avoid activation, even though the command
4629 ;; loop would deactivate the mark because we inserted text.
4630 (goto-char (prog1 (mark t)
4631 (set-marker (mark-marker) (point) (current-buffer))))))
4634 (defun yank (&optional arg)
4635 "Reinsert (\"paste\") the last stretch of killed text.
4636 More precisely, reinsert the most recent kill, which is the
4637 stretch of killed text most recently killed OR yanked. Put point
4638 at the end, and set mark at the beginning without activating it.
4639 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4640 With argument N, reinsert the Nth most recent kill.
4642 When this command inserts text into the buffer, it honors the
4643 `yank-handled-properties' and `yank-excluded-properties'
4644 variables, and the `yank-handler' text property. See
4645 `insert-for-yank-1' for details.
4647 See also the command `yank-pop' (\\[yank-pop])."
4649 (setq yank-window-start (window-start))
4650 ;; If we don't get all the way thru, make last-command indicate that
4651 ;; for the following command.
4652 (setq this-command t)
4654 (insert-for-yank (current-kill (cond
4659 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4660 ;; It is cleaner to avoid activation, even though the command
4661 ;; loop would deactivate the mark because we inserted text.
4662 (goto-char (prog1 (mark t)
4663 (set-marker (mark-marker) (point) (current-buffer)))))
4664 ;; If we do get all the way thru, make this-command indicate that.
4665 (if (eq this-command t)
4666 (setq this-command 'yank))
4669 (defun rotate-yank-pointer (arg)
4670 "Rotate the yanking point in the kill ring.
4671 With ARG, rotate that many kills forward (or backward, if negative)."
4675 ;; Some kill commands.
4677 ;; Internal subroutine of delete-char
4678 (defun kill-forward-chars (arg)
4679 (if (listp arg) (setq arg (car arg)))
4680 (if (eq arg '-) (setq arg -1))
4681 (kill-region (point) (+ (point) arg)))
4683 ;; Internal subroutine of backward-delete-char
4684 (defun kill-backward-chars (arg)
4685 (if (listp arg) (setq arg (car arg)))
4686 (if (eq arg '-) (setq arg -1))
4687 (kill-region (point) (- (point) arg)))
4689 (defcustom backward-delete-char-untabify-method 'untabify
4690 "The method for untabifying when deleting backward.
4691 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4692 `hungry' -- delete all whitespace, both tabs and spaces;
4693 `all' -- delete all whitespace, including tabs, spaces and newlines;
4694 nil -- just delete one character."
4695 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4699 (defun backward-delete-char-untabify (arg &optional killp)
4700 "Delete characters backward, changing tabs into spaces.
4701 The exact behavior depends on `backward-delete-char-untabify-method'.
4702 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4703 Interactively, ARG is the prefix arg (default 1)
4704 and KILLP is t if a prefix arg was specified."
4705 (interactive "*p\nP")
4706 (when (eq backward-delete-char-untabify-method 'untabify)
4709 (while (and (> count 0) (not (bobp)))
4710 (if (= (preceding-char) ?\t)
4711 (let ((col (current-column)))
4713 (setq col (- col (current-column)))
4714 (insert-char ?\s col)
4717 (setq count (1- count))))))
4718 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4719 ((eq backward-delete-char-untabify-method 'all)
4722 (let* ((oldpt (point))
4723 (wh (- oldpt (save-excursion
4724 (skip-chars-backward skip)
4725 (constrain-to-field nil oldpt)))))
4726 (+ arg (if (zerop wh) 0 (1- wh))))
4728 ;; Avoid warning about delete-backward-char
4729 (with-no-warnings (delete-backward-char n killp))))
4731 (defun zap-to-char (arg char)
4732 "Kill up to and including ARGth occurrence of CHAR.
4733 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4734 Goes backward if ARG is negative; error if CHAR not found."
4735 (interactive (list (prefix-numeric-value current-prefix-arg)
4736 (read-char "Zap to char: " t)))
4737 ;; Avoid "obsolete" warnings for translation-table-for-input.
4739 (if (char-table-p translation-table-for-input)
4740 (setq char (or (aref translation-table-for-input char) char))))
4741 (kill-region (point) (progn
4742 (search-forward (char-to-string char) nil nil arg)
4745 ;; kill-line and its subroutines.
4747 (defcustom kill-whole-line nil
4748 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4752 (defun kill-line (&optional arg)
4753 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4754 With prefix argument ARG, kill that many lines from point.
4755 Negative arguments kill lines backward.
4756 With zero argument, kills the text before point on the current line.
4758 When calling from a program, nil means \"no arg\",
4759 a number counts as a prefix arg.
4761 To kill a whole line, when point is not at the beginning, type \
4762 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4764 If `show-trailing-whitespace' is non-nil, this command will just
4765 kill the rest of the current line, even if there are only
4768 If option `kill-whole-line' is non-nil, then this command kills the whole line
4769 including its terminating newline, when used at the beginning of a line
4770 with no argument. As a consequence, you can always kill a whole line
4771 by typing \\[move-beginning-of-line] \\[kill-line].
4773 If you want to append the killed line to the last killed text,
4774 use \\[append-next-kill] before \\[kill-line].
4776 If the buffer is read-only, Emacs will beep and refrain from deleting
4777 the line, but put the line in the kill ring anyway. This means that
4778 you can use this command to copy text from a read-only buffer.
4779 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4782 (kill-region (point)
4783 ;; It is better to move point to the other end of the kill
4784 ;; before killing. That way, in a read-only buffer, point
4785 ;; moves across the text that is copied to the kill ring.
4786 ;; The choice has no effect on undo now that undo records
4787 ;; the value of point from before the command was run.
4790 (forward-visible-line (prefix-numeric-value arg))
4792 (signal 'end-of-buffer nil))
4795 (end-of-visible-line) (point))))
4796 (if (or (save-excursion
4797 ;; If trailing whitespace is visible,
4798 ;; don't treat it as nothing.
4799 (unless show-trailing-whitespace
4800 (skip-chars-forward " \t" end))
4802 (and kill-whole-line (bolp)))
4803 (forward-visible-line 1)
4807 (defun kill-whole-line (&optional arg)
4809 With prefix ARG, kill that many lines starting from the current line.
4810 If ARG is negative, kill backward. Also kill the preceding newline.
4811 \(This is meant to make \\[repeat] work well with negative arguments.)
4812 If ARG is zero, kill current line but exclude the trailing newline."
4814 (or arg (setq arg 1))
4815 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4816 (signal 'end-of-buffer nil))
4817 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4818 (signal 'beginning-of-buffer nil))
4819 (unless (eq last-command 'kill-region)
4821 (setq last-command 'kill-region))
4823 ;; We need to kill in two steps, because the previous command
4824 ;; could have been a kill command, in which case the text
4825 ;; before point needs to be prepended to the current kill
4826 ;; ring entry and the text after point appended. Also, we
4827 ;; need to use save-excursion to avoid copying the same text
4828 ;; twice to the kill ring in read-only buffers.
4830 (kill-region (point) (progn (forward-visible-line 0) (point))))
4831 (kill-region (point) (progn (end-of-visible-line) (point))))
4834 (kill-region (point) (progn (end-of-visible-line) (point))))
4835 (kill-region (point)
4836 (progn (forward-visible-line (1+ arg))
4837 (unless (bobp) (backward-char))
4841 (kill-region (point) (progn (forward-visible-line 0) (point))))
4842 (kill-region (point)
4843 (progn (forward-visible-line arg) (point))))))
4845 (defun forward-visible-line (arg)
4846 "Move forward by ARG lines, ignoring currently invisible newlines only.
4847 If ARG is negative, move backward -ARG lines.
4848 If ARG is zero, move to the beginning of the current line."
4853 (or (zerop (forward-line 1))
4854 (signal 'end-of-buffer nil))
4855 ;; If the newline we just skipped is invisible,
4858 (get-char-property (1- (point)) 'invisible)))
4859 (if (if (eq buffer-invisibility-spec t)
4861 (or (memq prop buffer-invisibility-spec)
4862 (assq prop buffer-invisibility-spec)))
4863 (setq arg (1+ arg))))
4864 (setq arg (1- arg)))
4865 ;; If invisible text follows, and it is a number of complete lines,
4867 (let ((opoint (point)))
4868 (while (and (not (eobp))
4870 (get-char-property (point) 'invisible)))
4871 (if (eq buffer-invisibility-spec t)
4873 (or (memq prop buffer-invisibility-spec)
4874 (assq prop buffer-invisibility-spec)))))
4876 (if (get-text-property (point) 'invisible)
4877 (or (next-single-property-change (point) 'invisible)
4879 (next-overlay-change (point)))))
4881 (goto-char opoint))))
4883 (while (or first (<= arg 0))
4886 (or (zerop (forward-line -1))
4887 (signal 'beginning-of-buffer nil)))
4888 ;; If the newline we just moved to is invisible,
4892 (get-char-property (1- (point)) 'invisible)))
4893 (unless (if (eq buffer-invisibility-spec t)
4895 (or (memq prop buffer-invisibility-spec)
4896 (assq prop buffer-invisibility-spec)))
4897 (setq arg (1+ arg)))))
4899 ;; If invisible text follows, and it is a number of complete lines,
4901 (let ((opoint (point)))
4902 (while (and (not (bobp))
4904 (get-char-property (1- (point)) 'invisible)))
4905 (if (eq buffer-invisibility-spec t)
4907 (or (memq prop buffer-invisibility-spec)
4908 (assq prop buffer-invisibility-spec)))))
4910 (if (get-text-property (1- (point)) 'invisible)
4911 (or (previous-single-property-change (point) 'invisible)
4913 (previous-overlay-change (point)))))
4915 (goto-char opoint)))))
4916 ((beginning-of-buffer end-of-buffer)
4919 (defun end-of-visible-line ()
4920 "Move to end of current visible line."
4922 ;; If the following character is currently invisible,
4923 ;; skip all characters with that same `invisible' property value,
4924 ;; then find the next newline.
4925 (while (and (not (eobp))
4927 (skip-chars-forward "^\n")
4929 (get-char-property (point) 'invisible)))
4930 (if (eq buffer-invisibility-spec t)
4932 (or (memq prop buffer-invisibility-spec)
4933 (assq prop buffer-invisibility-spec))))))
4934 (skip-chars-forward "^\n")
4935 (if (get-text-property (point) 'invisible)
4936 (goto-char (or (next-single-property-change (point) 'invisible)
4938 (goto-char (next-overlay-change (point))))
4941 (defun insert-buffer (buffer)
4942 "Insert after point the contents of BUFFER.
4943 Puts mark after the inserted text.
4944 BUFFER may be a buffer or a buffer name."
4945 (declare (interactive-only insert-buffer-substring))
4949 (barf-if-buffer-read-only)
4950 (read-buffer "Insert buffer: "
4951 (if (eq (selected-window) (next-window))
4952 (other-buffer (current-buffer))
4953 (window-buffer (next-window)))
4957 (insert-buffer-substring (get-buffer buffer))
4961 (defun append-to-buffer (buffer start end)
4962 "Append to specified buffer the text of the region.
4963 It is inserted into that buffer before its point.
4965 When calling from a program, give three arguments:
4966 BUFFER (or buffer name), START and END.
4967 START and END specify the portion of the current buffer to be copied."
4969 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
4970 (region-beginning) (region-end)))
4971 (let* ((oldbuf (current-buffer))
4972 (append-to (get-buffer-create buffer))
4973 (windows (get-buffer-window-list append-to t t))
4976 (with-current-buffer append-to
4977 (setq point (point))
4978 (barf-if-buffer-read-only)
4979 (insert-buffer-substring oldbuf start end)
4980 (dolist (window windows)
4981 (when (= (window-point window) point)
4982 (set-window-point window (point))))))))
4984 (defun prepend-to-buffer (buffer start end)
4985 "Prepend to specified buffer the text of the region.
4986 It is inserted into that buffer after its point.
4988 When calling from a program, give three arguments:
4989 BUFFER (or buffer name), START and END.
4990 START and END specify the portion of the current buffer to be copied."
4991 (interactive "BPrepend to buffer: \nr")
4992 (let ((oldbuf (current-buffer)))
4993 (with-current-buffer (get-buffer-create buffer)
4994 (barf-if-buffer-read-only)
4996 (insert-buffer-substring oldbuf start end)))))
4998 (defun copy-to-buffer (buffer start end)
4999 "Copy to specified buffer the text of the region.
5000 It is inserted into that buffer, replacing existing text there.
5002 When calling from a program, give three arguments:
5003 BUFFER (or buffer name), START and END.
5004 START and END specify the portion of the current buffer to be copied."
5005 (interactive "BCopy to buffer: \nr")
5006 (let ((oldbuf (current-buffer)))
5007 (with-current-buffer (get-buffer-create buffer)
5008 (barf-if-buffer-read-only)
5011 (insert-buffer-substring oldbuf start end)))))
5013 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5015 (defvar activate-mark-hook nil
5016 "Hook run when the mark becomes active.
5017 It is also run at the end of a command, if the mark is active and
5018 it is possible that the region may have changed.")
5020 (defvar deactivate-mark-hook nil
5021 "Hook run when the mark becomes inactive.")
5023 (defun mark (&optional force)
5024 "Return this buffer's mark value as integer, or nil if never set.
5026 In Transient Mark mode, this function signals an error if
5027 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5028 or the argument FORCE is non-nil, it disregards whether the mark
5029 is active, and returns an integer or nil in the usual way.
5031 If you are using this in an editing command, you are most likely making
5032 a mistake; see the documentation of `set-mark'."
5033 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5034 (marker-position (mark-marker))
5035 (signal 'mark-inactive nil)))
5037 ;; Behind display-selections-p.
5039 (defun deactivate-mark (&optional force)
5040 "Deactivate the mark.
5041 If Transient Mark mode is disabled, this function normally does
5042 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5044 Deactivating the mark sets `mark-active' to nil, updates the
5045 primary selection according to `select-active-regions', and runs
5046 `deactivate-mark-hook'.
5048 If Transient Mark mode was temporarily enabled, reset the value
5049 of the variable `transient-mark-mode'; if this causes Transient
5050 Mark mode to be disabled, don't change `mark-active' to nil or
5051 run `deactivate-mark-hook'."
5052 (when (or (region-active-p) force)
5053 (when (and (if (eq select-active-regions 'only)
5054 (eq (car-safe transient-mark-mode) 'only)
5055 select-active-regions)
5057 (display-selections-p))
5058 ;; The var `saved-region-selection', if non-nil, is the text in
5059 ;; the region prior to the last command modifying the buffer.
5060 ;; Set the selection to that, or to the current region.
5061 (cond (saved-region-selection
5062 (if (gui-backend-selection-owner-p 'PRIMARY)
5063 (gui-set-selection 'PRIMARY saved-region-selection))
5064 (setq saved-region-selection nil))
5065 ;; If another program has acquired the selection, region
5066 ;; deactivation should not clobber it (Bug#11772).
5067 ((and (/= (region-beginning) (region-end))
5068 (or (gui-backend-selection-owner-p 'PRIMARY)
5069 (null (gui-backend-selection-exists-p 'PRIMARY))))
5070 (gui-set-selection 'PRIMARY
5071 (funcall region-extract-function nil)))))
5072 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5074 ((eq (car-safe transient-mark-mode) 'only)
5075 (setq transient-mark-mode (cdr transient-mark-mode))
5076 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5077 (kill-local-variable 'transient-mark-mode)))
5078 ((eq transient-mark-mode 'lambda)
5079 (kill-local-variable 'transient-mark-mode)))
5080 (setq mark-active nil)
5081 (run-hooks 'deactivate-mark-hook)
5082 (redisplay--update-region-highlight (selected-window))))
5084 (defun activate-mark (&optional no-tmm)
5086 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5088 (unless (region-active-p)
5089 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5090 (setq mark-active t)
5091 (unless (or transient-mark-mode no-tmm)
5092 (setq-local transient-mark-mode 'lambda))
5093 (run-hooks 'activate-mark-hook))))
5095 (defun set-mark (pos)
5096 "Set this buffer's mark to POS. Don't use this function!
5097 That is to say, don't use this function unless you want
5098 the user to see that the mark has moved, and you want the previous
5099 mark position to be lost.
5101 Normally, when a new mark is set, the old one should go on the stack.
5102 This is why most applications should use `push-mark', not `set-mark'.
5104 Novice Emacs Lisp programmers often try to use the mark for the wrong
5105 purposes. The mark saves a location for the user's convenience.
5106 Most editing commands should not alter the mark.
5107 To remember a location for internal use in the Lisp program,
5108 store it in a Lisp variable. Example:
5110 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5113 (set-marker (mark-marker) pos (current-buffer))
5114 (activate-mark 'no-tmm))
5115 ;; Normally we never clear mark-active except in Transient Mark mode.
5116 ;; But when we actually clear out the mark value too, we must
5117 ;; clear mark-active in any mode.
5119 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5120 ;; it should never be nil if the mark is nil.
5121 (setq mark-active nil)
5122 (set-marker (mark-marker) nil)))
5124 (defun save-mark-and-excursion--save ()
5126 (let ((mark (mark-marker)))
5127 (and (marker-position mark) (copy-marker mark)))
5130 (defun save-mark-and-excursion--restore (saved-mark-info)
5131 (let ((saved-mark (car saved-mark-info))
5132 (omark (marker-position (mark-marker)))
5134 (saved-mark-active (cdr saved-mark-info)))
5136 (if (null saved-mark)
5137 (set-marker (mark-marker) nil)
5138 (setf nmark (marker-position saved-mark))
5139 (set-marker (mark-marker) nmark)
5140 (set-marker saved-mark nil))
5142 (let ((cur-mark-active mark-active))
5143 (setq mark-active saved-mark-active)
5144 ;; If mark is active now, and either was not active or was at a
5145 ;; different place, run the activate hook.
5146 (if saved-mark-active
5147 (when (or (not cur-mark-active)
5148 (not (eq omark nmark)))
5149 (run-hooks 'activate-mark-hook))
5150 ;; If mark has ceased to be active, run deactivate hook.
5151 (when cur-mark-active
5152 (run-hooks 'deactivate-mark-hook))))))
5154 (defmacro save-mark-and-excursion (&rest body)
5155 "Like `save-excursion', but also save and restore the mark state.
5156 This macro does what `save-excursion' did before Emacs 25.1."
5157 (let ((saved-marker-sym (make-symbol "saved-marker")))
5158 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5160 (save-excursion ,@body)
5161 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5163 (defcustom use-empty-active-region nil
5164 "Whether \"region-aware\" commands should act on empty regions.
5165 If nil, region-aware commands treat empty regions as inactive.
5166 If non-nil, region-aware commands treat the region as active as
5167 long as the mark is active, even if the region is empty.
5169 Region-aware commands are those that act on the region if it is
5170 active and Transient Mark mode is enabled, and on the text near
5174 :group 'editing-basics)
5176 (defun use-region-p ()
5177 "Return t if the region is active and it is appropriate to act on it.
5178 This is used by commands that act specially on the region under
5179 Transient Mark mode.
5181 The return value is t if Transient Mark mode is enabled and the
5182 mark is active; furthermore, if `use-empty-active-region' is nil,
5183 the region must not be empty. Otherwise, the return value is nil.
5185 For some commands, it may be appropriate to ignore the value of
5186 `use-empty-active-region'; in that case, use `region-active-p'."
5187 (and (region-active-p)
5188 (or use-empty-active-region (> (region-end) (region-beginning)))))
5190 (defun region-active-p ()
5191 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5193 Some commands act specially on the region when Transient Mark
5194 mode is enabled. Usually, such commands should use
5195 `use-region-p' instead of this function, because `use-region-p'
5196 also checks the value of `use-empty-active-region'."
5197 (and transient-mark-mode mark-active
5198 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5199 ;; without the mark being set (e.g. bug#17324). We really should fix
5200 ;; that problem, but in the mean time, let's make sure we don't say the
5201 ;; region is active when there's no mark.
5202 (progn (cl-assert (mark)) t)))
5204 (defun region-noncontiguous-p ()
5205 "Return non-nil if the region contains several pieces.
5206 An example is a rectangular region handled as a list of
5207 separate contiguous regions for each line."
5208 (> (length (funcall region-extract-function 'bounds)) 1))
5210 (defvar redisplay-unhighlight-region-function
5211 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5213 (defvar redisplay-highlight-region-function
5214 (lambda (start end window rol)
5215 (if (not (overlayp rol))
5216 (let ((nrol (make-overlay start end)))
5217 (funcall redisplay-unhighlight-region-function rol)
5218 (overlay-put nrol 'window window)
5219 (overlay-put nrol 'face 'region)
5220 ;; Normal priority so that a large region doesn't hide all the
5221 ;; overlays within it, but high secondary priority so that if it
5222 ;; ends/starts in the middle of a small overlay, that small overlay
5223 ;; won't hide the region's boundaries.
5224 (overlay-put nrol 'priority '(nil . 100))
5226 (unless (and (eq (overlay-buffer rol) (current-buffer))
5227 (eq (overlay-start rol) start)
5228 (eq (overlay-end rol) end))
5229 (move-overlay rol start end (current-buffer)))
5232 (defun redisplay--update-region-highlight (window)
5233 (let ((rol (window-parameter window 'internal-region-overlay)))
5234 (if (not (and (region-active-p)
5235 (or highlight-nonselected-windows
5236 (eq window (selected-window))
5237 (and (window-minibuffer-p)
5238 (eq window (minibuffer-selected-window))))))
5239 (funcall redisplay-unhighlight-region-function rol)
5240 (let* ((pt (window-point window))
5242 (start (min pt mark))
5245 (funcall redisplay-highlight-region-function
5246 start end window rol)))
5247 (unless (equal new rol)
5248 (set-window-parameter window 'internal-region-overlay
5251 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5252 "Hook run just before redisplay.
5253 It is called in each window that is to be redisplayed. It takes one argument,
5254 which is the window that will be redisplayed. When run, the `current-buffer'
5255 is set to the buffer displayed in that window.")
5257 (defun redisplay--pre-redisplay-functions (windows)
5258 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5260 (with-current-buffer (window-buffer (selected-window))
5261 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5262 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5263 (with-current-buffer (window-buffer win)
5264 (run-hook-with-args 'pre-redisplay-functions win))))))
5266 (add-function :before pre-redisplay-function
5267 #'redisplay--pre-redisplay-functions)
5270 (defvar-local mark-ring nil
5271 "The list of former marks of the current buffer, most recent first.")
5272 (put 'mark-ring 'permanent-local t)
5274 (defcustom mark-ring-max 16
5275 "Maximum size of mark ring. Start discarding off end if gets this big."
5277 :group 'editing-basics)
5279 (defvar global-mark-ring nil
5280 "The list of saved global marks, most recent first.")
5282 (defcustom global-mark-ring-max 16
5283 "Maximum size of global mark ring. \
5284 Start discarding off end if gets this big."
5286 :group 'editing-basics)
5288 (defun pop-to-mark-command ()
5289 "Jump to mark, and pop a new position for mark off the ring.
5290 \(Does not affect global mark ring)."
5293 (user-error "No mark set in this buffer")
5294 (if (= (point) (mark t))
5295 (message "Mark popped"))
5296 (goto-char (mark t))
5299 (defun push-mark-command (arg &optional nomsg)
5300 "Set mark at where point is.
5301 If no prefix ARG and mark is already set there, just activate it.
5302 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5304 (let ((mark (mark t)))
5305 (if (or arg (null mark) (/= mark (point)))
5306 (push-mark nil nomsg t)
5307 (activate-mark 'no-tmm)
5309 (message "Mark activated")))))
5311 (defcustom set-mark-command-repeat-pop nil
5312 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5313 That means that C-u \\[set-mark-command] \\[set-mark-command]
5314 will pop the mark twice, and
5315 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5316 will pop the mark three times.
5318 A value of nil means \\[set-mark-command]'s behavior does not change
5319 after C-u \\[set-mark-command]."
5321 :group 'editing-basics)
5323 (defun set-mark-command (arg)
5324 "Set the mark where point is, or jump to the mark.
5325 Setting the mark also alters the region, which is the text
5326 between point and mark; this is the closest equivalent in
5327 Emacs to what some editors call the \"selection\".
5329 With no prefix argument, set the mark at point, and push the
5330 old mark position on local mark ring. Also push the old mark on
5331 global mark ring, if the previous mark was set in another buffer.
5333 When Transient Mark Mode is off, immediately repeating this
5334 command activates `transient-mark-mode' temporarily.
5336 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5337 jump to the mark, and set the mark from
5338 position popped off the local mark ring (this does not affect the global
5339 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5340 mark ring (see `pop-global-mark').
5342 If `set-mark-command-repeat-pop' is non-nil, repeating
5343 the \\[set-mark-command] command with no prefix argument pops the next position
5344 off the local (or global) mark ring and jumps there.
5346 With \\[universal-argument] \\[universal-argument] as prefix
5347 argument, unconditionally set mark where point is, even if
5348 `set-mark-command-repeat-pop' is non-nil.
5350 Novice Emacs Lisp programmers often try to use the mark for the wrong
5351 purposes. See the documentation of `set-mark' for more information."
5353 (cond ((eq transient-mark-mode 'lambda)
5354 (kill-local-variable 'transient-mark-mode))
5355 ((eq (car-safe transient-mark-mode) 'only)
5358 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5359 (push-mark-command nil))
5360 ((not (eq this-command 'set-mark-command))
5362 (pop-to-mark-command)
5363 (push-mark-command t)))
5364 ((and set-mark-command-repeat-pop
5365 (eq last-command 'pop-global-mark)
5367 (setq this-command 'pop-global-mark)
5369 ((or (and set-mark-command-repeat-pop
5370 (eq last-command 'pop-to-mark-command))
5372 (setq this-command 'pop-to-mark-command)
5373 (pop-to-mark-command))
5374 ((eq last-command 'set-mark-command)
5375 (if (region-active-p)
5378 (message "Mark deactivated"))
5380 (message "Mark activated")))
5382 (push-mark-command nil))))
5384 (defun push-mark (&optional location nomsg activate)
5385 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5386 If the last global mark pushed was not in the current buffer,
5387 also push LOCATION on the global mark ring.
5388 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5390 Novice Emacs Lisp programmers often try to use the mark for the wrong
5391 purposes. See the documentation of `set-mark' for more information.
5393 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5394 (unless (null (mark t))
5395 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5396 (when (> (length mark-ring) mark-ring-max)
5397 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5398 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5399 (set-marker (mark-marker) (or location (point)) (current-buffer))
5400 ;; Now push the mark on the global mark ring.
5401 (if (and global-mark-ring
5402 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5403 ;; The last global mark pushed was in this same buffer.
5404 ;; Don't push another one.
5406 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5407 (when (> (length global-mark-ring) global-mark-ring-max)
5408 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5409 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5410 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5411 (message "Mark set"))
5412 (if (or activate (not transient-mark-mode))
5413 (set-mark (mark t)))
5417 "Pop off mark ring into the buffer's actual mark.
5418 Does not set point. Does nothing if mark ring is empty."
5420 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5421 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5422 (move-marker (car mark-ring) nil)
5423 (if (null (mark t)) (ding))
5424 (setq mark-ring (cdr mark-ring)))
5427 (define-obsolete-function-alias
5428 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5429 (defun exchange-point-and-mark (&optional arg)
5430 "Put the mark where point is now, and point where the mark is now.
5431 This command works even when the mark is not active,
5432 and it reactivates the mark.
5434 If Transient Mark mode is on, a prefix ARG deactivates the mark
5435 if it is active, and otherwise avoids reactivating it. If
5436 Transient Mark mode is off, a prefix ARG enables Transient Mark
5439 (let ((omark (mark t))
5440 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5442 (user-error "No mark set in this buffer"))
5445 (cond (temp-highlight
5446 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5447 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5448 (not (or arg (region-active-p))))
5450 (t (activate-mark)))
5453 (defcustom shift-select-mode t
5454 "When non-nil, shifted motion keys activate the mark momentarily.
5456 While the mark is activated in this way, any shift-translated point
5457 motion key extends the region, and if Transient Mark mode was off, it
5458 is temporarily turned on. Furthermore, the mark will be deactivated
5459 by any subsequent point motion key that was not shift-translated, or
5460 by any action that normally deactivates the mark in Transient Mark mode.
5462 See `this-command-keys-shift-translated' for the meaning of
5465 :group 'editing-basics)
5467 (defun handle-shift-selection ()
5468 "Activate/deactivate mark depending on invocation thru shift translation.
5469 This function is called by `call-interactively' when a command
5470 with a `^' character in its `interactive' spec is invoked, before
5471 running the command itself.
5473 If `shift-select-mode' is enabled and the command was invoked
5474 through shift translation, set the mark and activate the region
5475 temporarily, unless it was already set in this way. See
5476 `this-command-keys-shift-translated' for the meaning of shift
5479 Otherwise, if the region has been activated temporarily,
5480 deactivate it, and restore the variable `transient-mark-mode' to
5482 (cond ((and shift-select-mode this-command-keys-shift-translated)
5483 (unless (and mark-active
5484 (eq (car-safe transient-mark-mode) 'only))
5485 (setq-local transient-mark-mode
5487 (unless (eq transient-mark-mode 'lambda)
5488 transient-mark-mode)))
5489 (push-mark nil nil t)))
5490 ((eq (car-safe transient-mark-mode) 'only)
5491 (setq transient-mark-mode (cdr transient-mark-mode))
5492 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5493 (kill-local-variable 'transient-mark-mode))
5494 (deactivate-mark))))
5496 (define-minor-mode transient-mark-mode
5497 "Toggle Transient Mark mode.
5498 With a prefix argument ARG, enable Transient Mark mode if ARG is
5499 positive, and disable it otherwise. If called from Lisp, enable
5500 Transient Mark mode if ARG is omitted or nil.
5502 Transient Mark mode is a global minor mode. When enabled, the
5503 region is highlighted with the `region' face whenever the mark
5504 is active. The mark is \"deactivated\" by changing the buffer,
5505 and after certain other operations that set the mark but whose
5506 main purpose is something else--for example, incremental search,
5507 \\[beginning-of-buffer], and \\[end-of-buffer].
5509 You can also deactivate the mark by typing \\[keyboard-quit] or
5510 \\[keyboard-escape-quit].
5512 Many commands change their behavior when Transient Mark mode is
5513 in effect and the mark is active, by acting on the region instead
5514 of their usual default part of the buffer's text. Examples of
5515 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5516 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5517 To see the documentation of commands which are sensitive to the
5518 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5519 or \"mark.*active\" at the prompt."
5521 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5522 :variable (default-value 'transient-mark-mode))
5524 (defvar widen-automatically t
5525 "Non-nil means it is ok for commands to call `widen' when they want to.
5526 Some commands will do this in order to go to positions outside
5527 the current accessible part of the buffer.
5529 If `widen-automatically' is nil, these commands will do something else
5530 as a fallback, and won't change the buffer bounds.")
5532 (defvar non-essential nil
5533 "Whether the currently executing code is performing an essential task.
5534 This variable should be non-nil only when running code which should not
5535 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5536 user for a password when we are simply scanning a set of files in the
5537 background or displaying possible completions before the user even asked
5540 (defun pop-global-mark ()
5541 "Pop off global mark ring and jump to the top location."
5543 ;; Pop entries which refer to non-existent buffers.
5544 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5545 (setq global-mark-ring (cdr global-mark-ring)))
5546 (or global-mark-ring
5547 (error "No global mark set"))
5548 (let* ((marker (car global-mark-ring))
5549 (buffer (marker-buffer marker))
5550 (position (marker-position marker)))
5551 (setq global-mark-ring (nconc (cdr global-mark-ring)
5552 (list (car global-mark-ring))))
5554 (or (and (>= position (point-min))
5555 (<= position (point-max)))
5556 (if widen-automatically
5558 (error "Global mark position is outside accessible part of buffer")))
5559 (goto-char position)
5560 (switch-to-buffer buffer)))
5562 (defcustom next-line-add-newlines nil
5563 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5566 :group 'editing-basics)
5568 (defun next-line (&optional arg try-vscroll)
5569 "Move cursor vertically down ARG lines.
5570 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5571 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5572 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5573 function will not vscroll.
5577 If there is no character in the target line exactly under the current column,
5578 the cursor is positioned after the character in that line which spans this
5579 column, or at the end of the line if it is not long enough.
5580 If there is no line in the buffer after this one, behavior depends on the
5581 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5582 to create a line, and moves the cursor to that line. Otherwise it moves the
5583 cursor to the end of the buffer.
5585 If the variable `line-move-visual' is non-nil, this command moves
5586 by display lines. Otherwise, it moves by buffer lines, without
5587 taking variable-width characters or continued lines into account.
5589 The command \\[set-goal-column] can be used to create
5590 a semipermanent goal column for this command.
5591 Then instead of trying to move exactly vertically (or as close as possible),
5592 this command moves to the specified goal column (or as close as possible).
5593 The goal column is stored in the variable `goal-column', which is nil
5594 when there is no goal column. Note that setting `goal-column'
5595 overrides `line-move-visual' and causes this command to move by buffer
5596 lines rather than by display lines."
5597 (declare (interactive-only forward-line))
5598 (interactive "^p\np")
5599 (or arg (setq arg 1))
5600 (if (and next-line-add-newlines (= arg 1))
5601 (if (save-excursion (end-of-line) (eobp))
5602 ;; When adding a newline, don't expand an abbrev.
5603 (let ((abbrev-mode nil))
5605 (insert (if use-hard-newlines hard-newline "\n")))
5606 (line-move arg nil nil try-vscroll))
5607 (if (called-interactively-p 'interactive)
5609 (line-move arg nil nil try-vscroll)
5610 ((beginning-of-buffer end-of-buffer)
5611 (signal (car err) (cdr err))))
5612 (line-move arg nil nil try-vscroll)))
5615 (defun previous-line (&optional arg try-vscroll)
5616 "Move cursor vertically up ARG lines.
5617 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5618 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5619 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5620 function will not vscroll.
5624 If there is no character in the target line exactly over the current column,
5625 the cursor is positioned after the character in that line which spans this
5626 column, or at the end of the line if it is not long enough.
5628 If the variable `line-move-visual' is non-nil, this command moves
5629 by display lines. Otherwise, it moves by buffer lines, without
5630 taking variable-width characters or continued lines into account.
5632 The command \\[set-goal-column] can be used to create
5633 a semipermanent goal column for this command.
5634 Then instead of trying to move exactly vertically (or as close as possible),
5635 this command moves to the specified goal column (or as close as possible).
5636 The goal column is stored in the variable `goal-column', which is nil
5637 when there is no goal column. Note that setting `goal-column'
5638 overrides `line-move-visual' and causes this command to move by buffer
5639 lines rather than by display lines."
5640 (declare (interactive-only
5641 "use `forward-line' with negative argument instead."))
5642 (interactive "^p\np")
5643 (or arg (setq arg 1))
5644 (if (called-interactively-p 'interactive)
5646 (line-move (- arg) nil nil try-vscroll)
5647 ((beginning-of-buffer end-of-buffer)
5648 (signal (car err) (cdr err))))
5649 (line-move (- arg) nil nil try-vscroll))
5652 (defcustom track-eol nil
5653 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5654 This means moving to the end of each line moved onto.
5655 The beginning of a blank line does not count as the end of a line.
5656 This has no effect when the variable `line-move-visual' is non-nil."
5658 :group 'editing-basics)
5660 (defcustom goal-column nil
5661 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5662 A non-nil setting overrides the variable `line-move-visual', which see."
5663 :type '(choice integer
5664 (const :tag "None" nil))
5665 :group 'editing-basics)
5666 (make-variable-buffer-local 'goal-column)
5668 (defvar temporary-goal-column 0
5669 "Current goal column for vertical motion.
5670 It is the column where point was at the start of the current run
5671 of vertical motion commands.
5673 When moving by visual lines via the function `line-move-visual', it is a cons
5674 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5675 divided by the default column width, and HSCROLL is the number of
5676 columns by which window is scrolled from left margin.
5678 When the `track-eol' feature is doing its job, the value is
5679 `most-positive-fixnum'.")
5681 (defcustom line-move-ignore-invisible t
5682 "Non-nil means commands that move by lines ignore invisible newlines.
5683 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5684 as if newlines that are invisible didn't exist, and count
5685 only visible newlines. Thus, moving across across 2 newlines
5686 one of which is invisible will be counted as a one-line move.
5687 Also, a non-nil value causes invisible text to be ignored when
5688 counting columns for the purposes of keeping point in the same
5689 column by \\[next-line] and \\[previous-line].
5691 Outline mode sets this."
5693 :group 'editing-basics)
5695 (defcustom line-move-visual t
5696 "When non-nil, `line-move' moves point by visual lines.
5697 This movement is based on where the cursor is displayed on the
5698 screen, instead of relying on buffer contents alone. It takes
5699 into account variable-width characters and line continuation.
5700 If nil, `line-move' moves point by logical lines.
5701 A non-nil setting of `goal-column' overrides the value of this variable
5702 and forces movement by logical lines.
5703 A window that is horizontally scrolled also forces movement by logical
5706 :group 'editing-basics
5709 ;; Only used if display-graphic-p.
5710 (declare-function font-info "font.c" (name &optional frame))
5712 (defun default-font-height ()
5713 "Return the height in pixels of the current buffer's default face font.
5715 If the default font is remapped (see `face-remapping-alist'), the
5716 function returns the height of the remapped face."
5717 (let ((default-font (face-font 'default)))
5719 ((and (display-multi-font-p)
5720 ;; Avoid calling font-info if the frame's default font was
5721 ;; not changed since the frame was created. That's because
5722 ;; font-info is expensive for some fonts, see bug #14838.
5723 (not (string= (frame-parameter nil 'font) default-font)))
5724 (aref (font-info default-font) 3))
5725 (t (frame-char-height)))))
5727 (defun default-font-width ()
5728 "Return the width in pixels of the current buffer's default face font.
5730 If the default font is remapped (see `face-remapping-alist'), the
5731 function returns the width of the remapped face."
5732 (let ((default-font (face-font 'default)))
5734 ((and (display-multi-font-p)
5735 ;; Avoid calling font-info if the frame's default font was
5736 ;; not changed since the frame was created. That's because
5737 ;; font-info is expensive for some fonts, see bug #14838.
5738 (not (string= (frame-parameter nil 'font) default-font)))
5739 (let* ((info (font-info (face-font 'default)))
5740 (width (aref info 11)))
5744 (t (frame-char-width)))))
5746 (defun default-line-height ()
5747 "Return the pixel height of current buffer's default-face text line.
5749 The value includes `line-spacing', if any, defined for the buffer
5751 (let ((dfh (default-font-height))
5752 (lsp (if (display-graphic-p)
5754 (default-value 'line-spacing)
5755 (frame-parameter nil 'line-spacing)
5759 (setq lsp (truncate (* (frame-char-height) lsp))))
5762 (defun window-screen-lines ()
5763 "Return the number of screen lines in the text area of the selected window.
5765 This is different from `window-text-height' in that this function counts
5766 lines in units of the height of the font used by the default face displayed
5767 in the window, not in units of the frame's default font, and also accounts
5768 for `line-spacing', if any, defined for the window's buffer or frame.
5770 The value is a floating-point number."
5771 (let ((edges (window-inside-pixel-edges))
5772 (dlh (default-line-height)))
5773 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5775 ;; Returns non-nil if partial move was done.
5776 (defun line-move-partial (arg noerror to-end)
5778 ;; Move backward (up).
5779 ;; If already vscrolled, reduce vscroll
5780 (let ((vs (window-vscroll nil t))
5781 (dlh (default-line-height)))
5783 (set-window-vscroll nil (- vs dlh) t)))
5785 ;; Move forward (down).
5786 (let* ((lh (window-line-height -1))
5791 (this-lh (window-line-height))
5792 (this-height (car this-lh))
5793 (this-ypos (nth 2 this-lh))
5794 (dlh (default-line-height))
5795 (wslines (window-screen-lines))
5796 (edges (window-inside-pixel-edges))
5797 (winh (- (nth 3 edges) (nth 1 edges) 1))
5799 (if (> (mod wslines 1.0) 0.0)
5800 (setq wslines (round (+ wslines 0.5))))
5805 (<= this-ypos (- dlh)))
5807 (let ((wend (pos-visible-in-window-p t nil t)))
5808 (setq rbot (nth 3 wend)
5810 vpos (nth 5 wend))))
5812 (let ((wstart (pos-visible-in-window-p nil nil t)))
5813 (setq this-ypos (nth 2 wstart)
5814 this-height (nth 4 wstart))))
5817 (let ((ppos (posn-at-point))
5819 (setq col-row (posn-actual-col-row ppos))
5821 (- (cdr col-row) (window-vscroll))
5822 (cdr (posn-col-row ppos))))))
5823 ;; VPOS > 0 means the last line is only partially visible.
5824 ;; But if the part that is visible is at least as tall as the
5825 ;; default font, that means the line is actually fully
5826 ;; readable, and something like line-spacing is hidden. So in
5827 ;; that case we accept the last line in the window as still
5828 ;; visible, and consider the margin as starting one line
5830 (if (and vpos (> vpos 0))
5832 (>= rowh (default-font-height))
5834 (setq last-line (min (- wslines scroll-margin) vpos))
5835 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5837 ;; If last line of window is fully visible, and vscrolling
5838 ;; more would make this line invisible, move forward.
5839 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5841 (<= this-height dlh))
5842 (or (null rbot) (= rbot 0)))
5844 ;; If cursor is not in the bottom scroll margin, and the
5845 ;; current line is is not too tall, move forward.
5846 ((and (or (null this-height) (<= this-height winh))
5851 ;; When already vscrolled, we vscroll some more if we can,
5852 ;; or clear vscroll and move forward at end of tall image.
5854 (when (or (and rbot (> rbot 0))
5855 (and this-height (> this-height dlh)))
5856 (set-window-vscroll nil (+ vs dlh) t)))
5857 ;; If cursor just entered the bottom scroll margin, move forward,
5858 ;; but also optionally vscroll one line so redisplay won't recenter.
5862 ;; Don't vscroll if the partially-visible line at window
5863 ;; bottom is not too tall (a.k.a. "just one more text
5864 ;; line"): in that case, we do want redisplay to behave
5865 ;; normally, i.e. recenter or whatever.
5867 ;; Note: ROWH + RBOT from the value returned by
5868 ;; pos-visible-in-window-p give the total height of the
5869 ;; partially-visible glyph row at the end of the window. As
5870 ;; we are dealing with floats, we disregard sub-pixel
5871 ;; discrepancies between that and DLH.
5872 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5873 (set-window-vscroll nil dlh t))
5874 (line-move-1 arg noerror to-end)
5876 ;; If there are lines above the last line, scroll-up one line.
5877 ((and vpos (> vpos 0))
5880 ;; Finally, start vscroll.
5882 (set-window-vscroll nil dlh t)))))))
5885 ;; This is like line-move-1 except that it also performs
5886 ;; vertical scrolling of tall images if appropriate.
5887 ;; That is not really a clean thing to do, since it mixes
5888 ;; scrolling with cursor motion. But so far we don't have
5889 ;; a cleaner solution to the problem of making C-n do something
5890 ;; useful given a tall image.
5891 (defun line-move (arg &optional noerror to-end try-vscroll)
5892 "Move forward ARG lines.
5893 If NOERROR, don't signal an error if we can't move ARG lines.
5895 TRY-VSCROLL controls whether to vscroll tall lines: if either
5896 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5899 (line-move-1 arg noerror to-end)
5900 (unless (and auto-window-vscroll try-vscroll
5901 ;; Only vscroll for single line moves
5903 ;; Under scroll-conservatively, the display engine
5904 ;; does this better.
5905 (zerop scroll-conservatively)
5906 ;; But don't vscroll in a keyboard macro.
5907 (not defining-kbd-macro)
5908 (not executing-kbd-macro)
5909 (line-move-partial arg noerror to-end))
5910 (set-window-vscroll nil 0 t)
5911 (if (and line-move-visual
5912 ;; Display-based column are incompatible with goal-column.
5914 ;; When the text in the window is scrolled to the left,
5915 ;; display-based motion doesn't make sense (because each
5916 ;; logical line occupies exactly one screen line).
5917 (not (> (window-hscroll) 0))
5918 ;; Likewise when the text _was_ scrolled to the left
5919 ;; when the current run of vertical motion commands
5921 (not (and (memq last-command
5922 `(next-line previous-line ,this-command))
5924 (numberp temporary-goal-column)
5925 (>= temporary-goal-column
5926 (- (window-width) hscroll-margin)))))
5927 (prog1 (line-move-visual arg noerror)
5928 ;; If we moved into a tall line, set vscroll to make
5929 ;; scrolling through tall images more smooth.
5930 (let ((lh (line-pixel-height))
5931 (edges (window-inside-pixel-edges))
5932 (dlh (default-line-height))
5934 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5936 (< (point) (window-start))
5941 (line-move-1 arg noerror to-end)))))
5943 ;; Display-based alternative to line-move-1.
5944 ;; Arg says how many lines to move. The value is t if we can move the
5945 ;; specified number of lines.
5946 (defun line-move-visual (arg &optional noerror)
5947 "Move ARG lines forward.
5948 If NOERROR, don't signal an error if we can't move that many lines."
5949 (let ((opoint (point))
5950 (hscroll (window-hscroll))
5952 ;; Check if the previous command was a line-motion command, or if
5953 ;; we were called from some other command.
5954 (if (and (consp temporary-goal-column)
5955 (memq last-command `(next-line previous-line ,this-command)))
5956 ;; If so, there's no need to reset `temporary-goal-column',
5957 ;; but we may need to hscroll.
5958 (if (or (/= (cdr temporary-goal-column) hscroll)
5959 (> (cdr temporary-goal-column) 0))
5960 (setq target-hscroll (cdr temporary-goal-column)))
5961 ;; Otherwise, we should reset `temporary-goal-column'.
5962 (let ((posn (posn-at-point))
5965 ;; Handle the `overflow-newline-into-fringe' case:
5966 ((eq (nth 1 posn) 'right-fringe)
5967 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
5968 ((car (posn-x-y posn))
5969 (setq x-pos (car (posn-x-y posn)))
5970 ;; In R2L lines, the X pixel coordinate is measured from the
5971 ;; left edge of the window, but columns are still counted
5972 ;; from the logical-order beginning of the line, i.e. from
5973 ;; the right edge in this case. We need to adjust for that.
5974 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
5975 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
5976 (setq temporary-goal-column
5977 (cons (/ (float x-pos)
5981 (set-window-hscroll (selected-window) target-hscroll))
5982 ;; vertical-motion can move more than it was asked to if it moves
5983 ;; across display strings with newlines. We don't want to ring
5984 ;; the bell and announce beginning/end of buffer in that case.
5985 (or (and (or (and (>= arg 0)
5986 (>= (vertical-motion
5987 (cons (or goal-column
5988 (if (consp temporary-goal-column)
5989 (car temporary-goal-column)
5990 temporary-goal-column))
5994 (<= (vertical-motion
5995 (cons (or goal-column
5996 (if (consp temporary-goal-column)
5997 (car temporary-goal-column)
5998 temporary-goal-column))
6003 ;; If the goal column lies on a display string,
6004 ;; `vertical-motion' advances the cursor to the end
6005 ;; of the string. For arg < 0, this can cause the
6006 ;; cursor to get stuck. (Bug#3020).
6007 (= (vertical-motion arg) arg)))
6009 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6012 ;; This is the guts of next-line and previous-line.
6013 ;; Arg says how many lines to move.
6014 ;; The value is t if we can move the specified number of lines.
6015 (defun line-move-1 (arg &optional noerror _to-end)
6016 ;; Don't run any point-motion hooks, and disregard intangibility,
6017 ;; for intermediate positions.
6018 (let ((inhibit-point-motion-hooks t)
6021 (if (consp temporary-goal-column)
6022 (setq temporary-goal-column (+ (car temporary-goal-column)
6023 (cdr temporary-goal-column))))
6026 (if (not (memq last-command '(next-line previous-line)))
6027 (setq temporary-goal-column
6028 (if (and track-eol (eolp)
6029 ;; Don't count beg of empty line as end of line
6030 ;; unless we just did explicit end-of-line.
6031 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6032 most-positive-fixnum
6035 (if (not (or (integerp selective-display)
6036 line-move-ignore-invisible))
6037 ;; Use just newline characters.
6038 ;; Set ARG to 0 if we move as many lines as requested.
6040 (progn (if (> arg 1) (forward-line (1- arg)))
6041 ;; This way of moving forward ARG lines
6042 ;; verifies that we have a newline after the last one.
6043 ;; It doesn't get confused by intangible text.
6045 (if (zerop (forward-line 1))
6047 (and (zerop (forward-line arg))
6051 (signal (if (< arg 0)
6052 'beginning-of-buffer
6055 ;; Move by arg lines, but ignore invisible ones.
6057 (while (and (> arg 0) (not done))
6058 ;; If the following character is currently invisible,
6059 ;; skip all characters with that same `invisible' property value.
6060 (while (and (not (eobp)) (invisible-p (point)))
6061 (goto-char (next-char-property-change (point))))
6063 ;; We don't use `end-of-line', since we want to escape
6064 ;; from field boundaries occurring exactly at point.
6065 (goto-char (constrain-to-field
6066 (let ((inhibit-field-text-motion t))
6067 (line-end-position))
6069 'inhibit-line-move-field-capture))
6070 ;; If there's no invisibility here, move over the newline.
6074 (signal 'end-of-buffer nil)
6076 ((and (> arg 1) ;; Use vertical-motion for last move
6077 (not (integerp selective-display))
6078 (not (invisible-p (point))))
6079 ;; We avoid vertical-motion when possible
6080 ;; because that has to fontify.
6082 ;; Otherwise move a more sophisticated way.
6083 ((zerop (vertical-motion 1))
6085 (signal 'end-of-buffer nil)
6088 (setq arg (1- arg))))
6089 ;; The logic of this is the same as the loop above,
6090 ;; it just goes in the other direction.
6091 (while (and (< arg 0) (not done))
6092 ;; For completely consistency with the forward-motion
6093 ;; case, we should call beginning-of-line here.
6094 ;; However, if point is inside a field and on a
6095 ;; continued line, the call to (vertical-motion -1)
6096 ;; below won't move us back far enough; then we return
6097 ;; to the same column in line-move-finish, and point
6098 ;; gets stuck -- cyd
6103 (signal 'beginning-of-buffer nil)
6105 ((and (< arg -1) ;; Use vertical-motion for last move
6106 (not (integerp selective-display))
6107 (not (invisible-p (1- (point)))))
6109 ((zerop (vertical-motion -1))
6111 (signal 'beginning-of-buffer nil)
6115 (while (and ;; Don't move over previous invis lines
6116 ;; if our target is the middle of this line.
6117 (or (zerop (or goal-column temporary-goal-column))
6119 (not (bobp)) (invisible-p (1- (point))))
6120 (goto-char (previous-char-property-change (point))))))))
6121 ;; This is the value the function returns.
6125 ;; If we did not move down as far as desired, at least go
6126 ;; to end of line. Be sure to call point-entered and
6127 ;; point-left-hooks.
6128 (let* ((npoint (prog1 (line-end-position)
6129 (goto-char opoint)))
6130 (inhibit-point-motion-hooks nil))
6131 (goto-char npoint)))
6133 ;; If we did not move up as far as desired,
6134 ;; at least go to beginning of line.
6135 (let* ((npoint (prog1 (line-beginning-position)
6136 (goto-char opoint)))
6137 (inhibit-point-motion-hooks nil))
6138 (goto-char npoint)))
6140 (line-move-finish (or goal-column temporary-goal-column)
6141 opoint (> orig-arg 0)))))))
6143 (defun line-move-finish (column opoint forward)
6146 ;; Set REPEAT to t to repeat the whole thing.
6151 (line-beg (line-beginning-position))
6153 ;; Compute the end of the line
6154 ;; ignoring effectively invisible newlines.
6156 ;; Like end-of-line but ignores fields.
6157 (skip-chars-forward "^\n")
6158 (while (and (not (eobp)) (invisible-p (point)))
6159 (goto-char (next-char-property-change (point)))
6160 (skip-chars-forward "^\n"))
6163 ;; Move to the desired column.
6164 (line-move-to-column (truncate column))
6166 ;; Corner case: suppose we start out in a field boundary in
6167 ;; the middle of a continued line. When we get to
6168 ;; line-move-finish, point is at the start of a new *screen*
6169 ;; line but the same text line; then line-move-to-column would
6170 ;; move us backwards. Test using C-n with point on the "x" in
6171 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6178 ;; Process intangibility within a line.
6179 ;; With inhibit-point-motion-hooks bound to nil, a call to
6180 ;; goto-char moves point past intangible text.
6182 ;; However, inhibit-point-motion-hooks controls both the
6183 ;; intangibility and the point-entered/point-left hooks. The
6184 ;; following hack avoids calling the point-* hooks
6185 ;; unnecessarily. Note that we move *forward* past intangible
6186 ;; text when the initial and final points are the same.
6188 (let ((inhibit-point-motion-hooks nil))
6191 ;; If intangibility moves us to a different (later) place
6192 ;; in the same line, use that as the destination.
6193 (if (<= (point) line-end)
6195 ;; If that position is "too late",
6196 ;; try the previous allowable position.
6200 ;; If going forward, don't accept the previous
6201 ;; allowable position if it is before the target line.
6202 (< line-beg (point))
6203 ;; If going backward, don't accept the previous
6204 ;; allowable position if it is still after the target line.
6205 (<= (point) line-end))
6207 ;; As a last resort, use the end of the line.
6208 (setq new line-end))))
6210 ;; Now move to the updated destination, processing fields
6211 ;; as well as intangibility.
6213 (let ((inhibit-point-motion-hooks nil))
6215 ;; Ignore field boundaries if the initial and final
6216 ;; positions have the same `field' property, even if the
6217 ;; fields are non-contiguous. This seems to be "nicer"
6218 ;; behavior in many situations.
6219 (if (eq (get-char-property new 'field)
6220 (get-char-property opoint 'field))
6222 (constrain-to-field new opoint t t
6223 'inhibit-line-move-field-capture))))
6225 ;; If all this moved us to a different line,
6226 ;; retry everything within that new line.
6227 (when (or (< (point) line-beg) (> (point) line-end))
6228 ;; Repeat the intangibility and field processing.
6229 (setq repeat t))))))
6231 (defun line-move-to-column (col)
6232 "Try to find column COL, considering invisibility.
6233 This function works only in certain cases,
6234 because what we really need is for `move-to-column'
6235 and `current-column' to be able to ignore invisible text."
6238 (move-to-column col))
6240 (when (and line-move-ignore-invisible
6241 (not (bolp)) (invisible-p (1- (point))))
6242 (let ((normal-location (point))
6243 (normal-column (current-column)))
6244 ;; If the following character is currently invisible,
6245 ;; skip all characters with that same `invisible' property value.
6246 (while (and (not (eobp))
6247 (invisible-p (point)))
6248 (goto-char (next-char-property-change (point))))
6249 ;; Have we advanced to a larger column position?
6250 (if (> (current-column) normal-column)
6251 ;; We have made some progress towards the desired column.
6252 ;; See if we can make any further progress.
6253 (line-move-to-column (+ (current-column) (- col normal-column)))
6254 ;; Otherwise, go to the place we originally found
6255 ;; and move back over invisible text.
6256 ;; that will get us to the same place on the screen
6257 ;; but with a more reasonable buffer position.
6258 (goto-char normal-location)
6260 ;; We want the real line beginning, so it's consistent
6261 ;; with bolp below, otherwise we might infloop.
6262 (let ((inhibit-field-text-motion t))
6263 (line-beginning-position))))
6264 (while (and (not (bolp)) (invisible-p (1- (point))))
6265 (goto-char (previous-char-property-change (point) line-beg))))))))
6267 (defun move-end-of-line (arg)
6268 "Move point to end of current line as displayed.
6269 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6270 If point reaches the beginning or end of buffer, it stops there.
6272 To ignore the effects of the `intangible' text or overlay
6273 property, bind `inhibit-point-motion-hooks' to t.
6274 If there is an image in the current line, this function
6275 disregards newlines that are part of the text on which the image
6278 (or arg (setq arg 1))
6283 (let ((goal-column 0)
6284 (line-move-visual nil))
6285 (and (line-move arg t)
6286 ;; With bidi reordering, we may not be at bol,
6287 ;; so make sure we are.
6288 (skip-chars-backward "^\n")
6291 (while (and (not (bobp)) (invisible-p (1- (point))))
6292 (goto-char (previous-single-char-property-change
6293 (point) 'invisible)))
6297 (if (and (> (point) newpos)
6298 (eq (preceding-char) ?\n))
6300 (if (and (> (point) newpos) (not (eobp))
6301 (not (eq (following-char) ?\n)))
6302 ;; If we skipped something intangible and now we're not
6303 ;; really at eol, keep going.
6307 (defun move-beginning-of-line (arg)
6308 "Move point to beginning of current line as displayed.
6309 \(If there's an image in the line, this disregards newlines
6310 which are part of the text that the image rests on.)
6312 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6313 If point reaches the beginning or end of buffer, it stops there.
6314 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6316 (or arg (setq arg 1))
6318 (let ((orig (point))
6319 first-vis first-vis-field-value)
6321 ;; Move by lines, if ARG is not 1 (the default).
6323 (let ((line-move-visual nil))
6324 (line-move (1- arg) t)))
6326 ;; Move to beginning-of-line, ignoring fields and invisible text.
6327 (skip-chars-backward "^\n")
6328 (while (and (not (bobp)) (invisible-p (1- (point))))
6329 (goto-char (previous-char-property-change (point)))
6330 (skip-chars-backward "^\n"))
6332 ;; Now find first visible char in the line.
6333 (while (and (< (point) orig) (invisible-p (point)))
6334 (goto-char (next-char-property-change (point) orig)))
6335 (setq first-vis (point))
6337 ;; See if fields would stop us from reaching FIRST-VIS.
6338 (setq first-vis-field-value
6339 (constrain-to-field first-vis orig (/= arg 1) t nil))
6341 (goto-char (if (/= first-vis-field-value first-vis)
6342 ;; If yes, obey them.
6343 first-vis-field-value
6344 ;; Otherwise, move to START with attention to fields.
6345 ;; (It is possible that fields never matter in this case.)
6346 (constrain-to-field (point) orig
6347 (/= arg 1) t nil)))))
6350 ;; Many people have said they rarely use this feature, and often type
6351 ;; it by accident. Maybe it shouldn't even be on a key.
6352 (put 'set-goal-column 'disabled t)
6354 (defun set-goal-column (arg)
6355 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6356 Those commands will move to this position in the line moved to
6357 rather than trying to keep the same horizontal position.
6358 With a non-nil argument ARG, clears out the goal column
6359 so that \\[next-line] and \\[previous-line] resume vertical motion.
6360 The goal column is stored in the variable `goal-column'."
6364 (setq goal-column nil)
6365 (message "No goal column"))
6366 (setq goal-column (current-column))
6367 ;; The older method below can be erroneous if `set-goal-column' is bound
6368 ;; to a sequence containing %
6369 ;;(message (substitute-command-keys
6370 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6374 (format "Goal column %d " goal-column)
6375 (substitute-command-keys
6376 "(use \\[set-goal-column] with an arg to unset it)")))
6381 ;;; Editing based on visual lines, as opposed to logical lines.
6383 (defun end-of-visual-line (&optional n)
6384 "Move point to end of current visual line.
6385 With argument N not nil or 1, move forward N - 1 visual lines first.
6386 If point reaches the beginning or end of buffer, it stops there.
6387 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6391 (let ((line-move-visual t))
6392 (line-move (1- n) t)))
6393 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6394 ;; constrain to field boundaries, so we don't either.
6395 (vertical-motion (cons (window-width) 0)))
6397 (defun beginning-of-visual-line (&optional n)
6398 "Move point to beginning of current visual line.
6399 With argument N not nil or 1, move forward N - 1 visual lines first.
6400 If point reaches the beginning or end of buffer, it stops there.
6401 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6404 (let ((opoint (point)))
6406 (let ((line-move-visual t))
6407 (line-move (1- n) t)))
6409 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6410 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6412 (defun kill-visual-line (&optional arg)
6413 "Kill the rest of the visual line.
6414 With prefix argument ARG, kill that many visual lines from point.
6415 If ARG is negative, kill visual lines backward.
6416 If ARG is zero, kill the text before point on the current visual
6419 If you want to append the killed line to the last killed text,
6420 use \\[append-next-kill] before \\[kill-line].
6422 If the buffer is read-only, Emacs will beep and refrain from deleting
6423 the line, but put the line in the kill ring anyway. This means that
6424 you can use this command to copy text from a read-only buffer.
6425 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6428 ;; Like in `kill-line', it's better to move point to the other end
6429 ;; of the kill before killing.
6430 (let ((opoint (point))
6431 (kill-whole-line (and kill-whole-line (bolp))))
6433 (vertical-motion (prefix-numeric-value arg))
6434 (end-of-visual-line 1)
6435 (if (= (point) opoint)
6437 ;; Skip any trailing whitespace at the end of the visual line.
6438 ;; We used to do this only if `show-trailing-whitespace' is
6439 ;; nil, but that's wrong; the correct thing would be to check
6440 ;; whether the trailing whitespace is highlighted. But, it's
6441 ;; OK to just do this unconditionally.
6442 (skip-chars-forward " \t")))
6443 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6447 (defun next-logical-line (&optional arg try-vscroll)
6448 "Move cursor vertically down ARG lines.
6449 This is identical to `next-line', except that it always moves
6450 by logical lines instead of visual lines, ignoring the value of
6451 the variable `line-move-visual'."
6452 (interactive "^p\np")
6453 (let ((line-move-visual nil))
6455 (next-line arg try-vscroll))))
6457 (defun previous-logical-line (&optional arg try-vscroll)
6458 "Move cursor vertically up ARG lines.
6459 This is identical to `previous-line', except that it always moves
6460 by logical lines instead of visual lines, ignoring the value of
6461 the variable `line-move-visual'."
6462 (interactive "^p\np")
6463 (let ((line-move-visual nil))
6465 (previous-line arg try-vscroll))))
6467 (defgroup visual-line nil
6468 "Editing based on visual lines."
6472 (defvar visual-line-mode-map
6473 (let ((map (make-sparse-keymap)))
6474 (define-key map [remap kill-line] 'kill-visual-line)
6475 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6476 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6477 ;; These keybindings interfere with xterm function keys. Are
6478 ;; there any other suitable bindings?
6479 ;; (define-key map "\M-[" 'previous-logical-line)
6480 ;; (define-key map "\M-]" 'next-logical-line)
6483 (defcustom visual-line-fringe-indicators '(nil nil)
6484 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6485 The value should be a list of the form (LEFT RIGHT), where LEFT
6486 and RIGHT are symbols representing the bitmaps to display, to
6487 indicate wrapped lines, in the left and right fringes respectively.
6488 See also `fringe-indicator-alist'.
6489 The default is not to display fringe indicators for wrapped lines.
6490 This variable does not affect fringe indicators displayed for
6492 :type '(list (choice (const :tag "Hide left indicator" nil)
6493 (const :tag "Left curly arrow" left-curly-arrow)
6494 (symbol :tag "Other bitmap"))
6495 (choice (const :tag "Hide right indicator" nil)
6496 (const :tag "Right curly arrow" right-curly-arrow)
6497 (symbol :tag "Other bitmap")))
6498 :set (lambda (symbol value)
6499 (dolist (buf (buffer-list))
6500 (with-current-buffer buf
6501 (when (and (boundp 'visual-line-mode)
6502 (symbol-value 'visual-line-mode))
6503 (setq fringe-indicator-alist
6504 (cons (cons 'continuation value)
6507 (copy-tree fringe-indicator-alist)))))))
6508 (set-default symbol value)))
6510 (defvar visual-line--saved-state nil)
6512 (define-minor-mode visual-line-mode
6513 "Toggle visual line based editing (Visual Line mode).
6514 With a prefix argument ARG, enable Visual Line mode if ARG is
6515 positive, and disable it otherwise. If called from Lisp, enable
6516 the mode if ARG is omitted or nil.
6518 When Visual Line mode is enabled, `word-wrap' is turned on in
6519 this buffer, and simple editing commands are redefined to act on
6520 visual lines, not logical lines. See Info node `Visual Line
6522 :keymap visual-line-mode-map
6525 (if visual-line-mode
6527 (set (make-local-variable 'visual-line--saved-state) nil)
6528 ;; Save the local values of some variables, to be restored if
6529 ;; visual-line-mode is turned off.
6530 (dolist (var '(line-move-visual truncate-lines
6531 truncate-partial-width-windows
6532 word-wrap fringe-indicator-alist))
6533 (if (local-variable-p var)
6534 (push (cons var (symbol-value var))
6535 visual-line--saved-state)))
6536 (set (make-local-variable 'line-move-visual) t)
6537 (set (make-local-variable 'truncate-partial-width-windows) nil)
6538 (setq truncate-lines nil
6540 fringe-indicator-alist
6541 (cons (cons 'continuation visual-line-fringe-indicators)
6542 fringe-indicator-alist)))
6543 (kill-local-variable 'line-move-visual)
6544 (kill-local-variable 'word-wrap)
6545 (kill-local-variable 'truncate-lines)
6546 (kill-local-variable 'truncate-partial-width-windows)
6547 (kill-local-variable 'fringe-indicator-alist)
6548 (dolist (saved visual-line--saved-state)
6549 (set (make-local-variable (car saved)) (cdr saved)))
6550 (kill-local-variable 'visual-line--saved-state)))
6552 (defun turn-on-visual-line-mode ()
6553 (visual-line-mode 1))
6555 (define-globalized-minor-mode global-visual-line-mode
6556 visual-line-mode turn-on-visual-line-mode)
6559 (defun transpose-chars (arg)
6560 "Interchange characters around point, moving forward one character.
6561 With prefix arg ARG, effect is to take character before point
6562 and drag it forward past ARG other characters (backward if ARG negative).
6563 If no argument and at end of line, the previous two chars are exchanged."
6565 (when (and (null arg) (eolp) (not (bobp))
6566 (not (get-text-property (1- (point)) 'read-only)))
6568 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6570 (defun transpose-words (arg)
6571 "Interchange words around point, leaving point at end of them.
6572 With prefix arg ARG, effect is to take word before or around point
6573 and drag it forward past ARG other words (backward if ARG negative).
6574 If ARG is zero, the words around or after point and around or after mark
6576 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6578 (transpose-subr 'forward-word arg))
6580 (defun transpose-sexps (arg)
6581 "Like \\[transpose-words] but applies to sexps.
6582 Does not work on a sexp that point is in the middle of
6583 if it is a list or string."
6587 ;; Here we should try to simulate the behavior of
6588 ;; (cons (progn (forward-sexp x) (point))
6589 ;; (progn (forward-sexp (- x)) (point)))
6590 ;; Except that we don't want to rely on the second forward-sexp
6591 ;; putting us back to where we want to be, since forward-sexp-function
6592 ;; might do funny things like infix-precedence.
6594 (looking-at "\\sw\\|\\s_")
6596 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6597 ;; Jumping over a symbol. We might be inside it, mind you.
6598 (progn (funcall (if (> arg 0)
6599 'skip-syntax-backward 'skip-syntax-forward)
6601 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6602 ;; Otherwise, we're between sexps. Take a step back before jumping
6603 ;; to make sure we'll obey the same precedence no matter which direction
6605 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6606 (cons (save-excursion (forward-sexp arg) (point))
6607 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6608 (not (zerop (funcall (if (> arg 0)
6609 'skip-syntax-forward
6610 'skip-syntax-backward)
6615 (defun transpose-lines (arg)
6616 "Exchange current line and previous line, leaving point after both.
6617 With argument ARG, takes previous line and moves it past ARG lines.
6618 With argument 0, interchanges line point is in with line mark is in."
6620 (transpose-subr (function
6624 ;; Move forward over ARG lines,
6625 ;; but create newlines if necessary.
6626 (setq arg (forward-line arg))
6627 (if (/= (preceding-char) ?\n)
6628 (setq arg (1+ arg)))
6631 (forward-line arg))))
6634 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6635 ;; which seems inconsistent with the ARG /= 0 case.
6636 ;; FIXME document SPECIAL.
6637 (defun transpose-subr (mover arg &optional special)
6638 "Subroutine to do the work of transposing objects.
6639 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6640 moves forward by units of the given object (e.g. forward-sentence,
6641 forward-paragraph). If ARG is zero, exchanges the current object
6642 with the one containing mark. If ARG is an integer, moves the
6643 current object past ARG following (if ARG is positive) or
6644 preceding (if ARG is negative) objects, leaving point after the
6646 (let ((aux (if special mover
6648 (cons (progn (funcall mover x) (point))
6649 (progn (funcall mover (- x)) (point))))))
6654 (setq pos1 (funcall aux 1))
6655 (goto-char (or (mark) (error "No mark set in this buffer")))
6656 (setq pos2 (funcall aux 1))
6657 (transpose-subr-1 pos1 pos2))
6658 (exchange-point-and-mark))
6660 (setq pos1 (funcall aux -1))
6661 (setq pos2 (funcall aux arg))
6662 (transpose-subr-1 pos1 pos2)
6663 (goto-char (car pos2)))
6665 (setq pos1 (funcall aux -1))
6666 (goto-char (car pos1))
6667 (setq pos2 (funcall aux arg))
6668 (transpose-subr-1 pos1 pos2)
6669 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6671 (defun transpose-subr-1 (pos1 pos2)
6672 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6673 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6674 (when (> (car pos1) (car pos2))
6676 (setq pos1 pos2 pos2 swap)))
6677 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6678 (atomic-change-group
6679 ;; This sequence of insertions attempts to preserve marker
6680 ;; positions at the start and end of the transposed objects.
6681 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6682 (len1 (- (cdr pos1) (car pos1)))
6683 (len2 (length word))
6684 (boundary (make-marker)))
6685 (set-marker boundary (car pos2))
6686 (goto-char (cdr pos1))
6687 (insert-before-markers word)
6688 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6689 (goto-char boundary)
6691 (goto-char (+ boundary len1))
6692 (delete-region (point) (+ (point) len2))
6693 (set-marker boundary nil))))
6695 (defun backward-word (&optional arg)
6696 "Move backward until encountering the beginning of a word.
6697 With argument ARG, do this that many times.
6698 If ARG is omitted or nil, move point backward one word."
6700 (forward-word (- (or arg 1))))
6702 (defun mark-word (&optional arg allow-extend)
6703 "Set mark ARG words away from point.
6704 The place mark goes is the same place \\[forward-word] would
6705 move to with the same argument.
6706 Interactively, if this command is repeated
6707 or (in Transient Mark mode) if the mark is active,
6708 it marks the next ARG words after the ones already marked."
6709 (interactive "P\np")
6710 (cond ((and allow-extend
6711 (or (and (eq last-command this-command) (mark t))
6713 (setq arg (if arg (prefix-numeric-value arg)
6714 (if (< (mark) (point)) -1 1)))
6723 (forward-word (prefix-numeric-value arg))
6727 (defun kill-word (arg)
6728 "Kill characters forward until encountering the end of a word.
6729 With argument ARG, do this that many times."
6731 (kill-region (point) (progn (forward-word arg) (point))))
6733 (defun backward-kill-word (arg)
6734 "Kill characters backward until encountering the beginning of a word.
6735 With argument ARG, do this that many times."
6737 (kill-word (- arg)))
6739 (defun current-word (&optional strict really-word)
6740 "Return the symbol or word that point is on (or a nearby one) as a string.
6741 The return value includes no text properties.
6742 If optional arg STRICT is non-nil, return nil unless point is within
6743 or adjacent to a symbol or word. In all cases the value can be nil
6744 if there is no word nearby.
6745 The function, belying its name, normally finds a symbol.
6746 If optional arg REALLY-WORD is non-nil, it finds just a word."
6748 (let* ((oldpoint (point)) (start (point)) (end (point))
6749 (syntaxes (if really-word "w" "w_"))
6750 (not-syntaxes (concat "^" syntaxes)))
6751 (skip-syntax-backward syntaxes) (setq start (point))
6752 (goto-char oldpoint)
6753 (skip-syntax-forward syntaxes) (setq end (point))
6754 (when (and (eq start oldpoint) (eq end oldpoint)
6755 ;; Point is neither within nor adjacent to a word.
6757 ;; Look for preceding word in same line.
6758 (skip-syntax-backward not-syntaxes (line-beginning-position))
6760 ;; No preceding word in same line.
6761 ;; Look for following word in same line.
6763 (skip-syntax-forward not-syntaxes (line-end-position))
6764 (setq start (point))
6765 (skip-syntax-forward syntaxes)
6768 (skip-syntax-backward syntaxes)
6769 (setq start (point))))
6770 ;; If we found something nonempty, return it as a string.
6771 (unless (= start end)
6772 (buffer-substring-no-properties start end)))))
6774 (defcustom fill-prefix nil
6775 "String for filling to insert at front of new line, or nil for none."
6776 :type '(choice (const :tag "None" nil)
6779 (make-variable-buffer-local 'fill-prefix)
6780 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6782 (defcustom auto-fill-inhibit-regexp nil
6783 "Regexp to match lines which should not be auto-filled."
6784 :type '(choice (const :tag "None" nil)
6788 (defun do-auto-fill ()
6789 "The default value for `normal-auto-fill-function'.
6790 This is the default auto-fill function, some major modes use a different one.
6791 Returns t if it really did any work."
6792 (let (fc justify give-up
6793 (fill-prefix fill-prefix))
6794 (if (or (not (setq justify (current-justification)))
6795 (null (setq fc (current-fill-column)))
6796 (and (eq justify 'left)
6797 (<= (current-column) fc))
6798 (and auto-fill-inhibit-regexp
6799 (save-excursion (beginning-of-line)
6800 (looking-at auto-fill-inhibit-regexp))))
6801 nil ;; Auto-filling not required
6802 (if (memq justify '(full center right))
6803 (save-excursion (unjustify-current-line)))
6805 ;; Choose a fill-prefix automatically.
6806 (when (and adaptive-fill-mode
6807 (or (null fill-prefix) (string= fill-prefix "")))
6809 (fill-context-prefix
6810 (save-excursion (fill-forward-paragraph -1) (point))
6811 (save-excursion (fill-forward-paragraph 1) (point)))))
6812 (and prefix (not (equal prefix ""))
6813 ;; Use auto-indentation rather than a guessed empty prefix.
6814 (not (and fill-indent-according-to-mode
6815 (string-match "\\`[ \t]*\\'" prefix)))
6816 (setq fill-prefix prefix))))
6818 (while (and (not give-up) (> (current-column) fc))
6819 ;; Determine where to split the line.
6824 (setq after-prefix (point))
6826 (looking-at (regexp-quote fill-prefix))
6827 (setq after-prefix (match-end 0)))
6828 (move-to-column (1+ fc))
6829 (fill-move-to-break-point after-prefix)
6832 ;; See whether the place we found is any good.
6834 (goto-char fill-point)
6836 ;; There is no use breaking at end of line.
6837 (save-excursion (skip-chars-forward " ") (eolp))
6838 ;; It is futile to split at the end of the prefix
6839 ;; since we would just insert the prefix again.
6840 (and after-prefix (<= (point) after-prefix))
6841 ;; Don't split right after a comment starter
6842 ;; since we would just make another comment starter.
6843 (and comment-start-skip
6844 (let ((limit (point)))
6846 (and (re-search-forward comment-start-skip
6848 (eq (point) limit))))))
6849 ;; No good place to break => stop trying.
6851 ;; Ok, we have a useful place to break the line. Do it.
6852 (let ((prev-column (current-column)))
6853 ;; If point is at the fill-point, do not `save-excursion'.
6854 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6855 ;; point will end up before it rather than after it.
6857 (skip-chars-backward " \t")
6858 (= (point) fill-point))
6859 (default-indent-new-line t)
6861 (goto-char fill-point)
6862 (default-indent-new-line t)))
6863 ;; Now do justification, if required
6864 (if (not (eq justify 'left))
6867 (justify-current-line justify nil t)))
6868 ;; If making the new line didn't reduce the hpos of
6869 ;; the end of the line, then give up now;
6870 ;; trying again will not help.
6871 (if (>= (current-column) prev-column)
6872 (setq give-up t))))))
6873 ;; Justify last line.
6874 (justify-current-line justify t t)
6877 (defvar comment-line-break-function 'comment-indent-new-line
6878 "Mode-specific function which line breaks and continues a comment.
6879 This function is called during auto-filling when a comment syntax
6881 The function should take a single optional argument, which is a flag
6882 indicating whether it should use soft newlines.")
6884 (defun default-indent-new-line (&optional soft)
6885 "Break line at point and indent.
6886 If a comment syntax is defined, call `comment-indent-new-line'.
6888 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6889 unless optional argument SOFT is non-nil."
6892 (funcall comment-line-break-function soft)
6893 ;; Insert the newline before removing empty space so that markers
6894 ;; get preserved better.
6895 (if soft (insert-and-inherit ?\n) (newline 1))
6896 (save-excursion (forward-char -1) (delete-horizontal-space))
6897 (delete-horizontal-space)
6899 (if (and fill-prefix (not adaptive-fill-mode))
6900 ;; Blindly trust a non-adaptive fill-prefix.
6902 (indent-to-left-margin)
6903 (insert-before-markers-and-inherit fill-prefix))
6906 ;; If there's an adaptive prefix, use it unless we're inside
6907 ;; a comment and the prefix is not a comment starter.
6909 (indent-to-left-margin)
6910 (insert-and-inherit fill-prefix))
6911 ;; If we're not inside a comment, just try to indent.
6912 (t (indent-according-to-mode))))))
6914 (defvar normal-auto-fill-function 'do-auto-fill
6915 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6916 Some major modes set this.")
6918 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6919 ;; `functions' and `hooks' are usually unsafe to set, but setting
6920 ;; auto-fill-function to nil in a file-local setting is safe and
6921 ;; can be useful to prevent auto-filling.
6922 (put 'auto-fill-function 'safe-local-variable 'null)
6924 (define-minor-mode auto-fill-mode
6925 "Toggle automatic line breaking (Auto Fill mode).
6926 With a prefix argument ARG, enable Auto Fill mode if ARG is
6927 positive, and disable it otherwise. If called from Lisp, enable
6928 the mode if ARG is omitted or nil.
6930 When Auto Fill mode is enabled, inserting a space at a column
6931 beyond `current-fill-column' automatically breaks the line at a
6934 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6937 The value of `normal-auto-fill-function' specifies the function to use
6938 for `auto-fill-function' when turning Auto Fill mode on."
6939 :variable (auto-fill-function
6940 . (lambda (v) (setq auto-fill-function
6941 (if v normal-auto-fill-function)))))
6943 ;; This holds a document string used to document auto-fill-mode.
6944 (defun auto-fill-function ()
6945 "Automatically break line at a previous space, in insertion of text."
6948 (defun turn-on-auto-fill ()
6949 "Unconditionally turn on Auto Fill mode."
6952 (defun turn-off-auto-fill ()
6953 "Unconditionally turn off Auto Fill mode."
6954 (auto-fill-mode -1))
6956 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
6958 (defun set-fill-column (arg)
6959 "Set `fill-column' to specified argument.
6960 Use \\[universal-argument] followed by a number to specify a column.
6961 Just \\[universal-argument] as argument means to use the current column."
6963 (list (or current-prefix-arg
6964 ;; We used to use current-column silently, but C-x f is too easily
6965 ;; typed as a typo for C-x C-f, so we turned it into an error and
6966 ;; now an interactive prompt.
6967 (read-number "Set fill-column to: " (current-column)))))
6969 (setq arg (current-column)))
6970 (if (not (integerp arg))
6971 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6972 (error "set-fill-column requires an explicit argument")
6973 (message "Fill column set to %d (was %d)" arg fill-column)
6974 (setq fill-column arg)))
6976 (defun set-selective-display (arg)
6977 "Set `selective-display' to ARG; clear it if no arg.
6978 When the value of `selective-display' is a number > 0,
6979 lines whose indentation is >= that value are not displayed.
6980 The variable `selective-display' has a separate value for each buffer."
6982 (if (eq selective-display t)
6983 (error "selective-display already in use for marked lines"))
6986 (narrow-to-region (point-min) (point))
6987 (goto-char (window-start))
6988 (vertical-motion (window-height)))))
6989 (setq selective-display
6990 (and arg (prefix-numeric-value arg)))
6991 (recenter current-vpos))
6992 (set-window-start (selected-window) (window-start))
6993 (princ "selective-display set to " t)
6994 (prin1 selective-display t)
6997 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
6999 (defun toggle-truncate-lines (&optional arg)
7000 "Toggle truncating of long lines for the current buffer.
7001 When truncating is off, long lines are folded.
7002 With prefix argument ARG, truncate long lines if ARG is positive,
7003 otherwise fold them. Note that in side-by-side windows, this
7004 command has no effect if `truncate-partial-width-windows' is
7007 (setq truncate-lines
7009 (not truncate-lines)
7010 (> (prefix-numeric-value arg) 0)))
7011 (force-mode-line-update)
7012 (unless truncate-lines
7013 (let ((buffer (current-buffer)))
7014 (walk-windows (lambda (window)
7015 (if (eq buffer (window-buffer window))
7016 (set-window-hscroll window 0)))
7018 (message "Truncate long lines %s"
7019 (if truncate-lines "enabled" "disabled")))
7021 (defun toggle-word-wrap (&optional arg)
7022 "Toggle whether to use word-wrapping for continuation lines.
7023 With prefix argument ARG, wrap continuation lines at word boundaries
7024 if ARG is positive, otherwise wrap them at the right screen edge.
7025 This command toggles the value of `word-wrap'. It has no effect
7026 if long lines are truncated."
7031 (> (prefix-numeric-value arg) 0)))
7032 (force-mode-line-update)
7033 (message "Word wrapping %s"
7034 (if word-wrap "enabled" "disabled")))
7036 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7037 "The string displayed in the mode line when in overwrite mode.")
7038 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7039 "The string displayed in the mode line when in binary overwrite mode.")
7041 (define-minor-mode overwrite-mode
7042 "Toggle Overwrite mode.
7043 With a prefix argument ARG, enable Overwrite mode if ARG is
7044 positive, and disable it otherwise. If called from Lisp, enable
7045 the mode if ARG is omitted or nil.
7047 When Overwrite mode is enabled, printing characters typed in
7048 replace existing text on a one-for-one basis, rather than pushing
7049 it to the right. At the end of a line, such characters extend
7050 the line. Before a tab, such characters insert until the tab is
7051 filled in. \\[quoted-insert] still inserts characters in
7052 overwrite mode; this is supposed to make it easier to insert
7053 characters when necessary."
7054 :variable (overwrite-mode
7055 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7057 (define-minor-mode binary-overwrite-mode
7058 "Toggle Binary Overwrite mode.
7059 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7060 is positive, and disable it otherwise. If called from Lisp,
7061 enable the mode if ARG is omitted or nil.
7063 When Binary Overwrite mode is enabled, printing characters typed
7064 in replace existing text. Newlines are not treated specially, so
7065 typing at the end of a line joins the line to the next, with the
7066 typed character between them. Typing before a tab character
7067 simply replaces the tab with the character typed.
7068 \\[quoted-insert] replaces the text at the cursor, just as
7069 ordinary typing characters do.
7071 Note that Binary Overwrite mode is not its own minor mode; it is
7072 a specialization of overwrite mode, entered by setting the
7073 `overwrite-mode' variable to `overwrite-mode-binary'."
7074 :variable (overwrite-mode
7075 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7077 (define-minor-mode line-number-mode
7078 "Toggle line number display in the mode line (Line Number mode).
7079 With a prefix argument ARG, enable Line Number mode if ARG is
7080 positive, and disable it otherwise. If called from Lisp, enable
7081 the mode if ARG is omitted or nil.
7083 Line numbers do not appear for very large buffers and buffers
7084 with very long lines; see variables `line-number-display-limit'
7085 and `line-number-display-limit-width'."
7086 :init-value t :global t :group 'mode-line)
7088 (define-minor-mode column-number-mode
7089 "Toggle column number display in the mode line (Column Number mode).
7090 With a prefix argument ARG, enable Column Number mode if ARG is
7091 positive, and disable it otherwise.
7093 If called from Lisp, enable the mode if ARG is omitted or nil."
7094 :global t :group 'mode-line)
7096 (define-minor-mode size-indication-mode
7097 "Toggle buffer size display in the mode line (Size Indication mode).
7098 With a prefix argument ARG, enable Size Indication mode if ARG is
7099 positive, and disable it otherwise.
7101 If called from Lisp, enable the mode if ARG is omitted or nil."
7102 :global t :group 'mode-line)
7104 (define-minor-mode auto-save-mode
7105 "Toggle auto-saving in the current buffer (Auto Save mode).
7106 With a prefix argument ARG, enable Auto Save mode if ARG is
7107 positive, and disable it otherwise.
7109 If called from Lisp, enable the mode if ARG is omitted or nil."
7110 :variable ((and buffer-auto-save-file-name
7111 ;; If auto-save is off because buffer has shrunk,
7112 ;; then toggling should turn it on.
7113 (>= buffer-saved-size 0))
7115 (setq buffer-auto-save-file-name
7118 ((and buffer-file-name auto-save-visited-file-name
7119 (not buffer-read-only))
7121 (t (make-auto-save-file-name))))))
7122 ;; If -1 was stored here, to temporarily turn off saving,
7124 (and (< buffer-saved-size 0)
7125 (setq buffer-saved-size 0)))
7127 (defgroup paren-blinking nil
7128 "Blinking matching of parens and expressions."
7129 :prefix "blink-matching-"
7130 :group 'paren-matching)
7132 (defcustom blink-matching-paren t
7133 "Non-nil means show matching open-paren when close-paren is inserted.
7134 If t, highlight the paren. If `jump', briefly move cursor to its
7135 position. If `jump-offscreen', move cursor there even if the
7136 position is off screen. With any other non-nil value, the
7137 off-screen position of the opening paren will be shown in the
7140 (const :tag "Disable" nil)
7141 (const :tag "Highlight" t)
7142 (const :tag "Move cursor" jump)
7143 (const :tag "Move cursor, even if off screen" jump-offscreen))
7144 :group 'paren-blinking)
7146 (defcustom blink-matching-paren-on-screen t
7147 "Non-nil means show matching open-paren when it is on screen.
7148 If nil, don't show it (but the open-paren can still be shown
7149 in the echo area when it is off screen).
7151 This variable has no effect if `blink-matching-paren' is nil.
7152 \(In that case, the open-paren is never shown.)
7153 It is also ignored if `show-paren-mode' is enabled."
7155 :group 'paren-blinking)
7157 (defcustom blink-matching-paren-distance (* 100 1024)
7158 "If non-nil, maximum distance to search backwards for matching open-paren.
7159 If nil, search stops at the beginning of the accessible portion of the buffer."
7160 :version "23.2" ; 25->100k
7161 :type '(choice (const nil) integer)
7162 :group 'paren-blinking)
7164 (defcustom blink-matching-delay 1
7165 "Time in seconds to delay after showing a matching paren."
7167 :group 'paren-blinking)
7169 (defcustom blink-matching-paren-dont-ignore-comments nil
7170 "If nil, `blink-matching-paren' ignores comments.
7171 More precisely, when looking for the matching parenthesis,
7172 it skips the contents of comments that end before point."
7174 :group 'paren-blinking)
7176 (defun blink-matching-check-mismatch (start end)
7177 "Return whether or not START...END are matching parens.
7178 END is the current point and START is the blink position.
7179 START might be nil if no matching starter was found.
7180 Returns non-nil if we find there is a mismatch."
7181 (let* ((end-syntax (syntax-after (1- end)))
7182 (matching-paren (and (consp end-syntax)
7183 (eq (syntax-class end-syntax) 5)
7185 ;; For self-matched chars like " and $, we can't know when they're
7186 ;; mismatched or unmatched, so we can only do it for parens.
7187 (when matching-paren
7190 (eq (char-after start) matching-paren)
7191 ;; The cdr might hold a new paren-class info rather than
7192 ;; a matching-char info, in which case the two CDRs
7194 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7196 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7197 "Function to check parentheses mismatches.
7198 The function takes two arguments (START and END) where START is the
7199 position just before the opening token and END is the position right after.
7200 START can be nil, if it was not found.
7201 The function should return non-nil if the two tokens do not match.")
7203 (defvar blink-matching--overlay
7204 (let ((ol (make-overlay (point) (point) nil t)))
7205 (overlay-put ol 'face 'show-paren-match)
7208 "Overlay used to highlight the matching paren.")
7210 (defun blink-matching-open ()
7211 "Momentarily highlight the beginning of the sexp before point."
7213 (when (and (not (bobp))
7214 blink-matching-paren)
7215 (let* ((oldpos (point))
7216 (message-log-max nil) ; Don't log messages about paren matching.
7220 (if blink-matching-paren-distance
7222 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7223 (- (point) blink-matching-paren-distance))
7225 (let ((parse-sexp-ignore-comments
7226 (and parse-sexp-ignore-comments
7227 (not blink-matching-paren-dont-ignore-comments))))
7230 (syntax-propertize (point))
7232 ;; backward-sexp skips backward over prefix chars,
7233 ;; so move back to the matching paren.
7234 (while (and (< (point) (1- oldpos))
7235 (let ((code (syntax-after (point))))
7236 (or (eq (syntax-class code) 6)
7237 (eq (logand 1048576 (car code))
7242 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7247 (minibuffer-message "Mismatched parentheses")
7248 (message "Mismatched parentheses"))
7250 (minibuffer-message "No matching parenthesis found")
7251 (message "No matching parenthesis found"))))
7252 ((not blinkpos) nil)
7254 (eq blink-matching-paren 'jump-offscreen)
7255 (pos-visible-in-window-p blinkpos))
7256 ;; Matching open within window, temporarily move to or highlight
7257 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7259 (and blink-matching-paren-on-screen
7260 (not show-paren-mode)
7261 (if (memq blink-matching-paren '(jump jump-offscreen))
7263 (goto-char blinkpos)
7264 (sit-for blink-matching-delay))
7267 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7269 (sit-for blink-matching-delay))
7270 (delete-overlay blink-matching--overlay)))))
7272 (let ((open-paren-line-string
7274 (goto-char blinkpos)
7275 ;; Show what precedes the open in its line, if anything.
7277 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7278 (buffer-substring (line-beginning-position)
7280 ;; Show what follows the open in its line, if anything.
7283 (skip-chars-forward " \t")
7285 (buffer-substring blinkpos
7286 (line-end-position)))
7287 ;; Otherwise show the previous nonblank line,
7289 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7291 (buffer-substring (progn
7292 (skip-chars-backward "\n \t")
7293 (line-beginning-position))
7294 (progn (end-of-line)
7295 (skip-chars-backward " \t")
7297 ;; Replace the newline and other whitespace with `...'.
7299 (buffer-substring blinkpos (1+ blinkpos))))
7300 ;; There is nothing to show except the char itself.
7301 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7304 (substring-no-properties open-paren-line-string))))))))
7306 (defvar blink-paren-function 'blink-matching-open
7307 "Function called, if non-nil, whenever a close parenthesis is inserted.
7308 More precisely, a char with closeparen syntax is self-inserted.")
7310 (defun blink-paren-post-self-insert-function ()
7311 (when (and (eq (char-before) last-command-event) ; Sanity check.
7312 (memq (char-syntax last-command-event) '(?\) ?\$))
7313 blink-paren-function
7314 (not executing-kbd-macro)
7315 (not noninteractive)
7316 ;; Verify an even number of quoting characters precede the close.
7317 ;; FIXME: Also check if this parenthesis closes a comment as
7318 ;; can happen in Pascal and SML.
7319 (= 1 (logand 1 (- (point)
7322 (skip-syntax-backward "/\\")
7324 (funcall blink-paren-function)))
7326 (put 'blink-paren-post-self-insert-function 'priority 100)
7328 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7329 ;; Most likely, this hook is nil, so this arg doesn't matter,
7330 ;; but I use it as a reminder that this function usually
7331 ;; likes to be run after others since it does
7332 ;; `sit-for'. That's also the reason it get a `priority' prop
7336 ;; This executes C-g typed while Emacs is waiting for a command.
7337 ;; Quitting out of a program does not go through here;
7338 ;; that happens in the QUIT macro at the C code level.
7339 (defun keyboard-quit ()
7340 "Signal a `quit' condition.
7341 During execution of Lisp code, this character causes a quit directly.
7342 At top-level, as an editor command, this simply beeps."
7344 ;; Avoid adding the region to the window selection.
7345 (setq saved-region-selection nil)
7346 (let (select-active-regions)
7348 (if (fboundp 'kmacro-keyboard-quit)
7349 (kmacro-keyboard-quit))
7350 (when completion-in-region-mode
7351 (completion-in-region-mode -1))
7352 ;; Force the next redisplay cycle to remove the "Def" indicator from
7353 ;; all the mode lines.
7354 (if defining-kbd-macro
7355 (force-mode-line-update t))
7356 (setq defining-kbd-macro nil)
7357 (let ((debug-on-quit nil))
7358 (signal 'quit nil)))
7360 (defvar buffer-quit-function nil
7361 "Function to call to \"quit\" the current buffer, or nil if none.
7362 \\[keyboard-escape-quit] calls this function when its more local actions
7363 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7365 (defun keyboard-escape-quit ()
7366 "Exit the current \"mode\" (in a generalized sense of the word).
7367 This command can exit an interactive command such as `query-replace',
7368 can clear out a prefix argument or a region,
7369 can get out of the minibuffer or other recursive edit,
7370 cancel the use of the current buffer (for special-purpose buffers),
7371 or go back to just one window (by deleting all but the selected window)."
7373 (cond ((eq last-command 'mode-exited) nil)
7376 ((> (minibuffer-depth) 0)
7377 (abort-recursive-edit))
7380 ((> (recursion-depth) 0)
7381 (exit-recursive-edit))
7382 (buffer-quit-function
7383 (funcall buffer-quit-function))
7384 ((not (one-window-p t))
7385 (delete-other-windows))
7386 ((string-match "^ \\*" (buffer-name (current-buffer)))
7389 (defun play-sound-file (file &optional volume device)
7390 "Play sound stored in FILE.
7391 VOLUME and DEVICE correspond to the keywords of the sound
7392 specification for `play-sound'."
7393 (interactive "fPlay sound file: ")
7394 (let ((sound (list :file file)))
7396 (plist-put sound :volume volume))
7398 (plist-put sound :device device))
7400 (play-sound sound)))
7403 (defcustom read-mail-command 'rmail
7404 "Your preference for a mail reading package.
7405 This is used by some keybindings which support reading mail.
7406 See also `mail-user-agent' concerning sending mail."
7407 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7408 (function-item :tag "Gnus" :format "%t\n" gnus)
7409 (function-item :tag "Emacs interface to MH"
7410 :format "%t\n" mh-rmail)
7411 (function :tag "Other"))
7415 (defcustom mail-user-agent 'message-user-agent
7416 "Your preference for a mail composition package.
7417 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7418 outgoing email message. This variable lets you specify which
7419 mail-sending package you prefer.
7421 Valid values include:
7423 `message-user-agent' -- use the Message package.
7424 See Info node `(message)'.
7425 `sendmail-user-agent' -- use the Mail package.
7426 See Info node `(emacs)Sending Mail'.
7427 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7428 See Info node `(mh-e)'.
7429 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7430 paraphernalia if Gnus is running, particularly
7431 the Gcc: header for archiving.
7433 Additional valid symbols may be available; check with the author of
7434 your package for details. The function should return non-nil if it
7437 See also `read-mail-command' concerning reading mail."
7438 :type '(radio (function-item :tag "Message package"
7441 (function-item :tag "Mail package"
7443 sendmail-user-agent)
7444 (function-item :tag "Emacs interface to MH"
7447 (function-item :tag "Message with full Gnus features"
7450 (function :tag "Other"))
7451 :version "23.2" ; sendmail->message
7454 (defcustom compose-mail-user-agent-warnings t
7455 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7456 If the value of `mail-user-agent' is the default, and the user
7457 appears to have customizations applying to the old default,
7458 `compose-mail' issues a warning."
7463 (defun rfc822-goto-eoh ()
7464 "If the buffer starts with a mail header, move point to the header's end.
7465 Otherwise, moves to `point-min'.
7466 The end of the header is the start of the next line, if there is one,
7467 else the end of the last line. This function obeys RFC822."
7468 (goto-char (point-min))
7469 (when (re-search-forward
7470 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7471 (goto-char (match-beginning 0))))
7473 ;; Used by Rmail (e.g., rmail-forward).
7474 (defvar mail-encode-mml nil
7475 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7476 the outgoing message before sending it.")
7478 (defun compose-mail (&optional to subject other-headers continue
7479 switch-function yank-action send-actions
7481 "Start composing a mail message to send.
7482 This uses the user's chosen mail composition package
7483 as selected with the variable `mail-user-agent'.
7484 The optional arguments TO and SUBJECT specify recipients
7485 and the initial Subject field, respectively.
7487 OTHER-HEADERS is an alist specifying additional
7488 header fields. Elements look like (HEADER . VALUE) where both
7489 HEADER and VALUE are strings.
7491 CONTINUE, if non-nil, says to continue editing a message already
7492 being composed. Interactively, CONTINUE is the prefix argument.
7494 SWITCH-FUNCTION, if non-nil, is a function to use to
7495 switch to and display the buffer used for mail composition.
7497 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7498 to insert the raw text of the message being replied to.
7499 It has the form (FUNCTION . ARGS). The user agent will apply
7500 FUNCTION to ARGS, to insert the raw text of the original message.
7501 \(The user agent will also run `mail-citation-hook', *after* the
7502 original text has been inserted in this way.)
7504 SEND-ACTIONS is a list of actions to call when the message is sent.
7505 Each action has the form (FUNCTION . ARGS).
7507 RETURN-ACTION, if non-nil, is an action for returning to the
7508 caller. It has the form (FUNCTION . ARGS). The function is
7509 called after the mail has been sent or put aside, and the mail
7512 (list nil nil nil current-prefix-arg))
7514 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7515 ;; from sendmail-user-agent to message-user-agent. Some users may
7516 ;; encounter incompatibilities. This hack tries to detect problems
7517 ;; and warn about them.
7518 (and compose-mail-user-agent-warnings
7519 (eq mail-user-agent 'message-user-agent)
7521 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7522 mail-yank-hooks mail-archive-file-name
7523 mail-default-reply-to mail-mailing-lists
7527 (push var warn-vars)))
7529 (display-warning 'mail
7531 The default mail mode is now Message mode.
7532 You have the following Mail mode variable%s customized:
7533 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7534 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7535 (if (> (length warn-vars) 1) "s" "")
7536 (mapconcat 'symbol-name
7539 (let ((function (get mail-user-agent 'composefunc)))
7540 (funcall function to subject other-headers continue switch-function
7541 yank-action send-actions return-action)))
7543 (defun compose-mail-other-window (&optional to subject other-headers continue
7544 yank-action send-actions
7546 "Like \\[compose-mail], but edit the outgoing message in another window."
7547 (interactive (list nil nil nil current-prefix-arg))
7548 (compose-mail to subject other-headers continue
7549 'switch-to-buffer-other-window yank-action send-actions
7552 (defun compose-mail-other-frame (&optional to subject other-headers continue
7553 yank-action send-actions
7555 "Like \\[compose-mail], but edit the outgoing message in another frame."
7556 (interactive (list nil nil nil current-prefix-arg))
7557 (compose-mail to subject other-headers continue
7558 'switch-to-buffer-other-frame yank-action send-actions
7562 (defvar set-variable-value-history nil
7563 "History of values entered with `set-variable'.
7565 Maximum length of the history list is determined by the value
7566 of `history-length', which see.")
7568 (defun set-variable (variable value &optional make-local)
7569 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7570 VARIABLE should be a user option variable name, a Lisp variable
7571 meant to be customized by users. You should enter VALUE in Lisp syntax,
7572 so if you want VALUE to be a string, you must surround it with doublequotes.
7573 VALUE is used literally, not evaluated.
7575 If VARIABLE has a `variable-interactive' property, that is used as if
7576 it were the arg to `interactive' (which see) to interactively read VALUE.
7578 If VARIABLE has been defined with `defcustom', then the type information
7579 in the definition is used to check that VALUE is valid.
7581 Note that this function is at heart equivalent to the basic `set' function.
7582 For a variable defined with `defcustom', it does not pay attention to
7583 any :set property that the variable might have (if you want that, use
7584 \\[customize-set-variable] instead).
7586 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7588 (let* ((default-var (variable-at-point))
7589 (var (if (custom-variable-p default-var)
7590 (read-variable (format "Set variable (default %s): " default-var)
7592 (read-variable "Set variable: ")))
7593 (minibuffer-help-form '(describe-variable var))
7594 (prop (get var 'variable-interactive))
7595 (obsolete (car (get var 'byte-obsolete-variable)))
7596 (prompt (format "Set %s %s to value: " var
7597 (cond ((local-variable-p var)
7599 ((or current-prefix-arg
7600 (local-variable-if-set-p var))
7605 (message (concat "`%S' is obsolete; "
7606 (if (symbolp obsolete) "use `%S' instead" "%s"))
7610 ;; Use VAR's `variable-interactive' property
7611 ;; as an interactive spec for prompting.
7612 (call-interactively `(lambda (arg)
7615 (read-from-minibuffer prompt nil
7616 read-expression-map t
7617 'set-variable-value-history
7618 (format "%S" (symbol-value var)))))))
7619 (list var val current-prefix-arg)))
7621 (and (custom-variable-p variable)
7622 (not (get variable 'custom-type))
7623 (custom-load-symbol variable))
7624 (let ((type (get variable 'custom-type)))
7626 ;; Match with custom type.
7628 (setq type (widget-convert type))
7629 (unless (widget-apply type :match value)
7630 (user-error "Value `%S' does not match type %S of %S"
7631 value (car type) variable))))
7634 (make-local-variable variable))
7636 (set variable value)
7638 ;; Force a thorough redisplay for the case that the variable
7639 ;; has an effect on the display, like `tab-width' has.
7640 (force-mode-line-update))
7642 ;; Define the major mode for lists of completions.
7644 (defvar completion-list-mode-map
7645 (let ((map (make-sparse-keymap)))
7646 (define-key map [mouse-2] 'choose-completion)
7647 (define-key map [follow-link] 'mouse-face)
7648 (define-key map [down-mouse-2] nil)
7649 (define-key map "\C-m" 'choose-completion)
7650 (define-key map "\e\e\e" 'delete-completion-window)
7651 (define-key map [left] 'previous-completion)
7652 (define-key map [right] 'next-completion)
7653 (define-key map [?\t] 'next-completion)
7654 (define-key map [backtab] 'previous-completion)
7655 (define-key map "q" 'quit-window)
7656 (define-key map "z" 'kill-this-buffer)
7658 "Local map for completion list buffers.")
7660 ;; Completion mode is suitable only for specially formatted data.
7661 (put 'completion-list-mode 'mode-class 'special)
7663 (defvar completion-reference-buffer nil
7664 "Record the buffer that was current when the completion list was requested.
7665 This is a local variable in the completion list buffer.
7666 Initial value is nil to avoid some compiler warnings.")
7668 (defvar completion-no-auto-exit nil
7669 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7670 This also applies to other functions such as `choose-completion'.")
7672 (defvar completion-base-position nil
7673 "Position of the base of the text corresponding to the shown completions.
7674 This variable is used in the *Completions* buffers.
7675 Its value is a list of the form (START END) where START is the place
7676 where the completion should be inserted and END (if non-nil) is the end
7677 of the text to replace. If END is nil, point is used instead.")
7679 (defvar completion-list-insert-choice-function #'completion--replace
7680 "Function to use to insert the text chosen in *Completions*.
7681 Called with three arguments (BEG END TEXT), it should replace the text
7682 between BEG and END with TEXT. Expected to be set buffer-locally
7683 in the *Completions* buffer.")
7685 (defvar completion-base-size nil
7686 "Number of chars before point not involved in completion.
7687 This is a local variable in the completion list buffer.
7688 It refers to the chars in the minibuffer if completing in the
7689 minibuffer, or in `completion-reference-buffer' otherwise.
7690 Only characters in the field at point are included.
7692 If nil, Emacs determines which part of the tail end of the
7693 buffer's text is involved in completion by comparing the text
7695 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7697 (defun delete-completion-window ()
7698 "Delete the completion list window.
7699 Go to the window from which completion was requested."
7701 (let ((buf completion-reference-buffer))
7702 (if (one-window-p t)
7703 (if (window-dedicated-p) (delete-frame))
7704 (delete-window (selected-window))
7705 (if (get-buffer-window buf)
7706 (select-window (get-buffer-window buf))))))
7708 (defun previous-completion (n)
7709 "Move to the previous item in the completion list."
7711 (next-completion (- n)))
7713 (defun next-completion (n)
7714 "Move to the next item in the completion list.
7715 With prefix argument N, move N items (negative N means move backward)."
7717 (let ((beg (point-min)) (end (point-max)))
7718 (while (and (> n 0) (not (eobp)))
7719 ;; If in a completion, move to the end of it.
7720 (when (get-text-property (point) 'mouse-face)
7721 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7722 ;; Move to start of next one.
7723 (unless (get-text-property (point) 'mouse-face)
7724 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7726 (while (and (< n 0) (not (bobp)))
7727 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7728 ;; If in a completion, move to the start of it.
7729 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7730 (goto-char (previous-single-property-change
7731 (point) 'mouse-face nil beg)))
7732 ;; Move to end of the previous completion.
7733 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7734 (goto-char (previous-single-property-change
7735 (point) 'mouse-face nil beg)))
7736 ;; Move to the start of that one.
7737 (goto-char (previous-single-property-change
7738 (point) 'mouse-face nil beg))
7741 (defun choose-completion (&optional event)
7742 "Choose the completion at point.
7743 If EVENT, use EVENT's position to determine the starting position."
7744 (interactive (list last-nonmenu-event))
7745 ;; In case this is run via the mouse, give temporary modes such as
7746 ;; isearch a chance to turn off.
7747 (run-hooks 'mouse-leave-buffer-hook)
7748 (with-current-buffer (window-buffer (posn-window (event-start event)))
7749 (let ((buffer completion-reference-buffer)
7750 (base-size completion-base-size)
7751 (base-position completion-base-position)
7752 (insert-function completion-list-insert-choice-function)
7755 (goto-char (posn-point (event-start event)))
7758 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7759 (setq end (point) beg (1+ (point))))
7761 (get-text-property (1- (point)) 'mouse-face))
7762 (setq end (1- (point)) beg (point)))
7763 (t (error "No completion here")))
7764 (setq beg (previous-single-property-change beg 'mouse-face))
7765 (setq end (or (next-single-property-change end 'mouse-face)
7767 (buffer-substring-no-properties beg end)))))
7769 (unless (buffer-live-p buffer)
7770 (error "Destination buffer is dead"))
7771 (quit-window nil (posn-window (event-start event)))
7773 (with-current-buffer buffer
7774 (choose-completion-string
7778 ;; Someone's using old completion code that doesn't know
7779 ;; about base-position yet.
7780 (list (+ base-size (field-beginning))))
7781 ;; If all else fails, just guess.
7782 (list (choose-completion-guess-base-position choice)))
7783 insert-function)))))
7785 ;; Delete the longest partial match for STRING
7786 ;; that can be found before POINT.
7787 (defun choose-completion-guess-base-position (string)
7789 (let ((opoint (point))
7791 ;; Try moving back by the length of the string.
7792 (goto-char (max (- (point) (length string))
7793 (minibuffer-prompt-end)))
7794 ;; See how far back we were actually able to move. That is the
7795 ;; upper bound on how much we can match and delete.
7796 (setq len (- opoint (point)))
7797 (if completion-ignore-case
7798 (setq string (downcase string)))
7799 (while (and (> len 0)
7800 (let ((tail (buffer-substring (point) opoint)))
7801 (if completion-ignore-case
7802 (setq tail (downcase tail)))
7803 (not (string= tail (substring string 0 len)))))
7808 (defun choose-completion-delete-max-match (string)
7809 (declare (obsolete choose-completion-guess-base-position "23.2"))
7810 (delete-region (choose-completion-guess-base-position string) (point)))
7812 (defvar choose-completion-string-functions nil
7813 "Functions that may override the normal insertion of a completion choice.
7814 These functions are called in order with three arguments:
7815 CHOICE - the string to insert in the buffer,
7816 BUFFER - the buffer in which the choice should be inserted,
7817 BASE-POSITION - where to insert the completion.
7819 If a function in the list returns non-nil, that function is supposed
7820 to have inserted the CHOICE in the BUFFER, and possibly exited
7821 the minibuffer; no further functions will be called.
7823 If all functions in the list return nil, that means to use
7824 the default method of inserting the completion in BUFFER.")
7826 (defun choose-completion-string (choice &optional
7827 buffer base-position insert-function)
7828 "Switch to BUFFER and insert the completion choice CHOICE.
7829 BASE-POSITION says where to insert the completion.
7830 INSERT-FUNCTION says how to insert the completion and falls
7831 back on `completion-list-insert-choice-function' when nil."
7833 ;; If BUFFER is the minibuffer, exit the minibuffer
7834 ;; unless it is reading a file name and CHOICE is a directory,
7835 ;; or completion-no-auto-exit is non-nil.
7837 ;; Some older code may call us passing `base-size' instead of
7838 ;; `base-position'. It's difficult to make any use of `base-size',
7839 ;; so we just ignore it.
7840 (unless (consp base-position)
7841 (message "Obsolete `base-size' passed to choose-completion-string")
7842 (setq base-position nil))
7844 (let* ((buffer (or buffer completion-reference-buffer))
7845 (mini-p (minibufferp buffer)))
7846 ;; If BUFFER is a minibuffer, barf unless it's the currently
7847 ;; active minibuffer.
7849 (not (and (active-minibuffer-window)
7851 (window-buffer (active-minibuffer-window))))))
7852 (error "Minibuffer is not active for completion")
7853 ;; Set buffer so buffer-local choose-completion-string-functions works.
7855 (unless (run-hook-with-args-until-success
7856 'choose-completion-string-functions
7857 ;; The fourth arg used to be `mini-p' but was useless
7858 ;; (since minibufferp can be used on the `buffer' arg)
7859 ;; and indeed unused. The last used to be `base-size', so we
7860 ;; keep it to try and avoid breaking old code.
7861 choice buffer base-position nil)
7862 ;; This remove-text-properties should be unnecessary since `choice'
7863 ;; comes from buffer-substring-no-properties.
7864 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7865 ;; Insert the completion into the buffer where it was requested.
7866 (funcall (or insert-function completion-list-insert-choice-function)
7867 (or (car base-position) (point))
7868 (or (cadr base-position) (point))
7870 ;; Update point in the window that BUFFER is showing in.
7871 (let ((window (get-buffer-window buffer t)))
7872 (set-window-point window (point)))
7873 ;; If completing for the minibuffer, exit it with this choice.
7874 (and (not completion-no-auto-exit)
7875 (minibufferp buffer)
7876 minibuffer-completion-table
7877 ;; If this is reading a file name, and the file name chosen
7878 ;; is a directory, don't exit the minibuffer.
7879 (let* ((result (buffer-substring (field-beginning) (point)))
7881 (completion-boundaries result minibuffer-completion-table
7882 minibuffer-completion-predicate
7884 (if (eq (car bounds) (length result))
7885 ;; The completion chosen leads to a new set of completions
7886 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7887 (let ((mini (active-minibuffer-window)))
7888 (select-window mini)
7889 (when minibuffer-auto-raise
7890 (raise-frame (window-frame mini))))
7891 (exit-minibuffer))))))))
7893 (define-derived-mode completion-list-mode nil "Completion List"
7894 "Major mode for buffers showing lists of possible completions.
7895 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7896 to select the completion near point.
7897 Or click to select one with the mouse.
7899 \\{completion-list-mode-map}"
7900 (set (make-local-variable 'completion-base-size) nil))
7902 (defun completion-list-mode-finish ()
7903 "Finish setup of the completions buffer.
7904 Called from `temp-buffer-show-hook'."
7905 (when (eq major-mode 'completion-list-mode)
7906 (setq buffer-read-only t)))
7908 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7911 ;; Variables and faces used in `completion-setup-function'.
7913 (defcustom completion-show-help t
7914 "Non-nil means show help message in *Completions* buffer."
7919 ;; This function goes in completion-setup-hook, so that it is called
7920 ;; after the text of the completion list buffer is written.
7921 (defun completion-setup-function ()
7922 (let* ((mainbuf (current-buffer))
7924 ;; FIXME: This is a bad hack. We try to set the default-directory
7925 ;; in the *Completions* buffer so that the relative file names
7926 ;; displayed there can be treated as valid file names, independently
7927 ;; from the completion context. But this suffers from many problems:
7928 ;; - It's not clear when the completions are file names. With some
7929 ;; completion tables (e.g. bzr revision specs), the listed
7930 ;; completions can mix file names and other things.
7931 ;; - It doesn't pay attention to possible quoting.
7932 ;; - With fancy completion styles, the code below will not always
7933 ;; find the right base directory.
7934 (if minibuffer-completing-file-name
7935 (file-name-as-directory
7937 (buffer-substring (minibuffer-prompt-end)
7938 (- (point) (or completion-base-size 0))))))))
7939 (with-current-buffer standard-output
7940 (let ((base-size completion-base-size) ;Read before killing localvars.
7941 (base-position completion-base-position)
7942 (insert-fun completion-list-insert-choice-function))
7943 (completion-list-mode)
7944 (set (make-local-variable 'completion-base-size) base-size)
7945 (set (make-local-variable 'completion-base-position) base-position)
7946 (set (make-local-variable 'completion-list-insert-choice-function)
7948 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7949 (if base-dir (setq default-directory base-dir))
7950 ;; Maybe insert help string.
7951 (when completion-show-help
7952 (goto-char (point-min))
7953 (if (display-mouse-p)
7954 (insert "Click on a completion to select it.\n"))
7955 (insert (substitute-command-keys
7956 "In this buffer, type \\[choose-completion] to \
7957 select the completion near point.\n\n"))))))
7959 (add-hook 'completion-setup-hook 'completion-setup-function)
7961 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7962 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7964 (defun switch-to-completions ()
7965 "Select the completion list window."
7967 (let ((window (or (get-buffer-window "*Completions*" 0)
7968 ;; Make sure we have a completions window.
7969 (progn (minibuffer-completion-help)
7970 (get-buffer-window "*Completions*" 0)))))
7972 (select-window window)
7973 ;; In the new buffer, go to the first completion.
7974 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
7976 (next-completion 1)))))
7978 ;;; Support keyboard commands to turn on various modifiers.
7980 ;; These functions -- which are not commands -- each add one modifier
7981 ;; to the following event.
7983 (defun event-apply-alt-modifier (_ignore-prompt)
7984 "\\<function-key-map>Add the Alt modifier to the following event.
7985 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
7986 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
7987 (defun event-apply-super-modifier (_ignore-prompt)
7988 "\\<function-key-map>Add the Super modifier to the following event.
7989 For example, type \\[event-apply-super-modifier] & to enter Super-&."
7990 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
7991 (defun event-apply-hyper-modifier (_ignore-prompt)
7992 "\\<function-key-map>Add the Hyper modifier to the following event.
7993 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
7994 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
7995 (defun event-apply-shift-modifier (_ignore-prompt)
7996 "\\<function-key-map>Add the Shift modifier to the following event.
7997 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
7998 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
7999 (defun event-apply-control-modifier (_ignore-prompt)
8000 "\\<function-key-map>Add the Ctrl modifier to the following event.
8001 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8002 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8003 (defun event-apply-meta-modifier (_ignore-prompt)
8004 "\\<function-key-map>Add the Meta modifier to the following event.
8005 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8006 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8008 (defun event-apply-modifier (event symbol lshiftby prefix)
8009 "Apply a modifier flag to event EVENT.
8010 SYMBOL is the name of this modifier, as a symbol.
8011 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8012 PREFIX is the string that represents this modifier in an event type symbol."
8014 (cond ((eq symbol 'control)
8015 (if (and (<= (downcase event) ?z)
8016 (>= (downcase event) ?a))
8017 (- (downcase event) ?a -1)
8018 (if (and (<= (downcase event) ?Z)
8019 (>= (downcase event) ?A))
8020 (- (downcase event) ?A -1)
8021 (logior (lsh 1 lshiftby) event))))
8023 (if (and (<= (downcase event) ?z)
8024 (>= (downcase event) ?a))
8026 (logior (lsh 1 lshiftby) event)))
8028 (logior (lsh 1 lshiftby) event)))
8029 (if (memq symbol (event-modifiers event))
8031 (let ((event-type (if (symbolp event) event (car event))))
8032 (setq event-type (intern (concat prefix (symbol-name event-type))))
8035 (cons event-type (cdr event)))))))
8037 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8038 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8039 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8040 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8041 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8042 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8044 ;;;; Keypad support.
8046 ;; Make the keypad keys act like ordinary typing keys. If people add
8047 ;; bindings for the function key symbols, then those bindings will
8048 ;; override these, so this shouldn't interfere with any existing
8051 ;; Also tell read-char how to handle these keys.
8053 (lambda (keypad-normal)
8054 (let ((keypad (nth 0 keypad-normal))
8055 (normal (nth 1 keypad-normal)))
8056 (put keypad 'ascii-character normal)
8057 (define-key function-key-map (vector keypad) (vector normal))))
8058 ;; See also kp-keys bound in bindings.el.
8064 ;; Do the same for various keys that are represented as symbols under
8065 ;; GUIs but naturally correspond to characters.
8076 ;;;; forking a twin copy of a buffer.
8079 (defvar clone-buffer-hook nil
8080 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8082 (defvar clone-indirect-buffer-hook nil
8083 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8085 (defun clone-process (process &optional newname)
8086 "Create a twin copy of PROCESS.
8087 If NEWNAME is nil, it defaults to PROCESS' name;
8088 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8089 If PROCESS is associated with a buffer, the new process will be associated
8090 with the current buffer instead.
8091 Returns nil if PROCESS has already terminated."
8092 (setq newname (or newname (process-name process)))
8093 (if (string-match "<[0-9]+>\\'" newname)
8094 (setq newname (substring newname 0 (match-beginning 0))))
8095 (when (memq (process-status process) '(run stop open))
8096 (let* ((process-connection-type (process-tty-name process))
8098 (if (memq (process-status process) '(open))
8099 (let ((args (process-contact process t)))
8100 (setq args (plist-put args :name newname))
8101 (setq args (plist-put args :buffer
8102 (if (process-buffer process)
8104 (apply 'make-network-process args))
8105 (apply 'start-process newname
8106 (if (process-buffer process) (current-buffer))
8107 (process-command process)))))
8108 (set-process-query-on-exit-flag
8109 new-process (process-query-on-exit-flag process))
8110 (set-process-inherit-coding-system-flag
8111 new-process (process-inherit-coding-system-flag process))
8112 (set-process-filter new-process (process-filter process))
8113 (set-process-sentinel new-process (process-sentinel process))
8114 (set-process-plist new-process (copy-sequence (process-plist process)))
8117 ;; things to maybe add (currently partly covered by `funcall mode'):
8120 (defun clone-buffer (&optional newname display-flag)
8121 "Create and return a twin copy of the current buffer.
8122 Unlike an indirect buffer, the new buffer can be edited
8123 independently of the old one (if it is not read-only).
8124 NEWNAME is the name of the new buffer. It may be modified by
8125 adding or incrementing <N> at the end as necessary to create a
8126 unique buffer name. If nil, it defaults to the name of the
8127 current buffer, with the proper suffix. If DISPLAY-FLAG is
8128 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8129 clone a file-visiting buffer, or a buffer whose major mode symbol
8130 has a non-nil `no-clone' property, results in an error.
8132 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8133 current buffer with appropriate suffix. However, if a prefix
8134 argument is given, then the command prompts for NEWNAME in the
8137 This runs the normal hook `clone-buffer-hook' in the new buffer
8138 after it has been set up properly in other respects."
8141 (if buffer-file-name
8142 (error "Cannot clone a file-visiting buffer"))
8143 (if (get major-mode 'no-clone)
8144 (error "Cannot clone a buffer in %s mode" mode-name))
8145 (list (if current-prefix-arg
8146 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8148 (if buffer-file-name
8149 (error "Cannot clone a file-visiting buffer"))
8150 (if (get major-mode 'no-clone)
8151 (error "Cannot clone a buffer in %s mode" mode-name))
8152 (setq newname (or newname (buffer-name)))
8153 (if (string-match "<[0-9]+>\\'" newname)
8154 (setq newname (substring newname 0 (match-beginning 0))))
8155 (let ((buf (current-buffer))
8159 (mk (if mark-active (mark t)))
8160 (modified (buffer-modified-p))
8162 (lvars (buffer-local-variables))
8163 (process (get-buffer-process (current-buffer)))
8164 (new (generate-new-buffer (or newname (buffer-name)))))
8167 (with-current-buffer new
8168 (insert-buffer-substring buf)))
8169 (with-current-buffer new
8170 (narrow-to-region ptmin ptmax)
8172 (if mk (set-mark mk))
8173 (set-buffer-modified-p modified)
8175 ;; Clone the old buffer's process, if any.
8176 (when process (clone-process process))
8178 ;; Now set up the major mode.
8181 ;; Set up other local variables.
8183 (condition-case () ;in case var is read-only
8186 (set (make-local-variable (car v)) (cdr v)))
8190 ;; Run any hooks (typically set up by the major mode
8191 ;; for cloning to work properly).
8192 (run-hooks 'clone-buffer-hook))
8194 ;; Presumably the current buffer is shown in the selected frame, so
8195 ;; we want to display the clone elsewhere.
8196 (let ((same-window-regexps nil)
8197 (same-window-buffer-names))
8198 (pop-to-buffer new)))
8202 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8203 "Create an indirect buffer that is a twin copy of the current buffer.
8205 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8206 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8207 or if not called with a prefix arg, NEWNAME defaults to the current
8208 buffer's name. The name is modified by adding a `<N>' suffix to it
8209 or by incrementing the N in an existing suffix. Trying to clone a
8210 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8211 property results in an error.
8213 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8214 This is always done when called interactively.
8216 Optional third arg NORECORD non-nil means do not put this buffer at the
8217 front of the list of recently selected ones.
8219 Returns the newly created indirect buffer."
8222 (if (get major-mode 'no-clone-indirect)
8223 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8224 (list (if current-prefix-arg
8225 (read-buffer "Name of indirect buffer: " (current-buffer)))
8227 (if (get major-mode 'no-clone-indirect)
8228 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8229 (setq newname (or newname (buffer-name)))
8230 (if (string-match "<[0-9]+>\\'" newname)
8231 (setq newname (substring newname 0 (match-beginning 0))))
8232 (let* ((name (generate-new-buffer-name newname))
8233 (buffer (make-indirect-buffer (current-buffer) name t)))
8234 (with-current-buffer buffer
8235 (run-hooks 'clone-indirect-buffer-hook))
8237 (pop-to-buffer buffer norecord))
8241 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8242 "Like `clone-indirect-buffer' but display in another window."
8245 (if (get major-mode 'no-clone-indirect)
8246 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8247 (list (if current-prefix-arg
8248 (read-buffer "Name of indirect buffer: " (current-buffer)))
8250 (let ((pop-up-windows t))
8251 (clone-indirect-buffer newname display-flag norecord)))
8254 ;;; Handling of Backspace and Delete keys.
8256 (defcustom normal-erase-is-backspace 'maybe
8257 "Set the default behavior of the Delete and Backspace keys.
8259 If set to t, Delete key deletes forward and Backspace key deletes
8262 If set to nil, both Delete and Backspace keys delete backward.
8264 If set to `maybe' (which is the default), Emacs automatically
8265 selects a behavior. On window systems, the behavior depends on
8266 the keyboard used. If the keyboard has both a Backspace key and
8267 a Delete key, and both are mapped to their usual meanings, the
8268 option's default value is set to t, so that Backspace can be used
8269 to delete backward, and Delete can be used to delete forward.
8271 If not running under a window system, customizing this option
8272 accomplishes a similar effect by mapping C-h, which is usually
8273 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8274 via `keyboard-translate'. The former functionality of C-h is
8275 available on the F1 key. You should probably not use this
8276 setting if you don't have both Backspace, Delete and F1 keys.
8278 Setting this variable with setq doesn't take effect. Programmatically,
8279 call `normal-erase-is-backspace-mode' (which see) instead."
8280 :type '(choice (const :tag "Off" nil)
8281 (const :tag "Maybe" maybe)
8282 (other :tag "On" t))
8283 :group 'editing-basics
8285 :set (lambda (symbol value)
8286 ;; The fboundp is because of a problem with :set when
8287 ;; dumping Emacs. It doesn't really matter.
8288 (if (fboundp 'normal-erase-is-backspace-mode)
8289 (normal-erase-is-backspace-mode (or value 0))
8290 (set-default symbol value))))
8292 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8293 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8294 (unless frame (setq frame (selected-frame)))
8295 (with-selected-frame frame
8296 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8297 (normal-erase-is-backspace-mode
8298 (if (if (eq normal-erase-is-backspace 'maybe)
8299 (and (not noninteractive)
8300 (or (memq system-type '(ms-dos windows-nt))
8301 (memq window-system '(w32 ns))
8302 (and (memq window-system '(x))
8303 (fboundp 'x-backspace-delete-keys-p)
8304 (x-backspace-delete-keys-p))
8305 ;; If the terminal Emacs is running on has erase char
8306 ;; set to ^H, use the Backspace key for deleting
8307 ;; backward, and the Delete key for deleting forward.
8308 (and (null window-system)
8309 (eq tty-erase-char ?\^H))))
8310 normal-erase-is-backspace)
8313 (define-minor-mode normal-erase-is-backspace-mode
8314 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8315 With a prefix argument ARG, enable this feature if ARG is
8316 positive, and disable it otherwise. If called from Lisp, enable
8317 the mode if ARG is omitted or nil.
8319 On window systems, when this mode is on, Delete is mapped to C-d
8320 and Backspace is mapped to DEL; when this mode is off, both
8321 Delete and Backspace are mapped to DEL. (The remapping goes via
8322 `local-function-key-map', so binding Delete or Backspace in the
8323 global or local keymap will override that.)
8325 In addition, on window systems, the bindings of C-Delete, M-Delete,
8326 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8327 the global keymap in accordance with the functionality of Delete and
8328 Backspace. For example, if Delete is remapped to C-d, which deletes
8329 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8330 to DEL, which deletes backward, C-Delete is bound to
8331 `backward-kill-word'.
8333 If not running on a window system, a similar effect is accomplished by
8334 remapping C-h (normally produced by the Backspace key) and DEL via
8335 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8336 to C-d; if it's off, the keys are not remapped.
8338 When not running on a window system, and this mode is turned on, the
8339 former functionality of C-h is available on the F1 key. You should
8340 probably not turn on this mode on a text-only terminal if you don't
8341 have both Backspace, Delete and F1 keys.
8343 See also `normal-erase-is-backspace'."
8344 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8346 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8348 (let ((enabled (eq 1 (terminal-parameter
8349 nil 'normal-erase-is-backspace))))
8351 (cond ((or (memq window-system '(x w32 ns pc))
8352 (memq system-type '(ms-dos windows-nt)))
8354 `(([M-delete] [M-backspace])
8355 ([C-M-delete] [C-M-backspace])
8356 ([?\e C-delete] [?\e C-backspace]))))
8360 (define-key local-function-key-map [delete] [deletechar])
8361 (define-key local-function-key-map [kp-delete] [deletechar])
8362 (define-key local-function-key-map [backspace] [?\C-?])
8363 (dolist (b bindings)
8364 ;; Not sure if input-decode-map is really right, but
8365 ;; keyboard-translate-table (used below) only works
8366 ;; for integer events, and key-translation-table is
8367 ;; global (like the global-map, used earlier).
8368 (define-key input-decode-map (car b) nil)
8369 (define-key input-decode-map (cadr b) nil)))
8370 (define-key local-function-key-map [delete] [?\C-?])
8371 (define-key local-function-key-map [kp-delete] [?\C-?])
8372 (define-key local-function-key-map [backspace] [?\C-?])
8373 (dolist (b bindings)
8374 (define-key input-decode-map (car b) (cadr b))
8375 (define-key input-decode-map (cadr b) (car b))))))
8379 (keyboard-translate ?\C-h ?\C-?)
8380 (keyboard-translate ?\C-? ?\C-d))
8381 (keyboard-translate ?\C-h ?\C-h)
8382 (keyboard-translate ?\C-? ?\C-?))))
8384 (if (called-interactively-p 'interactive)
8385 (message "Delete key deletes %s"
8386 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8387 "forward" "backward")))))
8389 (defvar vis-mode-saved-buffer-invisibility-spec nil
8390 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8392 (define-minor-mode read-only-mode
8393 "Change whether the current buffer is read-only.
8394 With prefix argument ARG, make the buffer read-only if ARG is
8395 positive, otherwise make it writable. If buffer is read-only
8396 and `view-read-only' is non-nil, enter view mode.
8398 Do not call this from a Lisp program unless you really intend to
8399 do the same thing as the \\[read-only-mode] command, including
8400 possibly enabling or disabling View mode. Also, note that this
8401 command works by setting the variable `buffer-read-only', which
8402 does not affect read-only regions caused by text properties. To
8403 ignore read-only status in a Lisp program (whether due to text
8404 properties or buffer state), bind `inhibit-read-only' temporarily
8405 to a non-nil value."
8406 :variable buffer-read-only
8408 ((and (not buffer-read-only) view-mode)
8409 (View-exit-and-edit)
8410 (make-local-variable 'view-read-only)
8411 (setq view-read-only t)) ; Must leave view mode.
8412 ((and buffer-read-only view-read-only
8413 ;; If view-mode is already active, `view-mode-enter' is a nop.
8415 (not (eq (get major-mode 'mode-class) 'special)))
8416 (view-mode-enter))))
8418 (define-minor-mode visible-mode
8419 "Toggle making all invisible text temporarily visible (Visible mode).
8420 With a prefix argument ARG, enable Visible mode if ARG is
8421 positive, and disable it otherwise. If called from Lisp, enable
8422 the mode if ARG is omitted or nil.
8424 This mode works by saving the value of `buffer-invisibility-spec'
8425 and setting it to nil."
8427 :group 'editing-basics
8428 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8429 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8430 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8432 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8433 buffer-invisibility-spec)
8434 (setq buffer-invisibility-spec nil)))
8436 (defvar messages-buffer-mode-map
8437 (let ((map (make-sparse-keymap)))
8438 (set-keymap-parent map special-mode-map)
8439 (define-key map "g" nil) ; nothing to revert
8442 (define-derived-mode messages-buffer-mode special-mode "Messages"
8443 "Major mode used in the \"*Messages*\" buffer.")
8445 (defun messages-buffer ()
8446 "Return the \"*Messages*\" buffer.
8447 If it does not exist, create and it switch it to `messages-buffer-mode'."
8448 (or (get-buffer "*Messages*")
8449 (with-current-buffer (get-buffer-create "*Messages*")
8450 (messages-buffer-mode)
8454 ;; Minibuffer prompt stuff.
8456 ;;(defun minibuffer-prompt-modification (start end)
8457 ;; (error "You cannot modify the prompt"))
8460 ;;(defun minibuffer-prompt-insertion (start end)
8461 ;; (let ((inhibit-modification-hooks t))
8462 ;; (delete-region start end)
8463 ;; ;; Discard undo information for the text insertion itself
8464 ;; ;; and for the text deletion.above.
8465 ;; (when (consp buffer-undo-list)
8466 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8467 ;; (message "You cannot modify the prompt")))
8470 ;;(setq minibuffer-prompt-properties
8471 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8472 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8475 ;;;; Problematic external packages.
8477 ;; rms says this should be done by specifying symbols that define
8478 ;; versions together with bad values. This is therefore not as
8479 ;; flexible as it could be. See the thread:
8480 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8481 (defconst bad-packages-alist
8482 ;; Not sure exactly which semantic versions have problems.
8483 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8484 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8485 "The version of `semantic' loaded does not work in Emacs 22.
8486 It can cause constant high CPU load.
8487 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8488 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8489 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8490 ;; provided the `CUA-mode' feature. Since this is no longer true,
8491 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8493 "CUA-mode is now part of the standard GNU Emacs distribution,
8494 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8496 You have loaded an older version of CUA-mode which does not work
8497 correctly with this version of Emacs. You should remove the old
8498 version and use the one distributed with Emacs."))
8499 "Alist of packages known to cause problems in this version of Emacs.
8500 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8501 PACKAGE is either a regular expression to match file names, or a
8502 symbol (a feature name), like for `with-eval-after-load'.
8503 SYMBOL is either the name of a string variable, or t. Upon
8504 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8505 warning using STRING as the message.")
8507 (defun bad-package-check (package)
8508 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8510 (let* ((list (assoc package bad-packages-alist))
8511 (symbol (nth 1 list)))
8515 (and (stringp (setq symbol (eval symbol)))
8516 (string-match-p (nth 2 list) symbol)))
8517 (display-warning package (nth 3 list) :warning)))
8520 (dolist (elem bad-packages-alist)
8521 (let ((pkg (car elem)))
8522 (with-eval-after-load pkg
8523 (bad-package-check pkg))))
8526 ;;; Generic dispatcher commands
8528 ;; Macro `define-alternatives' is used to create generic commands.
8529 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8530 ;; that can have different alternative implementations where choosing
8531 ;; among them is exclusively a matter of user preference.
8533 ;; (define-alternatives COMMAND) creates a new interactive command
8534 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8535 ;; Typically, the user will not need to customize this variable; packages
8536 ;; wanting to add alternative implementations should use
8538 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8540 (defmacro define-alternatives (command &rest customizations)
8541 "Define the new command `COMMAND'.
8543 The argument `COMMAND' should be a symbol.
8545 Running `M-x COMMAND RET' for the first time prompts for which
8546 alternative to use and records the selected command as a custom
8549 Running `C-u M-x COMMAND RET' prompts again for an alternative
8550 and overwrites the previous choice.
8552 The variable `COMMAND-alternatives' contains an alist with
8553 alternative implementations of COMMAND. `define-alternatives'
8554 does not have any effect until this variable is set.
8556 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8557 `defcustom' keywords and values to add to the declaration of
8558 `COMMAND-alternatives' (typically :group and :version)."
8559 (let* ((command-name (symbol-name command))
8560 (varalt-name (concat command-name "-alternatives"))
8561 (varalt-sym (intern varalt-name))
8562 (varimp-sym (intern (concat command-name "--implementation"))))
8565 (defcustom ,varalt-sym nil
8566 ,(format "Alist of alternative implementations for the `%s' command.
8568 Each entry must be a pair (ALTNAME . ALTFUN), where:
8569 ALTNAME - The name shown at user to describe the alternative implementation.
8570 ALTFUN - The function called to implement this alternative."
8572 :type '(alist :key-type string :value-type function)
8575 (put ',varalt-sym 'definition-name ',command)
8576 (defvar ,varimp-sym nil "Internal use only.")
8578 (defun ,command (&optional arg)
8579 ,(format "Run generic command `%s'.
8580 If used for the first time, or with interactive ARG, ask the user which
8581 implementation to use for `%s'. The variable `%s'
8582 contains the list of implementations currently supported for this command."
8583 command-name command-name varalt-name)
8585 (when (or arg (null ,varimp-sym))
8586 (let ((val (completing-read
8588 "Select implementation for command `%s': "
8590 ,varalt-sym nil t)))
8591 (unless (string-equal val "")
8592 (when (null ,varimp-sym)
8594 "Use C-u M-x %s RET`to select another implementation"
8597 (customize-save-variable ',varimp-sym
8598 (cdr (assoc-string val ,varalt-sym))))))
8600 (call-interactively ,varimp-sym)
8601 (message "%s" ,(format-message
8602 "No implementation selected for command `%s'"
8606 ;;; Functions for changing capitalization that Do What I Mean
8607 (defun upcase-dwim (arg)
8608 "Upcase words in the region, if active; if not, upcase word at point.
8609 If the region is active, this function calls `upcase-region'.
8610 Otherwise, it calls `upcase-word', with prefix argument passed to it
8611 to upcase ARG words."
8614 (upcase-region (region-beginning) (region-end))
8617 (defun downcase-dwim (arg)
8618 "Downcase words in the region, if active; if not, downcase word at point.
8619 If the region is active, this function calls `downcase-region'.
8620 Otherwise, it calls `downcase-word', with prefix argument passed to it
8621 to downcase ARG words."
8624 (downcase-region (region-beginning) (region-end))
8625 (downcase-word arg)))
8627 (defun capitalize-dwim (arg)
8628 "Capitalize words in the region, if active; if not, capitalize word at point.
8629 If the region is active, this function calls `capitalize-region'.
8630 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8631 to capitalize ARG words."
8634 (capitalize-region (region-beginning) (region-end))
8635 (capitalize-word arg)))
8641 ;;; simple.el ends here