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,
978 after filtering it with `filter-buffer-substring'.")
980 (defvar region-insert-function
986 (insert-for-yank (car lines))
987 (setq lines (cdr lines)
989 "Function to insert the region's content.
990 Called with one argument LINES.
991 Insert the region as a list of lines.")
993 (defun delete-backward-char (n &optional killflag)
994 "Delete the previous N characters (following if N is negative).
995 If Transient Mark mode is enabled, the mark is active, and N is 1,
996 delete the text in the region and deactivate the mark instead.
997 To disable this, set option `delete-active-region' to nil.
999 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1000 kill ring) instead of delete. Interactively, N is the prefix
1001 arg, and KILLFLAG is set if N is explicitly specified.
1003 When killing, the killed text is filtered by
1004 `filter-buffer-substring' before it is saved in the kill ring, so
1005 the actual saved text might be different from what was killed.
1007 In Overwrite mode, single character backward deletion may replace
1008 tabs with spaces so as to back over columns, unless point is at
1009 the end of the line."
1010 (declare (interactive-only delete-char))
1011 (interactive "p\nP")
1012 (unless (integerp n)
1013 (signal 'wrong-type-argument (list 'integerp n)))
1014 (cond ((and (use-region-p)
1015 delete-active-region
1017 ;; If a region is active, kill or delete it.
1018 (if (eq delete-active-region 'kill)
1019 (kill-region (region-beginning) (region-end) 'region)
1020 (funcall region-extract-function 'delete-only)))
1021 ;; In Overwrite mode, maybe untabify while deleting
1022 ((null (or (null overwrite-mode)
1024 (memq (char-before) '(?\t ?\n))
1026 (eq (char-after) ?\n)))
1027 (let ((ocol (current-column)))
1028 (delete-char (- n) killflag)
1030 (insert-char ?\s (- ocol (current-column)) nil))))
1031 ;; Otherwise, do simple deletion.
1032 (t (delete-char (- n) killflag))))
1034 (defun delete-forward-char (n &optional killflag)
1035 "Delete the following N characters (previous if N is negative).
1036 If Transient Mark mode is enabled, the mark is active, and N is 1,
1037 delete the text in the region and deactivate the mark instead.
1038 To disable this, set variable `delete-active-region' to nil.
1040 Optional second arg KILLFLAG non-nil means to kill (save in kill
1041 ring) instead of delete. Interactively, N is the prefix arg, and
1042 KILLFLAG is set if N was explicitly specified.
1044 When killing, the killed text is filtered by
1045 `filter-buffer-substring' before it is saved in the kill ring, so
1046 the actual saved text might be different from what was killed."
1047 (declare (interactive-only delete-char))
1048 (interactive "p\nP")
1049 (unless (integerp n)
1050 (signal 'wrong-type-argument (list 'integerp n)))
1051 (cond ((and (use-region-p)
1052 delete-active-region
1054 ;; If a region is active, kill or delete it.
1055 (if (eq delete-active-region 'kill)
1056 (kill-region (region-beginning) (region-end) 'region)
1057 (funcall region-extract-function 'delete-only)))
1059 ;; Otherwise, do simple deletion.
1060 (t (delete-char n killflag))))
1062 (defun mark-whole-buffer ()
1063 "Put point at beginning and mark at end of buffer.
1064 If narrowing is in effect, only uses the accessible part of the buffer.
1065 You probably should not use this function in Lisp programs;
1066 it is usually a mistake for a Lisp function to use any subroutine
1067 that uses or sets the mark."
1068 (declare (interactive-only t))
1071 (push-mark (point-max) nil t)
1072 (goto-char (point-min)))
1075 ;; Counting lines, one way or another.
1077 (defun goto-line (line &optional buffer)
1078 "Go to LINE, counting from line 1 at beginning of buffer.
1079 If called interactively, a numeric prefix argument specifies
1080 LINE; without a numeric prefix argument, read LINE from the
1083 If optional argument BUFFER is non-nil, switch to that buffer and
1084 move to line LINE there. If called interactively with \\[universal-argument]
1085 as argument, BUFFER is the most recently selected other buffer.
1087 Prior to moving point, this function sets the mark (without
1088 activating it), unless Transient Mark mode is enabled and the
1089 mark is already active.
1091 This function is usually the wrong thing to use in a Lisp program.
1092 What you probably want instead is something like:
1093 (goto-char (point-min))
1094 (forward-line (1- N))
1095 If at all possible, an even better solution is to use char counts
1096 rather than line counts."
1097 (declare (interactive-only forward-line))
1099 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1100 (list (prefix-numeric-value current-prefix-arg))
1101 ;; Look for a default, a number in the buffer at point.
1104 (skip-chars-backward "0-9")
1105 (if (looking-at "[0-9]")
1107 (buffer-substring-no-properties
1109 (progn (skip-chars-forward "0-9")
1111 ;; Decide if we're switching buffers.
1113 (if (consp current-prefix-arg)
1114 (other-buffer (current-buffer) t)))
1117 (concat " in " (buffer-name buffer))
1119 ;; Read the argument, offering that number (if any) as default.
1120 (list (read-number (format "Goto line%s: " buffer-prompt)
1121 (list default (line-number-at-pos)))
1123 ;; Switch to the desired buffer, one way or another.
1125 (let ((window (get-buffer-window buffer)))
1126 (if window (select-window window)
1127 (switch-to-buffer-other-window buffer))))
1128 ;; Leave mark at previous position
1129 (or (region-active-p) (push-mark))
1130 ;; Move to the specified line number in that buffer.
1133 (goto-char (point-min))
1134 (if (eq selective-display t)
1135 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1136 (forward-line (1- line)))))
1138 (defun count-words-region (start end &optional arg)
1139 "Count the number of words in the region.
1140 If called interactively, print a message reporting the number of
1141 lines, words, and characters in the region (whether or not the
1142 region is active); with prefix ARG, report for the entire buffer
1143 rather than the region.
1145 If called from Lisp, return the number of words between positions
1147 (interactive (if current-prefix-arg
1148 (list nil nil current-prefix-arg)
1149 (list (region-beginning) (region-end) nil)))
1150 (cond ((not (called-interactively-p 'any))
1151 (count-words start end))
1153 (count-words--buffer-message))
1155 (count-words--message "Region" start end))))
1157 (defun count-words (start end)
1158 "Count words between START and END.
1159 If called interactively, START and END are normally the start and
1160 end of the buffer; but if the region is active, START and END are
1161 the start and end of the region. Print a message reporting the
1162 number of lines, words, and chars.
1164 If called from Lisp, return the number of words between START and
1165 END, without printing any message."
1166 (interactive (list nil nil))
1167 (cond ((not (called-interactively-p 'any))
1171 (narrow-to-region start end)
1172 (goto-char (point-min))
1173 (while (forward-word 1)
1174 (setq words (1+ words)))))
1177 (call-interactively 'count-words-region))
1179 (count-words--buffer-message))))
1181 (defun count-words--buffer-message ()
1182 (count-words--message
1183 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1184 (point-min) (point-max)))
1186 (defun count-words--message (str start end)
1187 (let ((lines (count-lines start end))
1188 (words (count-words start end))
1189 (chars (- end start)))
1190 (message "%s has %d line%s, %d word%s, and %d character%s."
1192 lines (if (= lines 1) "" "s")
1193 words (if (= words 1) "" "s")
1194 chars (if (= chars 1) "" "s"))))
1196 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1199 "Print the current buffer line number and narrowed line number of point."
1201 (let ((start (point-min))
1202 (n (line-number-at-pos)))
1204 (message "Line %d" n)
1208 (message "line %d (narrowed line %d)"
1209 (+ n (line-number-at-pos start) -1) n))))))
1211 (defun count-lines (start end)
1212 "Return number of lines between START and END.
1213 This is usually the number of newlines between them,
1214 but can be one more if START is not equal to END
1215 and the greater of them is not at the start of a line."
1218 (narrow-to-region start end)
1219 (goto-char (point-min))
1220 (if (eq selective-display t)
1223 (while (re-search-forward "[\n\C-m]" nil t 40)
1224 (setq done (+ 40 done)))
1225 (while (re-search-forward "[\n\C-m]" nil t 1)
1226 (setq done (+ 1 done)))
1227 (goto-char (point-max))
1228 (if (and (/= start end)
1232 (- (buffer-size) (forward-line (buffer-size)))))))
1234 (defun line-number-at-pos (&optional pos)
1235 "Return (narrowed) buffer line number at position POS.
1236 If POS is nil, use current buffer location.
1237 Counting starts at (point-min), so the value refers
1238 to the contents of the accessible portion of the buffer."
1239 (let ((opoint (or pos (point))) start)
1241 (goto-char (point-min))
1242 (setq start (point))
1245 (1+ (count-lines start (point))))))
1247 (defun what-cursor-position (&optional detail)
1248 "Print info on cursor position (on screen and within buffer).
1249 Also describe the character after point, and give its character code
1250 in octal, decimal and hex.
1252 For a non-ASCII multibyte character, also give its encoding in the
1253 buffer's selected coding system if the coding system encodes the
1254 character safely. If the character is encoded into one byte, that
1255 code is shown in hex. If the character is encoded into more than one
1256 byte, just \"...\" is shown.
1258 In addition, with prefix argument, show details about that character
1259 in *Help* buffer. See also the command `describe-char'."
1261 (let* ((char (following-char))
1263 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1264 ;; start a directional embedding, which could completely
1265 ;; disrupt the rest of the line (e.g., RLO will display the
1266 ;; rest of the line right-to-left). So we put an invisible
1267 ;; PDF character after these characters, to end the
1268 ;; embedding, which eliminates any effects on the rest of
1269 ;; the line. For RLE and RLO we also append an invisible
1270 ;; LRM, to avoid reordering the following numerical
1271 ;; characters. For LRI/RLI/FSI we append a PDI.
1272 (cond ((memq char '(?\x202a ?\x202d))
1273 (propertize (string ?\x202c) 'invisible t))
1274 ((memq char '(?\x202b ?\x202e))
1275 (propertize (string ?\x202c ?\x200e) 'invisible t))
1276 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1277 (propertize (string ?\x2069) 'invisible t))
1278 ;; Strong right-to-left characters cause reordering of
1279 ;; the following numerical characters which show the
1280 ;; codepoint, so append LRM to countermand that.
1281 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1282 (propertize (string ?\x200e) 'invisible t))
1288 (total (buffer-size))
1289 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1290 (hscroll (if (= (window-hscroll) 0)
1292 (format " Hscroll=%d" (window-hscroll))))
1293 (col (current-column)))
1295 (if (or (/= beg 1) (/= end (1+ total)))
1296 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1297 pos total percent beg end col hscroll)
1298 (message "point=%d of %d (EOB) column=%d%s"
1299 pos total col hscroll))
1300 (let ((coding buffer-file-coding-system)
1301 encoded encoding-msg display-prop under-display)
1302 (if (or (not coding)
1303 (eq (coding-system-type coding) t))
1304 (setq coding (default-value 'buffer-file-coding-system)))
1305 (if (eq (char-charset char) 'eight-bit)
1307 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1308 ;; Check if the character is displayed with some `display'
1309 ;; text property. In that case, set under-display to the
1310 ;; buffer substring covered by that property.
1311 (setq display-prop (get-char-property pos 'display))
1313 (let ((to (or (next-single-char-property-change pos 'display)
1315 (if (< to (+ pos 4))
1316 (setq under-display "")
1317 (setq under-display "..."
1320 (concat (buffer-substring-no-properties pos to)
1322 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1325 (if (not (stringp display-prop))
1326 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1327 char char char under-display)
1328 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1329 char char char under-display display-prop))
1331 (format "(%d, #o%o, #x%x, file %s)"
1333 (if (> (length encoded) 1)
1335 (encoded-string-description encoded coding)))
1336 (format "(%d, #o%o, #x%x)" char char char)))))
1338 ;; We show the detailed information about CHAR.
1339 (describe-char (point)))
1340 (if (or (/= beg 1) (/= end (1+ total)))
1341 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1343 (single-key-description char)
1344 (buffer-substring-no-properties (point) (1+ (point))))
1346 encoding-msg pos total percent beg end col hscroll)
1347 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1348 (if enable-multibyte-characters
1350 (single-key-description char)
1351 (buffer-substring-no-properties (point) (1+ (point))))
1352 (single-key-description char))
1353 bidi-fixer encoding-msg pos total percent col hscroll))))))
1355 ;; Initialize read-expression-map. It is defined at C level.
1356 (defvar read-expression-map
1357 (let ((m (make-sparse-keymap)))
1358 (define-key m "\M-\t" 'completion-at-point)
1359 ;; Might as well bind TAB to completion, since inserting a TAB char is
1360 ;; much too rarely useful.
1361 (define-key m "\t" 'completion-at-point)
1362 (set-keymap-parent m minibuffer-local-map)
1365 (defun read-minibuffer (prompt &optional initial-contents)
1366 "Return a Lisp object read using the minibuffer, unevaluated.
1367 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1368 is a string to insert in the minibuffer before reading.
1369 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1370 Such arguments are used as in `read-from-minibuffer'.)"
1371 ;; Used for interactive spec `x'.
1372 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1373 t 'minibuffer-history))
1375 (defun eval-minibuffer (prompt &optional initial-contents)
1376 "Return value of Lisp expression read using the minibuffer.
1377 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1378 is a string to insert in the minibuffer before reading.
1379 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1380 Such arguments are used as in `read-from-minibuffer'.)"
1381 ;; Used for interactive spec `X'.
1382 (eval (read--expression prompt initial-contents)))
1384 (defvar minibuffer-completing-symbol nil
1385 "Non-nil means completing a Lisp symbol in the minibuffer.")
1386 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1388 (defvar minibuffer-default nil
1389 "The current default value or list of default values in the minibuffer.
1390 The functions `read-from-minibuffer' and `completing-read' bind
1391 this variable locally.")
1393 (defcustom eval-expression-print-level 4
1394 "Value for `print-level' while printing value in `eval-expression'.
1395 A value of nil means no limit."
1397 :type '(choice (const :tag "No Limit" nil) integer)
1400 (defcustom eval-expression-print-length 12
1401 "Value for `print-length' while printing value in `eval-expression'.
1402 A value of nil means no limit."
1404 :type '(choice (const :tag "No Limit" nil) integer)
1407 (defcustom eval-expression-debug-on-error t
1408 "If non-nil set `debug-on-error' to t in `eval-expression'.
1409 If nil, don't change the value of `debug-on-error'."
1414 (defun eval-expression-print-format (value)
1415 "Format VALUE as a result of evaluated expression.
1416 Return a formatted string which is displayed in the echo area
1417 in addition to the value printed by prin1 in functions which
1418 display the result of expression evaluation."
1419 (if (and (integerp value)
1420 (or (eq standard-output t)
1421 (zerop (prefix-numeric-value current-prefix-arg))))
1423 (if (and (characterp value)
1424 (char-displayable-p value))
1425 (prin1-char value))))
1427 (format " (#o%o, #x%x, %s)" value value char-string)
1428 (format " (#o%o, #x%x)" value value)))))
1430 (defvar eval-expression-minibuffer-setup-hook nil
1431 "Hook run by `eval-expression' when entering the minibuffer.")
1433 (defun read--expression (prompt &optional initial-contents)
1434 (let ((minibuffer-completing-symbol t))
1435 (minibuffer-with-setup-hook
1437 ;; FIXME: call emacs-lisp-mode?
1438 (add-function :before-until (local 'eldoc-documentation-function)
1439 #'elisp-eldoc-documentation-function)
1440 (add-hook 'completion-at-point-functions
1441 #'elisp-completion-at-point nil t)
1442 (run-hooks 'eval-expression-minibuffer-setup-hook))
1443 (read-from-minibuffer prompt initial-contents
1444 read-expression-map t
1445 'read-expression-history))))
1447 ;; We define this, rather than making `eval' interactive,
1448 ;; for the sake of completion of names like eval-region, eval-buffer.
1449 (defun eval-expression (exp &optional insert-value)
1450 "Evaluate EXP and print value in the echo area.
1451 When called interactively, read an Emacs Lisp expression and evaluate it.
1452 Value is also consed on to front of the variable `values'.
1453 Optional argument INSERT-VALUE non-nil (interactively, with prefix
1454 argument) means insert the result into the current buffer instead of
1455 printing it in the echo area.
1457 Normally, this function truncates long output according to the value
1458 of the variables `eval-expression-print-length' and
1459 `eval-expression-print-level'. With a prefix argument of zero,
1460 however, there is no such truncation. Such a prefix argument
1461 also causes integers to be printed in several additional formats
1462 \(octal, hexadecimal, and character).
1464 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1467 If `eval-expression-debug-on-error' is non-nil, which is the default,
1468 this command arranges for all errors to enter the debugger."
1470 (list (read--expression "Eval: ")
1471 current-prefix-arg))
1473 (if (null eval-expression-debug-on-error)
1474 (push (eval exp lexical-binding) values)
1475 (let ((old-value (make-symbol "t")) new-value)
1476 ;; Bind debug-on-error to something unique so that we can
1477 ;; detect when evalled code changes it.
1478 (let ((debug-on-error old-value))
1479 (push (eval (macroexpand-all exp) lexical-binding) values)
1480 (setq new-value debug-on-error))
1481 ;; If evalled code has changed the value of debug-on-error,
1482 ;; propagate that change to the global binding.
1483 (unless (eq old-value new-value)
1484 (setq debug-on-error new-value))))
1486 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1487 eval-expression-print-length))
1488 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1489 eval-expression-print-level))
1493 (let ((standard-output (current-buffer)))
1495 (prin1 (car values))
1496 (when (zerop (prefix-numeric-value insert-value))
1497 (let ((str (eval-expression-print-format (car values))))
1498 (if str (princ str)))))))
1500 (prin1 (car values) t)
1501 (let ((str (eval-expression-print-format (car values))))
1502 (if str (princ str t)))))))
1504 (defun edit-and-eval-command (prompt command)
1505 "Prompting with PROMPT, let user edit COMMAND and eval result.
1506 COMMAND is a Lisp expression. Let user edit that expression in
1507 the minibuffer, then read and evaluate the result."
1509 (let ((print-level nil)
1510 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1512 (read-from-minibuffer prompt
1513 (prin1-to-string command)
1514 read-expression-map t
1516 ;; If command was added to command-history as a string,
1517 ;; get rid of that. We want only evaluable expressions there.
1518 (if (stringp (car command-history))
1519 (setq command-history (cdr command-history)))))))
1521 ;; If command to be redone does not match front of history,
1522 ;; add it to the history.
1523 (or (equal command (car command-history))
1524 (setq command-history (cons command command-history)))
1527 (defun repeat-complex-command (arg)
1528 "Edit and re-evaluate last complex command, or ARGth from last.
1529 A complex command is one which used the minibuffer.
1530 The command is placed in the minibuffer as a Lisp form for editing.
1531 The result is executed, repeating the command as changed.
1532 If the command has been changed or is not the most recent previous
1533 command it is added to the front of the command history.
1534 You can use the minibuffer history commands \
1535 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1536 to get different commands to edit and resubmit."
1538 (let ((elt (nth (1- arg) command-history))
1543 (let ((print-level nil)
1544 (minibuffer-history-position arg)
1545 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1547 (read-from-minibuffer
1548 "Redo: " (prin1-to-string elt) read-expression-map t
1549 (cons 'command-history arg))
1551 ;; If command was added to command-history as a
1552 ;; string, get rid of that. We want only
1553 ;; evaluable expressions there.
1554 (if (stringp (car command-history))
1555 (setq command-history (cdr command-history))))))
1557 ;; If command to be redone does not match front of history,
1558 ;; add it to the history.
1559 (or (equal newcmd (car command-history))
1560 (setq command-history (cons newcmd command-history)))
1561 (apply #'funcall-interactively
1563 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1565 (error "Argument %d is beyond length of command history" arg)
1566 (error "There are no previous complex commands to repeat")))))
1569 (defvar extended-command-history nil)
1570 (defvar execute-extended-command--last-typed nil)
1572 (defun read-extended-command ()
1573 "Read command name to invoke in `execute-extended-command'."
1574 (minibuffer-with-setup-hook
1576 (add-hook 'post-self-insert-hook
1578 (setq execute-extended-command--last-typed
1579 (minibuffer-contents)))
1581 (set (make-local-variable 'minibuffer-default-add-function)
1583 ;; Get a command name at point in the original buffer
1584 ;; to propose it after M-n.
1585 (with-current-buffer (window-buffer (minibuffer-selected-window))
1586 (and (commandp (function-called-at-point))
1587 (format "%S" (function-called-at-point)))))))
1588 ;; Read a string, completing from and restricting to the set of
1589 ;; all defined commands. Don't provide any initial input.
1590 ;; Save the command read on the extended-command history list.
1593 ((eq current-prefix-arg '-) "- ")
1594 ((and (consp current-prefix-arg)
1595 (eq (car current-prefix-arg) 4)) "C-u ")
1596 ((and (consp current-prefix-arg)
1597 (integerp (car current-prefix-arg)))
1598 (format "%d " (car current-prefix-arg)))
1599 ((integerp current-prefix-arg)
1600 (format "%d " current-prefix-arg)))
1601 ;; This isn't strictly correct if `execute-extended-command'
1602 ;; is bound to anything else (e.g. [menu]).
1603 ;; It could use (key-description (this-single-command-keys)),
1604 ;; but actually a prompt other than "M-x" would be confusing,
1605 ;; because "M-x" is a well-known prompt to read a command
1606 ;; and it serves as a shorthand for "Extended command: ".
1608 (lambda (string pred action)
1610 (if (memq action '(nil t))
1611 ;; Exclude obsolete commands from completions.
1613 (and (funcall pred sym)
1614 (or (equal string (symbol-name sym))
1615 (not (get sym 'byte-obsolete-info)))))
1617 (complete-with-action action obarray string pred)))
1618 #'commandp t nil 'extended-command-history)))
1620 (defcustom suggest-key-bindings t
1621 "Non-nil means show the equivalent key-binding when M-x command has one.
1622 The value can be a length of time to show the message for.
1623 If the value is non-nil and not a number, we wait 2 seconds."
1625 :type '(choice (const :tag "off" nil)
1626 (integer :tag "time" 2)
1629 (defun execute-extended-command--shorter-1 (name length)
1631 ((zerop length) (list ""))
1632 ((equal name "") nil)
1634 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1635 (execute-extended-command--shorter-1
1636 (substring name 1) (1- length)))
1637 (when (string-match "\\`\\(-\\)?[^-]*" name)
1638 (execute-extended-command--shorter-1
1639 (substring name (match-end 0)) length))))))
1641 (defun execute-extended-command--shorter (name typed)
1642 (let ((candidates '())
1643 (max (length typed))
1646 (while (and (not binding)
1650 (setq candidates (execute-extended-command--shorter-1
1652 ;; Don't show the help message if the binding isn't
1653 ;; significantly shorter than the M-x command the user typed.
1655 (let ((candidate (pop candidates)))
1657 (car-safe (completion-try-completion
1658 candidate obarray 'commandp len)))
1659 (setq binding candidate))))
1662 (defun execute-extended-command (prefixarg &optional command-name typed)
1663 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1664 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1665 "Read a command name, then read the arguments and call the command.
1666 To pass a prefix argument to the command you are
1667 invoking, give a prefix argument to `execute-extended-command'."
1668 (declare (interactive-only command-execute))
1669 ;; FIXME: Remember the actual text typed by the user before completion,
1670 ;; so that we don't later on suggest the same shortening.
1672 (let ((execute-extended-command--last-typed nil))
1673 (list current-prefix-arg
1674 (read-extended-command)
1675 execute-extended-command--last-typed)))
1676 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1677 (unless command-name
1678 (let ((current-prefix-arg prefixarg) ; for prompt
1679 (execute-extended-command--last-typed nil))
1680 (setq command-name (read-extended-command))
1681 (setq typed execute-extended-command--last-typed)))
1682 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1683 (binding (and suggest-key-bindings
1684 (not executing-kbd-macro)
1685 (where-is-internal function overriding-local-map t))))
1686 (unless (commandp function)
1687 (error "`%s' is not a valid command name" command-name))
1688 (setq this-command function)
1689 ;; Normally `real-this-command' should never be changed, but here we really
1690 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1691 ;; binding" for <cmd>, so the command the user really wanted to run is
1692 ;; `function' and not `execute-extended-command'. The difference is
1693 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1694 (setq real-this-command function)
1695 (let ((prefix-arg prefixarg))
1696 (command-execute function 'record))
1697 ;; If enabled, show which key runs this command.
1698 ;; But first wait, and skip the message if there is input.
1700 ;; If this command displayed something in the echo area;
1701 ;; wait a few seconds, then display our suggestion message.
1702 ;; FIXME: Wait *after* running post-command-hook!
1703 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1704 ;; find a better answer anyway!
1705 (when suggest-key-bindings
1707 ((zerop (length (current-message))) 0)
1708 ((numberp suggest-key-bindings) suggest-key-bindings)
1710 (when (and waited (not (consp unread-command-events)))
1711 (unless (or binding executing-kbd-macro (not (symbolp function))
1712 (<= (length (symbol-name function)) 2))
1713 ;; There's no binding for CMD. Let's try and find the shortest
1714 ;; string to use in M-x.
1715 ;; FIXME: Can be slow. Cache it maybe?
1717 (setq binding (execute-extended-command--shorter
1718 (symbol-name function) typed))))
1721 (format-message "You can run the command `%s' with %s"
1723 (if (stringp binding)
1724 (concat "M-x " binding " RET")
1725 (key-description binding)))
1726 (sit-for (if (numberp suggest-key-bindings)
1727 suggest-key-bindings
1730 (defun command-execute (cmd &optional record-flag keys special)
1731 ;; BEWARE: Called directly from the C code.
1732 "Execute CMD as an editor command.
1733 CMD must be a symbol that satisfies the `commandp' predicate.
1734 Optional second arg RECORD-FLAG non-nil
1735 means unconditionally put this command in the variable `command-history'.
1736 Otherwise, that is done only if an arg is read using the minibuffer.
1737 The argument KEYS specifies the value to use instead of (this-command-keys)
1738 when reading the arguments; if it is nil, (this-command-keys) is used.
1739 The argument SPECIAL, if non-nil, means that this command is executing
1740 a special event, so ignore the prefix argument and don't clear it."
1741 (setq debug-on-next-call nil)
1742 (let ((prefixarg (unless special
1743 ;; FIXME: This should probably be done around
1744 ;; pre-command-hook rather than here!
1746 (setq current-prefix-arg prefix-arg)
1747 (setq prefix-arg nil)
1748 (when current-prefix-arg
1749 (prefix-command-update))))))
1750 (if (and (symbolp cmd)
1752 disabled-command-function)
1753 ;; FIXME: Weird calling convention!
1754 (run-hooks 'disabled-command-function)
1758 (setq final (indirect-function final))
1759 (if (autoloadp final)
1760 (setq final (autoload-do-load final cmd)))))
1763 ;; If requested, place the macro in the command history. For
1764 ;; other sorts of commands, call-interactively takes care of this.
1766 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1767 ;; Don't keep command history around forever.
1768 (when (and (numberp history-length) (> history-length 0))
1769 (let ((cell (nthcdr history-length command-history)))
1770 (if (consp cell) (setcdr cell nil)))))
1771 (execute-kbd-macro final prefixarg))
1773 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1774 (prog1 (call-interactively cmd record-flag keys)
1775 (when (and (symbolp cmd)
1776 (get cmd 'byte-obsolete-info)
1777 (not (get cmd 'command-execute-obsolete-warned)))
1778 (put cmd 'command-execute-obsolete-warned t)
1779 (message "%s" (macroexp--obsolete-warning
1780 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1782 (defvar minibuffer-history nil
1783 "Default minibuffer history list.
1784 This is used for all minibuffer input
1785 except when an alternate history list is specified.
1787 Maximum length of the history list is determined by the value
1788 of `history-length', which see.")
1789 (defvar minibuffer-history-sexp-flag nil
1790 "Control whether history list elements are expressions or strings.
1791 If the value of this variable equals current minibuffer depth,
1792 they are expressions; otherwise they are strings.
1793 \(That convention is designed to do the right thing for
1794 recursive uses of the minibuffer.)")
1795 (setq minibuffer-history-variable 'minibuffer-history)
1796 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1797 (defvar minibuffer-history-search-history nil)
1799 (defvar minibuffer-text-before-history nil
1800 "Text that was in this minibuffer before any history commands.
1801 This is nil if there have not yet been any history commands
1802 in this use of the minibuffer.")
1804 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1806 (defun minibuffer-history-initialize ()
1807 (setq minibuffer-text-before-history nil))
1809 (defun minibuffer-avoid-prompt (_new _old)
1810 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1811 (declare (obsolete cursor-intangible-mode "25.1"))
1812 (constrain-to-field nil (point-max)))
1814 (defcustom minibuffer-history-case-insensitive-variables nil
1815 "Minibuffer history variables for which matching should ignore case.
1816 If a history variable is a member of this list, then the
1817 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1818 commands ignore case when searching it, regardless of `case-fold-search'."
1819 :type '(repeat variable)
1822 (defun previous-matching-history-element (regexp n)
1823 "Find the previous history element that matches REGEXP.
1824 \(Previous history elements refer to earlier actions.)
1825 With prefix argument N, search for Nth previous match.
1826 If N is negative, find the next or Nth next match.
1827 Normally, history elements are matched case-insensitively if
1828 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1829 makes the search case-sensitive.
1830 See also `minibuffer-history-case-insensitive-variables'."
1832 (let* ((enable-recursive-minibuffers t)
1833 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1835 minibuffer-local-map
1837 'minibuffer-history-search-history
1838 (car minibuffer-history-search-history))))
1839 ;; Use the last regexp specified, by default, if input is empty.
1840 (list (if (string= regexp "")
1841 (if minibuffer-history-search-history
1842 (car minibuffer-history-search-history)
1843 (user-error "No previous history search regexp"))
1845 (prefix-numeric-value current-prefix-arg))))
1847 (if (and (zerop minibuffer-history-position)
1848 (null minibuffer-text-before-history))
1849 (setq minibuffer-text-before-history
1850 (minibuffer-contents-no-properties)))
1851 (let ((history (symbol-value minibuffer-history-variable))
1853 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1854 ;; On some systems, ignore case for file names.
1855 (if (memq minibuffer-history-variable
1856 minibuffer-history-case-insensitive-variables)
1858 ;; Respect the user's setting for case-fold-search:
1864 (pos minibuffer-history-position))
1867 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1868 (when (= pos prevpos)
1869 (user-error (if (= pos 1)
1870 "No later matching history item"
1871 "No earlier matching history item")))
1873 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1874 (let ((print-level nil))
1875 (prin1-to-string (nth (1- pos) history)))
1876 (nth (1- pos) history)))
1879 (and (string-match regexp match-string)
1881 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1882 (match-beginning 1))))
1884 (setq n (+ n (if (< n 0) 1 -1)))))
1885 (setq minibuffer-history-position pos)
1886 (goto-char (point-max))
1887 (delete-minibuffer-contents)
1888 (insert match-string)
1889 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1890 (if (memq (car (car command-history)) '(previous-matching-history-element
1891 next-matching-history-element))
1892 (setq command-history (cdr command-history))))
1894 (defun next-matching-history-element (regexp n)
1895 "Find the next history element that matches REGEXP.
1896 \(The next history element refers to a more recent action.)
1897 With prefix argument N, search for Nth next match.
1898 If N is negative, find the previous or Nth previous match.
1899 Normally, history elements are matched case-insensitively if
1900 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1901 makes the search case-sensitive."
1903 (let* ((enable-recursive-minibuffers t)
1904 (regexp (read-from-minibuffer "Next element matching (regexp): "
1906 minibuffer-local-map
1908 'minibuffer-history-search-history
1909 (car minibuffer-history-search-history))))
1910 ;; Use the last regexp specified, by default, if input is empty.
1911 (list (if (string= regexp "")
1912 (if minibuffer-history-search-history
1913 (car minibuffer-history-search-history)
1914 (user-error "No previous history search regexp"))
1916 (prefix-numeric-value current-prefix-arg))))
1917 (previous-matching-history-element regexp (- n)))
1919 (defvar minibuffer-temporary-goal-position nil)
1921 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1922 "Function run by `goto-history-element' before consuming default values.
1923 This is useful to dynamically add more elements to the list of default values
1924 when `goto-history-element' reaches the end of this list.
1925 Before calling this function `goto-history-element' sets the variable
1926 `minibuffer-default-add-done' to t, so it will call this function only
1927 once. In special cases, when this function needs to be called more
1928 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1929 overriding the setting of this variable to t in `goto-history-element'.")
1931 (defvar minibuffer-default-add-done nil
1932 "When nil, add more elements to the end of the list of default values.
1933 The value nil causes `goto-history-element' to add more elements to
1934 the list of defaults when it reaches the end of this list. It does
1935 this by calling a function defined by `minibuffer-default-add-function'.")
1937 (make-variable-buffer-local 'minibuffer-default-add-done)
1939 (defun minibuffer-default-add-completions ()
1940 "Return a list of all completions without the default value.
1941 This function is used to add all elements of the completion table to
1942 the end of the list of defaults just after the default value."
1943 (let ((def minibuffer-default)
1944 (all (all-completions ""
1945 minibuffer-completion-table
1946 minibuffer-completion-predicate)))
1949 (cons def (delete def all)))))
1951 (defun goto-history-element (nabs)
1952 "Puts element of the minibuffer history in the minibuffer.
1953 The argument NABS specifies the absolute history position."
1955 (when (and (not minibuffer-default-add-done)
1956 (functionp minibuffer-default-add-function)
1957 (< nabs (- (if (listp minibuffer-default)
1958 (length minibuffer-default)
1960 (setq minibuffer-default-add-done t
1961 minibuffer-default (funcall minibuffer-default-add-function)))
1962 (let ((minimum (if minibuffer-default
1963 (- (if (listp minibuffer-default)
1964 (length minibuffer-default)
1967 elt minibuffer-returned-to-present)
1968 (if (and (zerop minibuffer-history-position)
1969 (null minibuffer-text-before-history))
1970 (setq minibuffer-text-before-history
1971 (minibuffer-contents-no-properties)))
1972 (if (< nabs minimum)
1973 (user-error (if minibuffer-default
1974 "End of defaults; no next item"
1975 "End of history; no default available")))
1976 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
1977 (length (symbol-value minibuffer-history-variable))
1979 (user-error "Beginning of history; no preceding item"))
1980 (unless (memq last-command '(next-history-element
1981 previous-history-element))
1982 (let ((prompt-end (minibuffer-prompt-end)))
1983 (set (make-local-variable 'minibuffer-temporary-goal-position)
1984 (cond ((<= (point) prompt-end) prompt-end)
1987 (goto-char (point-max))
1988 (delete-minibuffer-contents)
1989 (setq minibuffer-history-position nabs)
1991 (setq elt (if (listp minibuffer-default)
1992 (nth (1- (abs nabs)) minibuffer-default)
1993 minibuffer-default)))
1995 (setq elt (or minibuffer-text-before-history ""))
1996 (setq minibuffer-returned-to-present t)
1997 (setq minibuffer-text-before-history nil))
1998 (t (setq elt (nth (1- minibuffer-history-position)
1999 (symbol-value minibuffer-history-variable)))))
2001 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2002 (not minibuffer-returned-to-present))
2003 (let ((print-level nil))
2004 (prin1-to-string elt))
2006 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2008 (defun next-history-element (n)
2009 "Puts next element of the minibuffer history in the minibuffer.
2010 With argument N, it uses the Nth following element."
2013 (goto-history-element (- minibuffer-history-position n))))
2015 (defun previous-history-element (n)
2016 "Puts previous element of the minibuffer history in the minibuffer.
2017 With argument N, it uses the Nth previous element."
2020 (goto-history-element (+ minibuffer-history-position n))))
2022 (defun next-line-or-history-element (&optional arg)
2023 "Move cursor vertically down ARG lines, or to the next history element.
2024 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2025 next element of the minibuffer history in the minibuffer."
2027 (or arg (setq arg 1))
2028 (let* ((old-point (point))
2029 ;; Remember the original goal column of possibly multi-line input
2030 ;; excluding the length of the prompt on the first line.
2031 (prompt-end (minibuffer-prompt-end))
2032 (old-column (unless (and (eolp) (> (point) prompt-end))
2033 (if (= (line-number-at-pos) 1)
2034 (max (- (current-column) (1- prompt-end)) 0)
2035 (current-column)))))
2040 ;; Restore old position since `line-move-visual' moves point to
2041 ;; the end of the line when it fails to go to the next line.
2042 (goto-char old-point)
2043 (next-history-element arg)
2044 ;; Restore the original goal column on the last line
2045 ;; of possibly multi-line input.
2046 (goto-char (point-max))
2048 (if (= (line-number-at-pos) 1)
2049 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2050 (move-to-column old-column)))))))
2052 (defun previous-line-or-history-element (&optional arg)
2053 "Move cursor vertically up ARG lines, or to the previous history element.
2054 When point moves over the top line of multi-line minibuffer, puts ARGth
2055 previous element of the minibuffer history in the minibuffer."
2057 (or arg (setq arg 1))
2058 (let* ((old-point (point))
2059 ;; Remember the original goal column of possibly multi-line input
2060 ;; excluding the length of the prompt on the first line.
2061 (prompt-end (minibuffer-prompt-end))
2062 (old-column (unless (and (eolp) (> (point) prompt-end))
2063 (if (= (line-number-at-pos) 1)
2064 (max (- (current-column) (1- prompt-end)) 0)
2065 (current-column)))))
2068 (previous-line arg))
2069 (beginning-of-buffer
2070 ;; Restore old position since `line-move-visual' moves point to
2071 ;; the beginning of the line when it fails to go to the previous line.
2072 (goto-char old-point)
2073 (previous-history-element arg)
2074 ;; Restore the original goal column on the first line
2075 ;; of possibly multi-line input.
2076 (goto-char (minibuffer-prompt-end))
2078 (if (= (line-number-at-pos) 1)
2079 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2080 (move-to-column old-column))
2081 (goto-char (line-end-position)))))))
2083 (defun next-complete-history-element (n)
2084 "Get next history element which completes the minibuffer before the point.
2085 The contents of the minibuffer after the point are deleted, and replaced
2086 by the new completion."
2088 (let ((point-at-start (point)))
2089 (next-matching-history-element
2091 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2093 ;; next-matching-history-element always puts us at (point-min).
2094 ;; Move to the position we were at before changing the buffer contents.
2095 ;; This is still sensible, because the text before point has not changed.
2096 (goto-char point-at-start)))
2098 (defun previous-complete-history-element (n)
2100 Get previous history element which completes the minibuffer before the point.
2101 The contents of the minibuffer after the point are deleted, and replaced
2102 by the new completion."
2104 (next-complete-history-element (- n)))
2106 ;; For compatibility with the old subr of the same name.
2107 (defun minibuffer-prompt-width ()
2108 "Return the display width of the minibuffer prompt.
2109 Return 0 if current buffer is not a minibuffer."
2110 ;; Return the width of everything before the field at the end of
2111 ;; the buffer; this should be 0 for normal buffers.
2112 (1- (minibuffer-prompt-end)))
2114 ;; isearch minibuffer history
2115 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2117 (defvar minibuffer-history-isearch-message-overlay)
2118 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2120 (defun minibuffer-history-isearch-setup ()
2121 "Set up a minibuffer for using isearch to search the minibuffer history.
2122 Intended to be added to `minibuffer-setup-hook'."
2123 (set (make-local-variable 'isearch-search-fun-function)
2124 'minibuffer-history-isearch-search)
2125 (set (make-local-variable 'isearch-message-function)
2126 'minibuffer-history-isearch-message)
2127 (set (make-local-variable 'isearch-wrap-function)
2128 'minibuffer-history-isearch-wrap)
2129 (set (make-local-variable 'isearch-push-state-function)
2130 'minibuffer-history-isearch-push-state)
2131 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2133 (defun minibuffer-history-isearch-end ()
2134 "Clean up the minibuffer after terminating isearch in the minibuffer."
2135 (if minibuffer-history-isearch-message-overlay
2136 (delete-overlay minibuffer-history-isearch-message-overlay)))
2138 (defun minibuffer-history-isearch-search ()
2139 "Return the proper search function, for isearch in minibuffer history."
2140 (lambda (string bound noerror)
2142 ;; Use standard functions to search within minibuffer text
2143 (isearch-search-fun-default))
2145 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2146 ;; searching forward. Lazy-highlight calls this lambda with the
2147 ;; bound arg, so skip the minibuffer prompt.
2148 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2149 (goto-char (minibuffer-prompt-end)))
2151 ;; 1. First try searching in the initial minibuffer text
2152 (funcall search-fun string
2153 (if isearch-forward bound (minibuffer-prompt-end))
2155 ;; 2. If the above search fails, start putting next/prev history
2156 ;; elements in the minibuffer successively, and search the string
2157 ;; in them. Do this only when bound is nil (i.e. not while
2158 ;; lazy-highlighting search strings in the current minibuffer text).
2163 (cond (isearch-forward
2164 (next-history-element 1)
2165 (goto-char (minibuffer-prompt-end)))
2167 (previous-history-element 1)
2168 (goto-char (point-max))))
2169 (setq isearch-barrier (point) isearch-opoint (point))
2170 ;; After putting the next/prev history element, search
2171 ;; the string in them again, until next-history-element
2172 ;; or previous-history-element raises an error at the
2173 ;; beginning/end of history.
2174 (setq found (funcall search-fun string
2175 (unless isearch-forward
2176 ;; For backward search, don't search
2177 ;; in the minibuffer prompt
2178 (minibuffer-prompt-end))
2180 ;; Return point of the new search result
2182 ;; Return nil when next(prev)-history-element fails
2185 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2186 "Display the minibuffer history search prompt.
2187 If there are no search errors, this function displays an overlay with
2188 the isearch prompt which replaces the original minibuffer prompt.
2189 Otherwise, it displays the standard isearch message returned from
2190 the function `isearch-message'."
2191 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2192 ;; Use standard function `isearch-message' when not in the minibuffer,
2193 ;; or search fails, or has an error (like incomplete regexp).
2194 ;; This function overwrites minibuffer text with isearch message,
2195 ;; so it's possible to see what is wrong in the search string.
2196 (isearch-message c-q-hack ellipsis)
2197 ;; Otherwise, put the overlay with the standard isearch prompt over
2198 ;; the initial minibuffer prompt.
2199 (if (overlayp minibuffer-history-isearch-message-overlay)
2200 (move-overlay minibuffer-history-isearch-message-overlay
2201 (point-min) (minibuffer-prompt-end))
2202 (setq minibuffer-history-isearch-message-overlay
2203 (make-overlay (point-min) (minibuffer-prompt-end)))
2204 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2205 (overlay-put minibuffer-history-isearch-message-overlay
2206 'display (isearch-message-prefix c-q-hack ellipsis))
2207 ;; And clear any previous isearch message.
2210 (defun minibuffer-history-isearch-wrap ()
2211 "Wrap the minibuffer history search when search fails.
2212 Move point to the first history element for a forward search,
2213 or to the last history element for a backward search."
2214 ;; When `minibuffer-history-isearch-search' fails on reaching the
2215 ;; beginning/end of the history, wrap the search to the first/last
2216 ;; minibuffer history element.
2218 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2219 (goto-history-element 0))
2220 (setq isearch-success t)
2221 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2223 (defun minibuffer-history-isearch-push-state ()
2224 "Save a function restoring the state of minibuffer history search.
2225 Save `minibuffer-history-position' to the additional state parameter
2226 in the search status stack."
2227 (let ((pos minibuffer-history-position))
2229 (minibuffer-history-isearch-pop-state cmd pos))))
2231 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2232 "Restore the minibuffer history search state.
2233 Go to the history element by the absolute history position HIST-POS."
2234 (goto-history-element hist-pos))
2237 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2238 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2240 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2241 "Table mapping redo records to the corresponding undo one.
2242 A redo record for undo-in-region maps to t.
2243 A redo record for ordinary undo maps to the following (earlier) undo.")
2245 (defvar undo-in-region nil
2246 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2248 (defvar undo-no-redo nil
2249 "If t, `undo' doesn't go through redo entries.")
2251 (defvar pending-undo-list nil
2252 "Within a run of consecutive undo commands, list remaining to be undone.
2253 If t, we undid all the way to the end of it.")
2255 (defun undo (&optional arg)
2256 "Undo some previous changes.
2257 Repeat this command to undo more changes.
2258 A numeric ARG serves as a repeat count.
2260 In Transient Mark mode when the mark is active, only undo changes within
2261 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2262 as an argument limits undo to changes within the current region."
2264 ;; Make last-command indicate for the next command that this was an undo.
2265 ;; That way, another undo will undo more.
2266 ;; If we get to the end of the undo history and get an error,
2267 ;; another undo command will find the undo history empty
2268 ;; and will get another error. To begin undoing the undos,
2269 ;; you must type some other command.
2270 (let* ((modified (buffer-modified-p))
2271 ;; For an indirect buffer, look in the base buffer for the
2273 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2274 (recent-save (with-current-buffer base-buffer
2275 (recent-auto-save-p)))
2277 ;; If we get an error in undo-start,
2278 ;; the next command should not be a "consecutive undo".
2279 ;; So set `this-command' to something other than `undo'.
2280 (setq this-command 'undo-start)
2282 (unless (and (eq last-command 'undo)
2283 (or (eq pending-undo-list t)
2284 ;; If something (a timer or filter?) changed the buffer
2285 ;; since the previous command, don't continue the undo seq.
2286 (let ((list buffer-undo-list))
2287 (while (eq (car list) nil)
2288 (setq list (cdr list)))
2289 ;; If the last undo record made was made by undo
2290 ;; it shows nothing else happened in between.
2291 (gethash list undo-equiv-table))))
2292 (setq undo-in-region
2293 (or (region-active-p) (and arg (not (numberp arg)))))
2295 (undo-start (region-beginning) (region-end))
2297 ;; get rid of initial undo boundary
2299 ;; If we got this far, the next command should be a consecutive undo.
2300 (setq this-command 'undo)
2301 ;; Check to see whether we're hitting a redo record, and if
2302 ;; so, ask the user whether she wants to skip the redo/undo pair.
2303 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2304 (or (eq (selected-window) (minibuffer-window))
2305 (setq message (format "%s%s!"
2306 (if (or undo-no-redo (not equiv))
2308 (if undo-in-region " in region" ""))))
2309 (when (and (consp equiv) undo-no-redo)
2310 ;; The equiv entry might point to another redo record if we have done
2311 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2312 (while (let ((next (gethash equiv undo-equiv-table)))
2313 (if next (setq equiv next))))
2314 (setq pending-undo-list equiv)))
2317 (prefix-numeric-value arg)
2319 ;; Record the fact that the just-generated undo records come from an
2320 ;; undo operation--that is, they are redo records.
2321 ;; In the ordinary case (not within a region), map the redo
2322 ;; record to the following undos.
2323 ;; I don't know how to do that in the undo-in-region case.
2324 (let ((list buffer-undo-list))
2325 ;; Strip any leading undo boundaries there might be, like we do
2326 ;; above when checking.
2327 (while (eq (car list) nil)
2328 (setq list (cdr list)))
2330 ;; Prevent identity mapping. This can happen if
2331 ;; consecutive nils are erroneously in undo list.
2332 (if (or undo-in-region (eq list pending-undo-list))
2336 ;; Don't specify a position in the undo record for the undo command.
2337 ;; Instead, undoing this should move point to where the change is.
2338 (let ((tail buffer-undo-list)
2341 (when (integerp (car tail))
2342 (let ((pos (car tail)))
2344 (setcdr prev (cdr tail))
2345 (setq buffer-undo-list (cdr tail)))
2346 (setq tail (cdr tail))
2348 (if (eq pos (car tail))
2350 (setcdr prev (cdr tail))
2351 (setq buffer-undo-list (cdr tail)))
2353 (setq tail (cdr tail)))
2355 (setq prev tail tail (cdr tail))))
2356 ;; Record what the current undo list says,
2357 ;; so the next command can tell if the buffer was modified in between.
2358 (and modified (not (buffer-modified-p))
2359 (with-current-buffer base-buffer
2360 (delete-auto-save-file-if-necessary recent-save)))
2361 ;; Display a message announcing success.
2363 (message "%s" message))))
2365 (defun buffer-disable-undo (&optional buffer)
2366 "Make BUFFER stop keeping undo information.
2367 No argument or nil as argument means do this for the current buffer."
2369 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2370 (setq buffer-undo-list t)))
2372 (defun undo-only (&optional arg)
2373 "Undo some previous changes.
2374 Repeat this command to undo more changes.
2375 A numeric ARG serves as a repeat count.
2376 Contrary to `undo', this will not redo a previous undo."
2378 (let ((undo-no-redo t)) (undo arg)))
2380 (defvar undo-in-progress nil
2381 "Non-nil while performing an undo.
2382 Some change-hooks test this variable to do something different.")
2384 (defun undo-more (n)
2385 "Undo back N undo-boundaries beyond what was already undone recently.
2386 Call `undo-start' to get ready to undo recent changes,
2387 then call `undo-more' one or more times to undo them."
2388 (or (listp pending-undo-list)
2389 (user-error (concat "No further undo information"
2390 (and undo-in-region " for region"))))
2391 (let ((undo-in-progress t))
2392 ;; Note: The following, while pulling elements off
2393 ;; `pending-undo-list' will call primitive change functions which
2394 ;; will push more elements onto `buffer-undo-list'.
2395 (setq pending-undo-list (primitive-undo n pending-undo-list))
2396 (if (null pending-undo-list)
2397 (setq pending-undo-list t))))
2399 (defun primitive-undo (n list)
2400 "Undo N records from the front of the list LIST.
2401 Return what remains of the list."
2403 ;; This is a good feature, but would make undo-start
2404 ;; unable to do what is expected.
2405 ;;(when (null (car (list)))
2406 ;; ;; If the head of the list is a boundary, it is the boundary
2407 ;; ;; preceding this command. Get rid of it and don't count it.
2408 ;; (setq list (cdr list))))
2411 ;; In a writable buffer, enable undoing read-only text that is
2412 ;; so because of text properties.
2413 (inhibit-read-only t)
2414 ;; Don't let `intangible' properties interfere with undo.
2415 (inhibit-point-motion-hooks t)
2416 ;; We use oldlist only to check for EQ. ++kfs
2417 (oldlist buffer-undo-list)
2421 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2422 ;; Handle an integer by setting point to that value.
2424 ((pred integerp) (goto-char next))
2425 ;; Element (t . TIME) records previous modtime.
2426 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2427 ;; UNKNOWN_MODTIME_NSECS.
2429 ;; If this records an obsolete save
2430 ;; (not matching the actual disk file)
2431 ;; then don't mark unmodified.
2432 (when (or (equal time (visited-file-modtime))
2434 (equal (list (car time) (cdr time))
2435 (visited-file-modtime))))
2436 (when (fboundp 'unlock-buffer)
2438 (set-buffer-modified-p nil)))
2439 ;; Element (nil PROP VAL BEG . END) is property change.
2440 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2441 (when (or (> (point-min) beg) (< (point-max) end))
2442 (error "Changes to be undone are outside visible portion of buffer"))
2443 (put-text-property beg end prop val))
2444 ;; Element (BEG . END) means range was inserted.
2445 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2446 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2447 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2448 (when (or (> (point-min) beg) (< (point-max) end))
2449 (error "Changes to be undone are outside visible portion of buffer"))
2450 ;; Set point first thing, so that undoing this undo
2451 ;; does not send point back to where it is now.
2453 (delete-region beg end))
2454 ;; Element (apply FUN . ARGS) means call FUN to undo.
2455 (`(apply . ,fun-args)
2456 (let ((currbuff (current-buffer)))
2457 (if (integerp (car fun-args))
2458 ;; Long format: (apply DELTA START END FUN . ARGS).
2459 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2460 (start-mark (copy-marker start nil))
2461 (end-mark (copy-marker end t)))
2462 (when (or (> (point-min) start) (< (point-max) end))
2463 (error "Changes to be undone are outside visible portion of buffer"))
2464 (apply fun args) ;; Use `save-current-buffer'?
2465 ;; Check that the function did what the entry
2466 ;; said it would do.
2467 (unless (and (= start start-mark)
2468 (= (+ delta end) end-mark))
2469 (error "Changes to be undone by function different than announced"))
2470 (set-marker start-mark nil)
2471 (set-marker end-mark nil))
2473 (unless (eq currbuff (current-buffer))
2474 (error "Undo function switched buffer"))
2475 (setq did-apply t)))
2476 ;; Element (STRING . POS) means STRING was deleted.
2477 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2478 (when (let ((apos (abs pos)))
2479 (or (< apos (point-min)) (> apos (point-max))))
2480 (error "Changes to be undone are outside visible portion of buffer"))
2481 (let (valid-marker-adjustments)
2482 ;; Check that marker adjustments which were recorded
2483 ;; with the (STRING . POS) record are still valid, ie
2484 ;; the markers haven't moved. We check their validity
2485 ;; before reinserting the string so as we don't need to
2486 ;; mind marker insertion-type.
2487 (while (and (markerp (car-safe (car list)))
2488 (integerp (cdr-safe (car list))))
2489 (let* ((marker-adj (pop list))
2490 (m (car marker-adj)))
2491 (and (eq (marker-buffer m) (current-buffer))
2493 (push marker-adj valid-marker-adjustments))))
2494 ;; Insert string and adjust point
2502 ;; Adjust the valid marker adjustments
2503 (dolist (adj valid-marker-adjustments)
2504 (set-marker (car adj)
2505 (- (car adj) (cdr adj))))))
2506 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2507 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2508 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2510 ;; Even though these elements are not expected in the undo
2511 ;; list, adjust them to be conservative for the 24.4
2512 ;; release. (Bug#16818)
2513 (when (marker-buffer marker)
2516 (marker-buffer marker))))
2517 (_ (error "Unrecognized entry in undo list %S" next))))
2518 (setq arg (1- arg)))
2519 ;; Make sure an apply entry produces at least one undo entry,
2520 ;; so the test in `undo' for continuing an undo series
2523 (eq oldlist buffer-undo-list))
2524 (setq buffer-undo-list
2525 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2528 ;; Deep copy of a list
2529 (defun undo-copy-list (list)
2530 "Make a copy of undo list LIST."
2531 (mapcar 'undo-copy-list-1 list))
2533 (defun undo-copy-list-1 (elt)
2535 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2538 (defun undo-start (&optional beg end)
2539 "Set `pending-undo-list' to the front of the undo list.
2540 The next call to `undo-more' will undo the most recently made change.
2541 If BEG and END are specified, then only undo elements
2542 that apply to text between BEG and END are used; other undo elements
2543 are ignored. If BEG and END are nil, all undo elements are used."
2544 (if (eq buffer-undo-list t)
2545 (user-error "No undo information in this buffer"))
2546 (setq pending-undo-list
2547 (if (and beg end (not (= beg end)))
2548 (undo-make-selective-list (min beg end) (max beg end))
2551 ;; The positions given in elements of the undo list are the positions
2552 ;; as of the time that element was recorded to undo history. In
2553 ;; general, subsequent buffer edits render those positions invalid in
2554 ;; the current buffer, unless adjusted according to the intervening
2557 ;; Undo in region is a use case that requires adjustments to undo
2558 ;; elements. It must adjust positions of elements in the region based
2559 ;; on newer elements not in the region so as they may be correctly
2560 ;; applied in the current buffer. undo-make-selective-list
2561 ;; accomplishes this with its undo-deltas list of adjustments. An
2562 ;; example undo history from oldest to newest:
2565 ;; 123456789 buffer-undo-list undo-deltas
2566 ;; --------- ---------------- -----------
2567 ;; aaa (1 . 4) (1 . -3)
2568 ;; aaba (3 . 4) N/A (in region)
2569 ;; ccaaba (1 . 3) (1 . -2)
2570 ;; ccaabaddd (7 . 10) (7 . -3)
2571 ;; ccaabdd ("ad" . 6) (6 . 2)
2572 ;; ccaabaddd (6 . 8) (6 . -2)
2573 ;; | |<-- region: "caab", from 2 to 6
2575 ;; When the user starts a run of undos in region,
2576 ;; undo-make-selective-list is called to create the full list of in
2577 ;; region elements. Each element is adjusted forward chronologically
2578 ;; through undo-deltas to determine if it is in the region.
2580 ;; In the above example, the insertion of "b" is (3 . 4) in the
2581 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2582 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2583 ;; . 6) is assessed as in the region and placed in the selective list.
2584 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2585 ;; due to the selected element. The "b" insertion is the only element
2586 ;; fully in the region, so in this example undo-make-selective-list
2587 ;; returns (nil (5 . 6)).
2589 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2590 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2591 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2592 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2593 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2595 ;; More interesting is how to adjust the "ddd" insertion due to the
2596 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2597 ;; If the reinsertion was a manual retyping of "ad", then the total
2598 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2599 ;; the reinsertion was due to undo, one might expect the first "d"
2600 ;; character would again be a part of the "ddd" text, meaning its
2601 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2603 ;; undo-make-selective-list assumes in this situation that "ad" was a
2604 ;; new edit, even if it was inserted because of an undo.
2605 ;; Consequently, if the user undos in region "8 to 10" of the
2606 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2607 ;; "ccaabad", as though the first "d" became detached from the
2608 ;; original "ddd" insertion. This quirk is a FIXME.
2610 (defun undo-make-selective-list (start end)
2611 "Return a list of undo elements for the region START to END.
2612 The elements come from `buffer-undo-list', but we keep only the
2613 elements inside this region, and discard those outside this
2614 region. The elements' positions are adjusted so as the returned
2615 list can be applied to the current buffer."
2616 (let ((ulist buffer-undo-list)
2617 ;; A list of position adjusted undo elements in the region.
2618 (selective-list (list nil))
2619 ;; A list of undo-deltas for out of region undo elements.
2624 (while (gethash ulist undo-equiv-table)
2625 (setq ulist (gethash ulist undo-equiv-table))))
2626 (setq undo-elt (car ulist))
2629 ;; Don't put two nils together in the list
2630 (when (car selective-list)
2631 (push nil selective-list)))
2632 ((and (consp undo-elt) (eq (car undo-elt) t))
2633 ;; This is a "was unmodified" element. Keep it
2634 ;; if we have kept everything thus far.
2635 (when (not undo-deltas)
2636 (push undo-elt selective-list)))
2637 ;; Skip over marker adjustments, instead relying
2638 ;; on finding them after (TEXT . POS) elements
2639 ((markerp (car-safe undo-elt))
2642 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2644 (if (undo-elt-in-region adjusted-undo-elt start end)
2646 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2647 (push adjusted-undo-elt selective-list)
2648 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2649 ;; kept. primitive-undo may discard them later.
2650 (when (and (stringp (car-safe adjusted-undo-elt))
2651 (integerp (cdr-safe adjusted-undo-elt)))
2652 (let ((list-i (cdr ulist)))
2653 (while (markerp (car-safe (car list-i)))
2654 (push (pop list-i) selective-list)))))
2655 (let ((delta (undo-delta undo-elt)))
2656 (when (/= 0 (cdr delta))
2657 (push delta undo-deltas)))))))
2659 (nreverse selective-list)))
2661 (defun undo-elt-in-region (undo-elt start end)
2662 "Determine whether UNDO-ELT falls inside the region START ... END.
2663 If it crosses the edge, we return nil.
2665 Generally this function is not useful for determining
2666 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2667 because markers can be arbitrarily relocated. Instead, pass the
2668 marker adjustment's corresponding (TEXT . POS) element."
2669 (cond ((integerp undo-elt)
2670 (and (>= undo-elt start)
2676 ((stringp (car undo-elt))
2677 ;; (TEXT . POSITION)
2678 (and (>= (abs (cdr undo-elt)) start)
2679 (<= (abs (cdr undo-elt)) end)))
2680 ((and (consp undo-elt) (markerp (car undo-elt)))
2681 ;; (MARKER . ADJUSTMENT)
2682 (<= start (car undo-elt) end))
2683 ((null (car undo-elt))
2684 ;; (nil PROPERTY VALUE BEG . END)
2685 (let ((tail (nthcdr 3 undo-elt)))
2686 (and (>= (car tail) start)
2687 (<= (cdr tail) end))))
2688 ((integerp (car undo-elt))
2690 (and (>= (car undo-elt) start)
2691 (<= (cdr undo-elt) end)))))
2693 (defun undo-elt-crosses-region (undo-elt start end)
2694 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2695 This assumes we have already decided that UNDO-ELT
2696 is not *inside* the region START...END."
2697 (declare (obsolete nil "25.1"))
2698 (cond ((atom undo-elt) nil)
2699 ((null (car undo-elt))
2700 ;; (nil PROPERTY VALUE BEG . END)
2701 (let ((tail (nthcdr 3 undo-elt)))
2702 (and (< (car tail) end)
2703 (> (cdr tail) start))))
2704 ((integerp (car undo-elt))
2706 (and (< (car undo-elt) end)
2707 (> (cdr undo-elt) start)))))
2709 (defun undo-adjust-elt (elt deltas)
2710 "Return adjustment of undo element ELT by the undo DELTAS
2715 (undo-adjust-pos elt deltas))
2717 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2718 (undo-adjust-beg-end beg end deltas))
2719 ;; (TEXT . POSITION)
2720 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2721 (cons text (* (if (< pos 0) -1 1)
2722 (undo-adjust-pos (abs pos) deltas))))
2723 ;; (nil PROPERTY VALUE BEG . END)
2724 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2725 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2726 ;; (apply DELTA START END FUN . ARGS)
2728 ;; All others return same elt
2731 ;; (BEG . END) can adjust to the same positions, commonly when an
2732 ;; insertion was undone and they are out of region, for example:
2735 ;; 123456789 buffer-undo-list undo-deltas
2736 ;; --------- ---------------- -----------
2738 ;; abbaa (2 . 4) (2 . -2)
2739 ;; aaa ("bb" . 2) (2 . 2)
2742 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2743 ;; undo. Further adjustments to such an element should be the same as
2744 ;; for (TEXT . POSITION) elements. The options are:
2746 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2747 ;; analogous to marker insertion-type t.
2749 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2750 ;; marker insertion-type nil.
2752 ;; There was no strong reason to prefer one or the other, except that
2753 ;; the first is more consistent with prior undo in region behavior.
2754 (defun undo-adjust-beg-end (beg end deltas)
2755 "Return cons of adjustments to BEG and END by the undo DELTAS
2757 (let ((adj-beg (undo-adjust-pos beg deltas)))
2758 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2760 (max adj-beg (undo-adjust-pos end deltas t)))))
2762 (defun undo-adjust-pos (pos deltas &optional use-<)
2763 "Return adjustment of POS by the undo DELTAS list, comparing
2764 with < or <= based on USE-<."
2765 (dolist (d deltas pos)
2770 ;; Don't allow pos to become less than the undo-delta
2771 ;; position. This edge case is described in the overview
2773 (max (car d) (- pos (cdr d)))))))
2775 ;; Return the first affected buffer position and the delta for an undo element
2776 ;; delta is defined as the change in subsequent buffer positions if we *did*
2778 (defun undo-delta (undo-elt)
2779 (if (consp undo-elt)
2780 (cond ((stringp (car undo-elt))
2781 ;; (TEXT . POSITION)
2782 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2783 ((integerp (car undo-elt))
2785 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2790 ;;; Default undo-boundary addition
2792 ;; This section adds a new undo-boundary at either after a command is
2793 ;; called or in some cases on a timer called after a change is made in
2795 (defvar-local undo-auto--last-boundary-cause nil
2796 "Describe the cause of the last undo-boundary.
2798 If `explicit', the last boundary was caused by an explicit call to
2799 `undo-boundary', that is one not called by the code in this
2802 If it is equal to `timer', then the last boundary was inserted
2803 by `undo-auto--boundary-timer'.
2805 If it is equal to `command', then the last boundary was inserted
2806 automatically after a command, that is by the code defined in
2809 If it is equal to a list, then the last boundary was inserted by
2810 an amalgamating command. The car of the list is the number of
2811 times an amalgamating command has been called, and the cdr are the
2812 buffers that were changed during the last command.")
2814 (defvar undo-auto-current-boundary-timer nil
2815 "Current timer which will run `undo-auto--boundary-timer' or nil.
2817 If set to non-nil, this will effectively disable the timer.")
2819 (defvar undo-auto--this-command-amalgamating nil
2820 "Non-nil if `this-command' should be amalgamated.
2821 This variable is set to nil by `undo-auto--boundaries' and is set
2822 by `undo-auto-amalgamate'." )
2824 (defun undo-auto--needs-boundary-p ()
2825 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2826 (car-safe buffer-undo-list))
2828 (defun undo-auto--last-boundary-amalgamating-number ()
2829 "Return the number of amalgamating last commands or nil.
2830 Amalgamating commands are, by default, either
2831 `self-insert-command' and `delete-char', but can be any command
2832 that calls `undo-auto-amalgamate'."
2833 (car-safe undo-auto--last-boundary-cause))
2835 (defun undo-auto--ensure-boundary (cause)
2836 "Add an `undo-boundary' to the current buffer if needed.
2837 REASON describes the reason that the boundary is being added; see
2838 `undo-auto--last-boundary' for more information."
2840 (undo-auto--needs-boundary-p))
2841 (let ((last-amalgamating
2842 (undo-auto--last-boundary-amalgamating-number)))
2844 (setq undo-auto--last-boundary-cause
2845 (if (eq 'amalgamate cause)
2847 (if last-amalgamating (1+ last-amalgamating) 0)
2848 undo-auto--undoably-changed-buffers)
2851 (defun undo-auto--boundaries (cause)
2852 "Check recently changed buffers and add a boundary if necessary.
2853 REASON describes the reason that the boundary is being added; see
2854 `undo-last-boundary' for more information."
2855 (dolist (b undo-auto--undoably-changed-buffers)
2856 (when (buffer-live-p b)
2857 (with-current-buffer b
2858 (undo-auto--ensure-boundary cause))))
2859 (setq undo-auto--undoably-changed-buffers nil))
2861 (defun undo-auto--boundary-timer ()
2862 "Timer which will run `undo--auto-boundary-timer'."
2863 (setq undo-auto-current-boundary-timer nil)
2864 (undo-auto--boundaries 'timer))
2866 (defun undo-auto--boundary-ensure-timer ()
2867 "Ensure that the `undo-auto-boundary-timer' is set."
2868 (unless undo-auto-current-boundary-timer
2869 (setq undo-auto-current-boundary-timer
2870 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2872 (defvar undo-auto--undoably-changed-buffers nil
2873 "List of buffers that have changed recently.
2875 This list is maintained by `undo-auto--undoable-change' and
2876 `undo-auto--boundaries' and can be affected by changes to their
2879 See also `undo-auto--buffer-undoably-changed'.")
2881 (defun undo-auto--add-boundary ()
2882 "Add an `undo-boundary' in appropriate buffers."
2883 (undo-auto--boundaries
2884 (let ((amal undo-auto--this-command-amalgamating))
2885 (setq undo-auto--this-command-amalgamating nil)
2890 (defun undo-auto-amalgamate ()
2891 "Amalgamate undo if necessary.
2892 This function can be called before an amalgamating command. It
2893 removes the previous `undo-boundary' if a series of such calls
2894 have been made. By default `self-insert-command' and
2895 `delete-char' are the only amalgamating commands, although this
2896 function could be called by any command wishing to have this
2898 (let ((last-amalgamating-count
2899 (undo-auto--last-boundary-amalgamating-number)))
2900 (setq undo-auto--this-command-amalgamating t)
2902 last-amalgamating-count
2905 (< last-amalgamating-count 20)
2906 (eq this-command last-command))
2907 ;; Amalgamate all buffers that have changed.
2908 (dolist (b (cdr undo-auto--last-boundary-cause))
2909 (when (buffer-live-p b)
2910 (with-current-buffer
2913 ;; The head of `buffer-undo-list' is nil.
2914 ;; `car-safe' doesn't work because
2915 ;; `buffer-undo-list' need not be a list!
2916 (and (listp buffer-undo-list)
2917 (not (car buffer-undo-list)))
2918 (setq buffer-undo-list
2919 (cdr buffer-undo-list))))))
2920 (setq undo-auto--last-boundary-cause 0)))))
2922 (defun undo-auto--undoable-change ()
2923 "Called after every undoable buffer change."
2924 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
2925 (undo-auto--boundary-ensure-timer))
2926 ;; End auto-boundary section
2928 (defcustom undo-ask-before-discard nil
2929 "If non-nil ask about discarding undo info for the current command.
2930 Normally, Emacs discards the undo info for the current command if
2931 it exceeds `undo-outer-limit'. But if you set this option
2932 non-nil, it asks in the echo area whether to discard the info.
2933 If you answer no, there is a slight risk that Emacs might crash, so
2934 only do it if you really want to undo the command.
2936 This option is mainly intended for debugging. You have to be
2937 careful if you use it for other purposes. Garbage collection is
2938 inhibited while the question is asked, meaning that Emacs might
2939 leak memory. So you should make sure that you do not wait
2940 excessively long before answering the question."
2945 (defvar undo-extra-outer-limit nil
2946 "If non-nil, an extra level of size that's ok in an undo item.
2947 We don't ask the user about truncating the undo list until the
2948 current item gets bigger than this amount.
2950 This variable only matters if `undo-ask-before-discard' is non-nil.")
2951 (make-variable-buffer-local 'undo-extra-outer-limit)
2953 ;; When the first undo batch in an undo list is longer than
2954 ;; undo-outer-limit, this function gets called to warn the user that
2955 ;; the undo info for the current command was discarded. Garbage
2956 ;; collection is inhibited around the call, so it had better not do a
2958 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2959 (defun undo-outer-limit-truncate (size)
2960 (if undo-ask-before-discard
2961 (when (or (null undo-extra-outer-limit)
2962 (> size undo-extra-outer-limit))
2963 ;; Don't ask the question again unless it gets even bigger.
2964 ;; This applies, in particular, if the user quits from the question.
2965 ;; Such a quit quits out of GC, but something else will call GC
2966 ;; again momentarily. It will call this function again,
2967 ;; but we don't want to ask the question again.
2968 (setq undo-extra-outer-limit (+ size 50000))
2969 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2970 (yes-or-no-p (format-message
2971 "Buffer `%s' undo info is %d bytes long; discard it? "
2972 (buffer-name) size)))
2973 (progn (setq buffer-undo-list nil)
2974 (setq undo-extra-outer-limit nil)
2977 (display-warning '(undo discard-info)
2980 "Buffer `%s' undo info was %d bytes long.\n"
2982 "The undo info was discarded because it exceeded \
2985 This is normal if you executed a command that made a huge change
2986 to the buffer. In that case, to prevent similar problems in the
2987 future, set `undo-outer-limit' to a value that is large enough to
2988 cover the maximum size of normal changes you expect a single
2989 command to make, but not so large that it might exceed the
2990 maximum memory allotted to Emacs.
2992 If you did not execute any such command, the situation is
2993 probably due to a bug and you should report it.
2995 You can disable the popping up of this buffer by adding the entry
2996 \(undo discard-info) to the user option `warning-suppress-types',
2997 which is defined in the `warnings' library.\n")
2999 (setq buffer-undo-list nil)
3002 (defcustom password-word-equivalents
3003 '("password" "passcode" "passphrase" "pass phrase"
3004 ; These are sorted according to the GNU en_US locale.
3007 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3033 "пароль" ; kk, ru, uk
3048 "List of words equivalent to \"password\".
3049 This is used by Shell mode and other parts of Emacs to recognize
3050 password prompts, including prompts in languages other than
3051 English. Different case choices should not be assumed to be
3052 included; callers should bind `case-fold-search' to t."
3053 :type '(repeat string)
3057 (defvar shell-command-history nil
3058 "History list for some commands that read shell commands.
3060 Maximum length of the history list is determined by the value
3061 of `history-length', which see.")
3063 (defvar shell-command-switch (purecopy "-c")
3064 "Switch used to have the shell execute its command line argument.")
3066 (defvar shell-command-default-error-buffer nil
3067 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3068 This buffer is used when `shell-command' or `shell-command-on-region'
3069 is run interactively. A value of nil means that output to stderr and
3070 stdout will be intermixed in the output stream.")
3072 (declare-function mailcap-file-default-commands "mailcap" (files))
3073 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3075 (defun minibuffer-default-add-shell-commands ()
3076 "Return a list of all commands associated with the current file.
3077 This function is used to add all related commands retrieved by `mailcap'
3078 to the end of the list of defaults just after the default value."
3080 (let* ((filename (if (listp minibuffer-default)
3081 (car minibuffer-default)
3082 minibuffer-default))
3083 (commands (and filename (require 'mailcap nil t)
3084 (mailcap-file-default-commands (list filename)))))
3085 (setq commands (mapcar (lambda (command)
3086 (concat command " " filename))
3088 (if (listp minibuffer-default)
3089 (append minibuffer-default commands)
3090 (cons minibuffer-default commands))))
3092 (declare-function shell-completion-vars "shell" ())
3094 (defvar minibuffer-local-shell-command-map
3095 (let ((map (make-sparse-keymap)))
3096 (set-keymap-parent map minibuffer-local-map)
3097 (define-key map "\t" 'completion-at-point)
3099 "Keymap used for completing shell commands in minibuffer.")
3101 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3102 "Read a shell command from the minibuffer.
3103 The arguments are the same as the ones of `read-from-minibuffer',
3104 except READ and KEYMAP are missing and HIST defaults
3105 to `shell-command-history'."
3107 (minibuffer-with-setup-hook
3109 (shell-completion-vars)
3110 (set (make-local-variable 'minibuffer-default-add-function)
3111 'minibuffer-default-add-shell-commands))
3112 (apply 'read-from-minibuffer prompt initial-contents
3113 minibuffer-local-shell-command-map
3115 (or hist 'shell-command-history)
3118 (defcustom async-shell-command-buffer 'confirm-new-buffer
3119 "What to do when the output buffer is used by another shell command.
3120 This option specifies how to resolve the conflict where a new command
3121 wants to direct its output to the buffer `*Async Shell Command*',
3122 but this buffer is already taken by another running shell command.
3124 The value `confirm-kill-process' is used to ask for confirmation before
3125 killing the already running process and running a new process
3126 in the same buffer, `confirm-new-buffer' for confirmation before running
3127 the command in a new buffer with a name other than the default buffer name,
3128 `new-buffer' for doing the same without confirmation,
3129 `confirm-rename-buffer' for confirmation before renaming the existing
3130 output buffer and running a new command in the default buffer,
3131 `rename-buffer' for doing the same without confirmation."
3132 :type '(choice (const :tag "Confirm killing of running command"
3133 confirm-kill-process)
3134 (const :tag "Confirm creation of a new buffer"
3136 (const :tag "Create a new buffer"
3138 (const :tag "Confirm renaming of existing buffer"
3139 confirm-rename-buffer)
3140 (const :tag "Rename the existing buffer"
3145 (defun async-shell-command (command &optional output-buffer error-buffer)
3146 "Execute string COMMAND asynchronously in background.
3148 Like `shell-command', but adds `&' at the end of COMMAND
3149 to execute it asynchronously.
3151 The output appears in the buffer `*Async Shell Command*'.
3152 That buffer is in shell mode.
3154 You can configure `async-shell-command-buffer' to specify what to do in
3155 case when `*Async Shell Command*' buffer is already taken by another
3156 running shell command. To run COMMAND without displaying the output
3157 in a window you can configure `display-buffer-alist' to use the action
3158 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3160 In Elisp, you will often be better served by calling `start-process'
3161 directly, since it offers more control and does not impose the use of a
3162 shell (with its need to quote arguments)."
3165 (read-shell-command "Async shell command: " nil nil
3169 ((eq major-mode 'dired-mode)
3170 (dired-get-filename nil t)))))
3171 (and filename (file-relative-name filename))))
3173 shell-command-default-error-buffer))
3174 (unless (string-match "&[ \t]*\\'" command)
3175 (setq command (concat command " &")))
3176 (shell-command command output-buffer error-buffer))
3178 (defun shell-command (command &optional output-buffer error-buffer)
3179 "Execute string COMMAND in inferior shell; display output, if any.
3180 With prefix argument, insert the COMMAND's output at point.
3182 If COMMAND ends in `&', execute it asynchronously.
3183 The output appears in the buffer `*Async Shell Command*'.
3184 That buffer is in shell mode. You can also use
3185 `async-shell-command' that automatically adds `&'.
3187 Otherwise, COMMAND is executed synchronously. The output appears in
3188 the buffer `*Shell Command Output*'. If the output is short enough to
3189 display in the echo area (which is determined by the variables
3190 `resize-mini-windows' and `max-mini-window-height'), it is shown
3191 there, but it is nonetheless available in buffer `*Shell Command
3192 Output*' even though that buffer is not automatically displayed.
3194 To specify a coding system for converting non-ASCII characters
3195 in the shell command output, use \\[universal-coding-system-argument] \
3196 before this command.
3198 Noninteractive callers can specify coding systems by binding
3199 `coding-system-for-read' and `coding-system-for-write'.
3201 The optional second argument OUTPUT-BUFFER, if non-nil,
3202 says to put the output in some other buffer.
3203 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
3204 If OUTPUT-BUFFER is not a buffer and not nil,
3205 insert output in current buffer. (This cannot be done asynchronously.)
3206 In either case, the buffer is first erased, and the output is
3207 inserted after point (leaving mark after it).
3209 If the command terminates without error, but generates output,
3210 and you did not specify \"insert it in the current buffer\",
3211 the output can be displayed in the echo area or in its buffer.
3212 If the output is short enough to display in the echo area
3213 \(determined by the variable `max-mini-window-height' if
3214 `resize-mini-windows' is non-nil), it is shown there.
3215 Otherwise,the buffer containing the output is displayed.
3217 If there is output and an error, and you did not specify \"insert it
3218 in the current buffer\", a message about the error goes at the end
3221 If there is no output, or if output is inserted in the current buffer,
3222 then `*Shell Command Output*' is deleted.
3224 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3225 or buffer name to which to direct the command's standard error output.
3226 If it is nil, error output is mingled with regular output.
3227 In an interactive call, the variable `shell-command-default-error-buffer'
3228 specifies the value of ERROR-BUFFER.
3230 In Elisp, you will often be better served by calling `call-process' or
3231 `start-process' directly, since it offers more control and does not impose
3232 the use of a shell (with its need to quote arguments)."
3236 (read-shell-command "Shell command: " nil nil
3240 ((eq major-mode 'dired-mode)
3241 (dired-get-filename nil t)))))
3242 (and filename (file-relative-name filename))))
3244 shell-command-default-error-buffer))
3245 ;; Look for a handler in case default-directory is a remote file name.
3247 (find-file-name-handler (directory-file-name default-directory)
3250 (funcall handler 'shell-command command output-buffer error-buffer)
3251 (if (and output-buffer
3252 (not (or (bufferp output-buffer) (stringp output-buffer))))
3253 ;; Output goes in current buffer.
3257 (expand-file-name "scor"
3258 (or small-temporary-file-directory
3259 temporary-file-directory)))
3261 (barf-if-buffer-read-only)
3263 ;; We do not use -f for csh; we will not support broken use of
3264 ;; .cshrcs. Even the BSD csh manual says to use
3265 ;; "if ($?prompt) exit" before things which are not useful
3266 ;; non-interactively. Besides, if someone wants their other
3267 ;; aliases for shell commands then they can still have them.
3268 (call-process shell-file-name nil
3272 nil shell-command-switch command)
3273 (when (and error-file (file-exists-p error-file))
3274 (if (< 0 (nth 7 (file-attributes error-file)))
3275 (with-current-buffer (get-buffer-create error-buffer)
3276 (let ((pos-from-end (- (point-max) (point))))
3279 ;; Do no formatting while reading error file,
3280 ;; because that can run a shell command, and we
3281 ;; don't want that to cause an infinite recursion.
3282 (format-insert-file error-file nil)
3283 ;; Put point after the inserted errors.
3284 (goto-char (- (point-max) pos-from-end)))
3285 (display-buffer (current-buffer))))
3286 (delete-file error-file))
3287 ;; This is like exchange-point-and-mark, but doesn't
3288 ;; activate the mark. It is cleaner to avoid activation,
3289 ;; even though the command loop would deactivate the mark
3290 ;; because we inserted text.
3291 (goto-char (prog1 (mark t)
3292 (set-marker (mark-marker) (point)
3293 (current-buffer)))))
3294 ;; Output goes in a separate buffer.
3295 ;; Preserve the match data in case called from a program.
3297 (if (string-match "[ \t]*&[ \t]*\\'" command)
3298 ;; Command ending with ampersand means asynchronous.
3299 (let ((buffer (get-buffer-create
3300 (or output-buffer "*Async Shell Command*")))
3301 (directory default-directory)
3303 ;; Remove the ampersand.
3304 (setq command (substring command 0 (match-beginning 0)))
3305 ;; Ask the user what to do with already running process.
3306 (setq proc (get-buffer-process buffer))
3309 ((eq async-shell-command-buffer 'confirm-kill-process)
3310 ;; If will kill a process, query first.
3311 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3313 (error "Shell command in progress")))
3314 ((eq async-shell-command-buffer 'confirm-new-buffer)
3315 ;; If will create a new buffer, query first.
3316 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3317 (setq buffer (generate-new-buffer
3318 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3319 output-buffer "*Async Shell Command*")))
3320 (error "Shell command in progress")))
3321 ((eq async-shell-command-buffer 'new-buffer)
3322 ;; It will create a new buffer.
3323 (setq buffer (generate-new-buffer
3324 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3325 output-buffer "*Async Shell Command*"))))
3326 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3327 ;; If will rename the buffer, query first.
3328 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3330 (with-current-buffer buffer
3332 (setq buffer (get-buffer-create
3333 (or output-buffer "*Async Shell Command*"))))
3334 (error "Shell command in progress")))
3335 ((eq async-shell-command-buffer 'rename-buffer)
3336 ;; It will rename the buffer.
3337 (with-current-buffer buffer
3339 (setq buffer (get-buffer-create
3340 (or output-buffer "*Async Shell Command*"))))))
3341 (with-current-buffer buffer
3342 (setq buffer-read-only nil)
3343 ;; Setting buffer-read-only to nil doesn't suffice
3344 ;; if some text has a non-nil read-only property,
3345 ;; which comint sometimes adds for prompts.
3346 (let ((inhibit-read-only t))
3348 (display-buffer buffer '(nil (allow-no-window . t)))
3349 (setq default-directory directory)
3350 (setq proc (start-process "Shell" buffer shell-file-name
3351 shell-command-switch command))
3352 (setq mode-line-process '(":%s"))
3353 (require 'shell) (shell-mode)
3354 (set-process-sentinel proc 'shell-command-sentinel)
3355 ;; Use the comint filter for proper handling of carriage motion
3356 ;; (see `comint-inhibit-carriage-motion'),.
3357 (set-process-filter proc 'comint-output-filter)
3359 ;; Otherwise, command is executed synchronously.
3360 (shell-command-on-region (point) (point) command
3361 output-buffer nil error-buffer)))))))
3363 (defun display-message-or-buffer (message &optional buffer-name action frame)
3364 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3365 MESSAGE may be either a string or a buffer.
3367 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3368 for maximum height of the echo area, as defined by `max-mini-window-height'
3369 if `resize-mini-windows' is non-nil.
3371 Returns either the string shown in the echo area, or when a pop-up
3372 buffer is used, the window used to display it.
3374 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3375 name of the buffer used to display it in the case where a pop-up buffer
3376 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3377 string and it is displayed in the echo area, it is not specified whether
3378 the contents are inserted into the buffer anyway.
3380 Optional arguments ACTION and FRAME are as for `display-buffer',
3381 and are only used if a pop-up buffer is displayed."
3382 (cond ((and (stringp message) (not (string-match "\n" message)))
3383 ;; Trivial case where we can use the echo area
3384 (message "%s" message))
3385 ((and (stringp message)
3386 (= (string-match "\n" message) (1- (length message))))
3387 ;; Trivial case where we can just remove single trailing newline
3388 (message "%s" (substring message 0 (1- (length message)))))
3391 (with-current-buffer
3392 (if (bufferp message)
3394 (get-buffer-create (or buffer-name "*Message*")))
3396 (unless (bufferp message)
3401 (if (= (buffer-size) 0)
3403 (count-screen-lines nil nil nil (minibuffer-window)))))
3405 ((and (or (<= lines 1)
3407 (if resize-mini-windows
3408 (cond ((floatp max-mini-window-height)
3410 max-mini-window-height))
3411 ((integerp max-mini-window-height)
3412 max-mini-window-height)
3416 ;; Don't use the echo area if the output buffer is
3417 ;; already displayed in the selected frame.
3418 (not (get-buffer-window (current-buffer))))
3420 (goto-char (point-max))
3423 (message "%s" (buffer-substring (point-min) (point))))
3426 (goto-char (point-min))
3427 (display-buffer (current-buffer)
3428 not-this-window frame))))))))
3431 ;; We have a sentinel to prevent insertion of a termination message
3432 ;; in the buffer itself.
3433 (defun shell-command-sentinel (process signal)
3434 (if (memq (process-status process) '(exit signal))
3436 (car (cdr (cdr (process-command process))))
3437 (substring signal 0 -1))))
3439 (defun shell-command-on-region (start end command
3440 &optional output-buffer replace
3441 error-buffer display-error-buffer
3442 region-noncontiguous-p)
3443 "Execute string COMMAND in inferior shell with region as input.
3444 Normally display output (if any) in temp buffer `*Shell Command Output*';
3445 Prefix arg means replace the region with it. Return the exit code of
3448 To specify a coding system for converting non-ASCII characters
3449 in the input and output to the shell command, use \\[universal-coding-system-argument]
3450 before this command. By default, the input (from the current buffer)
3451 is encoded using coding-system specified by `process-coding-system-alist',
3452 falling back to `default-process-coding-system' if no match for COMMAND
3453 is found in `process-coding-system-alist'.
3455 Noninteractive callers can specify coding systems by binding
3456 `coding-system-for-read' and `coding-system-for-write'.
3458 If the command generates output, the output may be displayed
3459 in the echo area or in a buffer.
3460 If the output is short enough to display in the echo area
3461 \(determined by the variable `max-mini-window-height' if
3462 `resize-mini-windows' is non-nil), it is shown there.
3463 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3464 The output is available in that buffer in both cases.
3466 If there is output and an error, a message about the error
3467 appears at the end of the output. If there is no output, or if
3468 output is inserted in the current buffer, the buffer `*Shell
3469 Command Output*' is deleted.
3471 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3472 command's output. If the value is a buffer or buffer name,
3473 put the output there. If the value is nil, use the buffer
3474 `*Shell Command Output*'. Any other value, excluding nil,
3475 means to insert the output in the current buffer. In either case,
3476 the output is inserted after point (leaving mark after it).
3478 Optional fifth arg REPLACE, if non-nil, means to insert the
3479 output in place of text from START to END, putting point and mark
3482 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3483 or buffer name to which to direct the command's standard error
3484 output. If nil, error output is mingled with regular output.
3485 When called interactively, `shell-command-default-error-buffer'
3486 is used for ERROR-BUFFER.
3488 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3489 display the error buffer if there were any errors. When called
3490 interactively, this is t."
3491 (interactive (let (string)
3493 (user-error "The mark is not set now, so there is no region"))
3494 ;; Do this before calling region-beginning
3495 ;; and region-end, in case subprocess output
3496 ;; relocates them while we are in the minibuffer.
3497 (setq string (read-shell-command "Shell command on region: "))
3498 ;; call-interactively recognizes region-beginning and
3499 ;; region-end specially, leaving them in the history.
3500 (list (region-beginning) (region-end)
3504 shell-command-default-error-buffer
3506 (region-noncontiguous-p))))
3510 (expand-file-name "scor"
3511 (or small-temporary-file-directory
3512 temporary-file-directory)))
3515 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3516 (if region-noncontiguous-p
3517 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3521 (call-process-region (point-min) (point-max)
3523 nil shell-command-switch
3525 (setq output (split-string (buffer-string) "\n")))
3527 (funcall region-insert-function output))
3530 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3531 ;; Replace specified region with output from command.
3532 (let ((swap (and replace (< start end))))
3533 ;; Don't muck with mark unless REPLACE says we should.
3535 (and replace (push-mark (point) 'nomsg))
3537 (call-process-region start end shell-file-name replace
3541 nil shell-command-switch command))
3542 ;; It is rude to delete a buffer which the command is not using.
3543 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3544 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3545 ;; (kill-buffer shell-buffer)))
3546 ;; Don't muck with mark unless REPLACE says we should.
3547 (and replace swap (exchange-point-and-mark)))
3548 ;; No prefix argument: put the output in a temp buffer,
3549 ;; replacing its entire contents.
3550 (let ((buffer (get-buffer-create
3551 (or output-buffer "*Shell Command Output*"))))
3553 (if (eq buffer (current-buffer))
3554 ;; If the input is the same buffer as the output,
3555 ;; delete everything but the specified region,
3556 ;; then replace that region with the output.
3557 (progn (setq buffer-read-only nil)
3558 (delete-region (max start end) (point-max))
3559 (delete-region (point-min) (min start end))
3561 (call-process-region (point-min) (point-max)
3566 nil shell-command-switch
3568 ;; Clear the output buffer, then run the command with
3570 (let ((directory default-directory))
3571 (with-current-buffer buffer
3572 (setq buffer-read-only nil)
3573 (if (not output-buffer)
3574 (setq default-directory directory))
3577 (call-process-region start end shell-file-name nil
3579 (list buffer error-file)
3581 nil shell-command-switch command)))
3582 ;; Report the output.
3583 (with-current-buffer buffer
3584 (setq mode-line-process
3585 (cond ((null exit-status)
3587 ((stringp exit-status)
3588 (format " - Signal [%s]" exit-status))
3589 ((not (equal 0 exit-status))
3590 (format " - Exit [%d]" exit-status)))))
3591 (if (with-current-buffer buffer (> (point-max) (point-min)))
3592 ;; There's some output, display it
3593 (display-message-or-buffer buffer)
3594 ;; No output; error?
3597 (< 0 (nth 7 (file-attributes error-file))))
3598 (format "some error output%s"
3599 (if shell-command-default-error-buffer
3600 (format " to the \"%s\" buffer"
3601 shell-command-default-error-buffer)
3604 (cond ((null exit-status)
3605 (message "(Shell command failed with error)"))
3606 ((equal 0 exit-status)
3607 (message "(Shell command succeeded with %s)"
3609 ((stringp exit-status)
3610 (message "(Shell command killed by signal %s)"
3613 (message "(Shell command failed with code %d and %s)"
3614 exit-status output))))
3615 ;; Don't kill: there might be useful info in the undo-log.
3616 ;; (kill-buffer buffer)
3619 (when (and error-file (file-exists-p error-file))
3620 (if (< 0 (nth 7 (file-attributes error-file)))
3621 (with-current-buffer (get-buffer-create error-buffer)
3622 (let ((pos-from-end (- (point-max) (point))))
3625 ;; Do no formatting while reading error file,
3626 ;; because that can run a shell command, and we
3627 ;; don't want that to cause an infinite recursion.
3628 (format-insert-file error-file nil)
3629 ;; Put point after the inserted errors.
3630 (goto-char (- (point-max) pos-from-end)))
3631 (and display-error-buffer
3632 (display-buffer (current-buffer)))))
3633 (delete-file error-file))
3636 (defun shell-command-to-string (command)
3637 "Execute shell command COMMAND and return its output as a string."
3638 (with-output-to-string
3639 (with-current-buffer
3641 (process-file shell-file-name nil t nil shell-command-switch command))))
3643 (defun process-file (program &optional infile buffer display &rest args)
3644 "Process files synchronously in a separate process.
3645 Similar to `call-process', but may invoke a file handler based on
3646 `default-directory'. The current working directory of the
3647 subprocess is `default-directory'.
3649 File names in INFILE and BUFFER are handled normally, but file
3650 names in ARGS should be relative to `default-directory', as they
3651 are passed to the process verbatim. (This is a difference to
3652 `call-process' which does not support file handlers for INFILE
3655 Some file handlers might not support all variants, for example
3656 they might behave as if DISPLAY was nil, regardless of the actual
3658 (let ((fh (find-file-name-handler default-directory 'process-file))
3661 (if fh (apply fh 'process-file program infile buffer display args)
3662 (when infile (setq lc (file-local-copy infile)))
3663 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3664 (make-temp-file "emacs")))
3666 (apply 'call-process program
3668 (if stderr-file (list (car buffer) stderr-file) buffer)
3670 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3671 (when stderr-file (delete-file stderr-file))
3672 (when lc (delete-file lc)))))
3674 (defvar process-file-side-effects t
3675 "Whether a call of `process-file' changes remote files.
3677 By default, this variable is always set to t, meaning that a
3678 call of `process-file' could potentially change any file on a
3679 remote host. When set to nil, a file handler could optimize
3680 its behavior with respect to remote file attribute caching.
3682 You should only ever change this variable with a let-binding;
3683 never with `setq'.")
3685 (defun start-file-process (name buffer program &rest program-args)
3686 "Start a program in a subprocess. Return the process object for it.
3688 Similar to `start-process', but may invoke a file handler based on
3689 `default-directory'. See Info node `(elisp)Magic File Names'.
3691 This handler ought to run PROGRAM, perhaps on the local host,
3692 perhaps on a remote host that corresponds to `default-directory'.
3693 In the latter case, the local part of `default-directory' becomes
3694 the working directory of the process.
3696 PROGRAM and PROGRAM-ARGS might be file names. They are not
3697 objects of file handler invocation. File handlers might not
3698 support pty association, if PROGRAM is nil."
3699 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3700 (if fh (apply fh 'start-file-process name buffer program program-args)
3701 (apply 'start-process name buffer program program-args))))
3705 (defvar tabulated-list-format)
3706 (defvar tabulated-list-entries)
3707 (defvar tabulated-list-sort-key)
3708 (declare-function tabulated-list-init-header "tabulated-list" ())
3709 (declare-function tabulated-list-print "tabulated-list"
3710 (&optional remember-pos update))
3712 (defvar process-menu-query-only nil)
3714 (defvar process-menu-mode-map
3715 (let ((map (make-sparse-keymap)))
3716 (define-key map [?d] 'process-menu-delete-process)
3719 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3720 "Major mode for listing the processes called by Emacs."
3721 (setq tabulated-list-format [("Process" 15 t)
3726 (make-local-variable 'process-menu-query-only)
3727 (setq tabulated-list-sort-key (cons "Process" nil))
3728 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3729 (tabulated-list-init-header))
3731 (defun process-menu-delete-process ()
3732 "Kill process at point in a `list-processes' buffer."
3734 (delete-process (tabulated-list-get-id))
3737 (defun list-processes--refresh ()
3738 "Recompute the list of processes for the Process List buffer.
3739 Also, delete any process that is exited or signaled."
3740 (setq tabulated-list-entries nil)
3741 (dolist (p (process-list))
3742 (cond ((memq (process-status p) '(exit signal closed))
3744 ((or (not process-menu-query-only)
3745 (process-query-on-exit-flag p))
3746 (let* ((buf (process-buffer p))
3747 (type (process-type p))
3748 (name (process-name p))
3749 (status (symbol-name (process-status p)))
3750 (buf-label (if (buffer-live-p buf)
3751 `(,(buffer-name buf)
3753 help-echo ,(format-message
3758 action process-menu-visit-buffer)
3760 (tty (or (process-tty-name p) "--"))
3762 (if (memq type '(network serial))
3763 (let ((contact (process-contact p t)))
3764 (if (eq type 'network)
3766 (if (plist-get contact :type)
3769 (if (plist-get contact :server)
3770 (format "server on %s"
3772 (plist-get contact :host)
3773 (plist-get contact :local)))
3774 (format "connection to %s"
3775 (plist-get contact :host))))
3776 (format "(serial port %s%s)"
3777 (or (plist-get contact :port) "?")
3778 (let ((speed (plist-get contact :speed)))
3780 (format " at %s b/s" speed)
3782 (mapconcat 'identity (process-command p) " "))))
3783 (push (list p (vector name status buf-label tty cmd))
3784 tabulated-list-entries))))))
3786 (defun process-menu-visit-buffer (button)
3787 (display-buffer (button-get button 'process-buffer)))
3789 (defun list-processes (&optional query-only buffer)
3790 "Display a list of all processes that are Emacs sub-processes.
3791 If optional argument QUERY-ONLY is non-nil, only processes with
3792 the query-on-exit flag set are listed.
3793 Any process listed as exited or signaled is actually eliminated
3794 after the listing is made.
3795 Optional argument BUFFER specifies a buffer to use, instead of
3797 The return value is always nil.
3799 This function lists only processes that were launched by Emacs. To
3800 see other processes running on the system, use `list-system-processes'."
3802 (or (fboundp 'process-list)
3803 (error "Asynchronous subprocesses are not supported on this system"))
3804 (unless (bufferp buffer)
3805 (setq buffer (get-buffer-create "*Process List*")))
3806 (with-current-buffer buffer
3808 (setq process-menu-query-only query-only)
3809 (list-processes--refresh)
3810 (tabulated-list-print))
3811 (display-buffer buffer)
3814 ;;;; Prefix commands
3816 (setq prefix-command--needs-update nil)
3817 (setq prefix-command--last-echo nil)
3819 (defun internal-echo-keystrokes-prefix ()
3820 ;; BEWARE: Called directly from C code.
3821 ;; If the return value is non-nil, it means we are in the middle of
3822 ;; a command with prefix, such as a command invoked with prefix-arg.
3823 (if (not prefix-command--needs-update)
3824 prefix-command--last-echo
3825 (setq prefix-command--last-echo
3827 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3828 (lambda (fun) (push (funcall fun) strs)))
3829 (setq strs (delq nil strs))
3830 (when strs (mapconcat #'identity strs " "))))))
3832 (defvar prefix-command-echo-keystrokes-functions nil
3833 "Abnormal hook which constructs the description of the current prefix state.
3834 Each function is called with no argument, should return a string or nil.")
3836 (defun prefix-command-update ()
3837 "Update state of prefix commands.
3838 Call it whenever you change the \"prefix command state\"."
3839 (setq prefix-command--needs-update t))
3841 (defvar prefix-command-preserve-state-hook nil
3842 "Normal hook run when a command needs to preserve the prefix.")
3844 (defun prefix-command-preserve-state ()
3845 "Pass the current prefix command state to the next command.
3846 Should be called by all prefix commands.
3847 Runs `prefix-command-preserve-state-hook'."
3848 (run-hooks 'prefix-command-preserve-state-hook)
3849 ;; If the current command is a prefix command, we don't want the next (real)
3850 ;; command to have `last-command' set to, say, `universal-argument'.
3851 (setq this-command last-command)
3852 (setq real-this-command real-last-command)
3853 (prefix-command-update))
3855 (defun reset-this-command-lengths ()
3856 (declare (obsolete prefix-command-preserve-state "25.1"))
3859 ;;;;; The main prefix command.
3861 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
3863 (add-hook 'prefix-command-echo-keystrokes-functions
3864 #'universal-argument--description)
3865 (defun universal-argument--description ()
3870 (`(,(and (pred integerp) n))
3872 (while (and (> n 4) (= (mod n 4) 0))
3873 (setq str (concat str " C-u"))
3875 (if (= n 4) str (format " %s" prefix-arg))))
3876 (_ (format " %s" prefix-arg))))))
3878 (add-hook 'prefix-command-preserve-state-hook
3879 #'universal-argument--preserve)
3880 (defun universal-argument--preserve ()
3881 (setq prefix-arg current-prefix-arg))
3883 (defvar universal-argument-map
3884 (let ((map (make-sparse-keymap))
3885 (universal-argument-minus
3886 ;; For backward compatibility, minus with no modifiers is an ordinary
3887 ;; command if digits have already been entered.
3888 `(menu-item "" negative-argument
3889 :filter ,(lambda (cmd)
3890 (if (integerp prefix-arg) nil cmd)))))
3891 (define-key map [switch-frame]
3892 (lambda (e) (interactive "e")
3893 (handle-switch-frame e) (universal-argument--mode)))
3894 (define-key map [?\C-u] 'universal-argument-more)
3895 (define-key map [?-] universal-argument-minus)
3896 (define-key map [?0] 'digit-argument)
3897 (define-key map [?1] 'digit-argument)
3898 (define-key map [?2] 'digit-argument)
3899 (define-key map [?3] 'digit-argument)
3900 (define-key map [?4] 'digit-argument)
3901 (define-key map [?5] 'digit-argument)
3902 (define-key map [?6] 'digit-argument)
3903 (define-key map [?7] 'digit-argument)
3904 (define-key map [?8] 'digit-argument)
3905 (define-key map [?9] 'digit-argument)
3906 (define-key map [kp-0] 'digit-argument)
3907 (define-key map [kp-1] 'digit-argument)
3908 (define-key map [kp-2] 'digit-argument)
3909 (define-key map [kp-3] 'digit-argument)
3910 (define-key map [kp-4] 'digit-argument)
3911 (define-key map [kp-5] 'digit-argument)
3912 (define-key map [kp-6] 'digit-argument)
3913 (define-key map [kp-7] 'digit-argument)
3914 (define-key map [kp-8] 'digit-argument)
3915 (define-key map [kp-9] 'digit-argument)
3916 (define-key map [kp-subtract] universal-argument-minus)
3918 "Keymap used while processing \\[universal-argument].")
3920 (defun universal-argument--mode ()
3921 (prefix-command-update)
3922 (set-transient-map universal-argument-map nil))
3924 (defun universal-argument ()
3925 "Begin a numeric argument for the following command.
3926 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3927 \\[universal-argument] following the digits or minus sign ends the argument.
3928 \\[universal-argument] without digits or minus sign provides 4 as argument.
3929 Repeating \\[universal-argument] without digits or minus sign
3930 multiplies the argument by 4 each time.
3931 For some commands, just \\[universal-argument] by itself serves as a flag
3932 which is different in effect from any particular numeric argument.
3933 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3935 (prefix-command-preserve-state)
3936 (setq prefix-arg (list 4))
3937 (universal-argument--mode))
3939 (defun universal-argument-more (arg)
3940 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3941 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3943 (prefix-command-preserve-state)
3944 (setq prefix-arg (if (consp arg)
3945 (list (* 4 (car arg)))
3949 (when (consp prefix-arg) (universal-argument--mode)))
3951 (defun negative-argument (arg)
3952 "Begin a negative numeric argument for the next command.
3953 \\[universal-argument] following digits or minus sign ends the argument."
3955 (prefix-command-preserve-state)
3956 (setq prefix-arg (cond ((integerp arg) (- arg))
3959 (universal-argument--mode))
3961 (defun digit-argument (arg)
3962 "Part of the numeric argument for the next command.
3963 \\[universal-argument] following digits or minus sign ends the argument."
3965 (prefix-command-preserve-state)
3966 (let* ((char (if (integerp last-command-event)
3968 (get last-command-event 'ascii-character)))
3969 (digit (- (logand char ?\177) ?0)))
3970 (setq prefix-arg (cond ((integerp arg)
3972 (if (< arg 0) (- digit) digit)))
3974 ;; Treat -0 as just -, so that -01 will work.
3975 (if (zerop digit) '- (- digit)))
3978 (universal-argument--mode))
3981 (defvar filter-buffer-substring-functions nil
3982 "This variable is a wrapper hook around `buffer-substring--filter'.")
3983 (make-obsolete-variable 'filter-buffer-substring-functions
3984 'filter-buffer-substring-function "24.4")
3986 (defvar filter-buffer-substring-function #'buffer-substring--filter
3987 "Function to perform the filtering in `filter-buffer-substring'.
3988 The function is called with the same 3 arguments (BEG END DELETE)
3989 that `filter-buffer-substring' received. It should return the
3990 buffer substring between BEG and END, after filtering. If DELETE is
3991 non-nil, it should delete the text between BEG and END from the buffer.")
3993 (defvar buffer-substring-filters nil
3994 "List of filter functions for `buffer-substring--filter'.
3995 Each function must accept a single argument, a string, and return a string.
3996 The buffer substring is passed to the first function in the list,
3997 and the return value of each function is passed to the next.
3998 As a special convention, point is set to the start of the buffer text
3999 being operated on (i.e., the first argument of `buffer-substring--filter')
4000 before these functions are called.")
4001 (make-obsolete-variable 'buffer-substring-filters
4002 'filter-buffer-substring-function "24.1")
4004 (defun filter-buffer-substring (beg end &optional delete)
4005 "Return the buffer substring between BEG and END, after filtering.
4006 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4008 This calls the function that `filter-buffer-substring-function' specifies
4009 \(passing the same three arguments that it received) to do the work,
4010 and returns whatever it does. The default function does no filtering,
4011 unless a hook has been set.
4013 Use `filter-buffer-substring' instead of `buffer-substring',
4014 `buffer-substring-no-properties', or `delete-and-extract-region' when
4015 you want to allow filtering to take place. For example, major or minor
4016 modes can use `filter-buffer-substring-function' to extract characters
4017 that are special to a buffer, and should not be copied into other buffers."
4018 (funcall filter-buffer-substring-function beg end delete))
4020 (defun buffer-substring--filter (beg end &optional delete)
4021 "Default function to use for `filter-buffer-substring-function'.
4022 Its arguments and return value are as specified for `filter-buffer-substring'.
4023 This respects the wrapper hook `filter-buffer-substring-functions',
4024 and the abnormal hook `buffer-substring-filters'.
4025 No filtering is done unless a hook says to."
4026 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
4028 ((or delete buffer-substring-filters)
4031 (let ((string (if delete (delete-and-extract-region beg end)
4032 (buffer-substring beg end))))
4033 (dolist (filter buffer-substring-filters)
4034 (setq string (funcall filter string)))
4037 (buffer-substring beg end)))))
4040 ;;;; Window system cut and paste hooks.
4042 (defvar interprogram-cut-function #'gui-select-text
4043 "Function to call to make a killed region available to other programs.
4044 Most window systems provide a facility for cutting and pasting
4045 text between different programs, such as the clipboard on X and
4046 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4048 This variable holds a function that Emacs calls whenever text is
4049 put in the kill ring, to make the new kill available to other
4050 programs. The function takes one argument, TEXT, which is a
4051 string containing the text which should be made available.")
4053 (defvar interprogram-paste-function #'gui-selection-value
4054 "Function to call to get text cut from other programs.
4055 Most window systems provide a facility for cutting and pasting
4056 text between different programs, such as the clipboard on X and
4057 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4059 This variable holds a function that Emacs calls to obtain text
4060 that other programs have provided for pasting. The function is
4061 called with no arguments. If no other program has provided text
4062 to paste, the function should return nil (in which case the
4063 caller, usually `current-kill', should use the top of the Emacs
4064 kill ring). If another program has provided text to paste, the
4065 function should return that text as a string (in which case the
4066 caller should put this string in the kill ring as the latest
4069 The function may also return a list of strings if the window
4070 system supports multiple selections. The first string will be
4071 used as the pasted text, but the other will be placed in the kill
4072 ring for easy access via `yank-pop'.
4074 Note that the function should return a string only if a program
4075 other than Emacs has provided a string for pasting; if Emacs
4076 provided the most recent string, the function should return nil.
4077 If it is difficult to tell whether Emacs or some other program
4078 provided the current string, it is probably good enough to return
4079 nil if the string is equal (according to `string=') to the last
4080 text Emacs provided.")
4084 ;;;; The kill ring data structure.
4086 (defvar kill-ring nil
4087 "List of killed text sequences.
4088 Since the kill ring is supposed to interact nicely with cut-and-paste
4089 facilities offered by window systems, use of this variable should
4090 interact nicely with `interprogram-cut-function' and
4091 `interprogram-paste-function'. The functions `kill-new',
4092 `kill-append', and `current-kill' are supposed to implement this
4093 interaction; you may want to use them instead of manipulating the kill
4096 (defcustom kill-ring-max 60
4097 "Maximum length of kill ring before oldest elements are thrown away."
4101 (defvar kill-ring-yank-pointer nil
4102 "The tail of the kill ring whose car is the last thing yanked.")
4104 (defcustom save-interprogram-paste-before-kill nil
4105 "Save clipboard strings into kill ring before replacing them.
4106 When one selects something in another program to paste it into Emacs,
4107 but kills something in Emacs before actually pasting it,
4108 this selection is gone unless this variable is non-nil,
4109 in which case the other program's selection is saved in the `kill-ring'
4110 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4115 (defcustom kill-do-not-save-duplicates nil
4116 "Do not add a new string to `kill-ring' if it duplicates the last one.
4117 The comparison is done using `equal-including-properties'."
4122 (defun kill-new (string &optional replace)
4123 "Make STRING the latest kill in the kill ring.
4124 Set `kill-ring-yank-pointer' to point to it.
4125 If `interprogram-cut-function' is non-nil, apply it to STRING.
4126 Optional second argument REPLACE non-nil means that STRING will replace
4127 the front of the kill ring, rather than being added to the list.
4129 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4130 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4133 When the yank handler has a non-nil PARAM element, the original STRING
4134 argument is not used by `insert-for-yank'. However, since Lisp code
4135 may access and use elements from the kill ring directly, the STRING
4136 argument should still be a \"useful\" string for such uses."
4137 (unless (and kill-do-not-save-duplicates
4138 ;; Due to text properties such as 'yank-handler that
4139 ;; can alter the contents to yank, comparison using
4140 ;; `equal' is unsafe.
4141 (equal-including-properties string (car kill-ring)))
4142 (if (fboundp 'menu-bar-update-yank-menu)
4143 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4144 (when save-interprogram-paste-before-kill
4145 (let ((interprogram-paste (and interprogram-paste-function
4146 (funcall interprogram-paste-function))))
4147 (when interprogram-paste
4148 (dolist (s (if (listp interprogram-paste)
4149 (nreverse interprogram-paste)
4150 (list interprogram-paste)))
4151 (unless (and kill-do-not-save-duplicates
4152 (equal-including-properties s (car kill-ring)))
4153 (push s kill-ring))))))
4154 (unless (and kill-do-not-save-duplicates
4155 (equal-including-properties string (car kill-ring)))
4156 (if (and replace kill-ring)
4157 (setcar kill-ring string)
4158 (push string kill-ring)
4159 (if (> (length kill-ring) kill-ring-max)
4160 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4161 (setq kill-ring-yank-pointer kill-ring)
4162 (if interprogram-cut-function
4163 (funcall interprogram-cut-function string)))
4165 ;; It has been argued that this should work similar to `self-insert-command'
4166 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4167 (defcustom kill-append-merge-undo nil
4168 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4173 (defun kill-append (string before-p)
4174 "Append STRING to the end of the latest kill in the kill ring.
4175 If BEFORE-P is non-nil, prepend STRING to the kill.
4176 Also removes the last undo boundary in the current buffer,
4177 depending on `kill-append-merge-undo'.
4178 If `interprogram-cut-function' is set, pass the resulting kill to it."
4179 (let* ((cur (car kill-ring)))
4180 (kill-new (if before-p (concat string cur) (concat cur string))
4181 (or (= (length cur) 0)
4182 (equal nil (get-text-property 0 'yank-handler cur))))
4183 (when (and kill-append-merge-undo (not buffer-read-only))
4184 (let ((prev buffer-undo-list)
4185 (next (cdr buffer-undo-list)))
4186 ;; find the next undo boundary
4190 ;; remove this undo boundary
4192 (setcdr prev (cdr next)))))))
4194 (defcustom yank-pop-change-selection nil
4195 "Whether rotating the kill ring changes the window system selection.
4196 If non-nil, whenever the kill ring is rotated (usually via the
4197 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4198 to copy the new kill to the window system selection."
4203 (defun current-kill (n &optional do-not-move)
4204 "Rotate the yanking point by N places, and then return that kill.
4205 If N is zero and `interprogram-paste-function' is set to a
4206 function that returns a string or a list of strings, and if that
4207 function doesn't return nil, then that string (or list) is added
4208 to the front of the kill ring and the string (or first string in
4209 the list) is returned as the latest kill.
4211 If N is not zero, and if `yank-pop-change-selection' is
4212 non-nil, use `interprogram-cut-function' to transfer the
4213 kill at the new yank point into the window system selection.
4215 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4216 move the yanking point; just return the Nth kill forward."
4218 (let ((interprogram-paste (and (= n 0)
4219 interprogram-paste-function
4220 (funcall interprogram-paste-function))))
4221 (if interprogram-paste
4223 ;; Disable the interprogram cut function when we add the new
4224 ;; text to the kill ring, so Emacs doesn't try to own the
4225 ;; selection, with identical text.
4226 (let ((interprogram-cut-function nil))
4227 (if (listp interprogram-paste)
4228 (mapc 'kill-new (nreverse interprogram-paste))
4229 (kill-new interprogram-paste)))
4231 (or kill-ring (error "Kill ring is empty"))
4232 (let ((ARGth-kill-element
4233 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4237 (setq kill-ring-yank-pointer ARGth-kill-element)
4238 (when (and yank-pop-change-selection
4240 interprogram-cut-function)
4241 (funcall interprogram-cut-function (car ARGth-kill-element))))
4242 (car ARGth-kill-element)))))
4246 ;;;; Commands for manipulating the kill ring.
4248 (defcustom kill-read-only-ok nil
4249 "Non-nil means don't signal an error for killing read-only text."
4253 (defun kill-region (beg end &optional region)
4254 "Kill (\"cut\") text between point and mark.
4255 This deletes the text from the buffer and saves it in the kill ring.
4256 The command \\[yank] can retrieve it from there.
4257 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4259 If you want to append the killed region to the last killed text,
4260 use \\[append-next-kill] before \\[kill-region].
4262 Any command that calls this function is a \"kill command\".
4263 If the previous command was also a kill command,
4264 the text killed this time appends to the text killed last time
4265 to make one entry in the kill ring.
4267 The killed text is filtered by `filter-buffer-substring' before it is
4268 saved in the kill ring, so the actual saved text might be different
4269 from what was killed.
4271 If the buffer is read-only, Emacs will beep and refrain from deleting
4272 the text, but put the text in the kill ring anyway. This means that
4273 you can use the killing commands to copy text from a read-only buffer.
4275 Lisp programs should use this function for killing text.
4276 (To delete text, use `delete-region'.)
4277 Supply two arguments, character positions BEG and END indicating the
4278 stretch of text to be killed. If the optional argument REGION is
4279 non-nil, the function ignores BEG and END, and kills the current
4281 ;; Pass mark first, then point, because the order matters when
4282 ;; calling `kill-append'.
4283 (interactive (list (mark) (point) 'region))
4284 (unless (and beg end)
4285 (user-error "The mark is not set now, so there is no region"))
4287 (let ((string (if region
4288 (funcall region-extract-function 'delete)
4289 (filter-buffer-substring beg end 'delete))))
4290 (when string ;STRING is nil if BEG = END
4291 ;; Add that string to the kill ring, one way or another.
4292 (if (eq last-command 'kill-region)
4293 (kill-append string (< end beg))
4295 (when (or string (eq last-command 'kill-region))
4296 (setq this-command 'kill-region))
4297 (setq deactivate-mark t)
4299 ((buffer-read-only text-read-only)
4300 ;; The code above failed because the buffer, or some of the characters
4301 ;; in the region, are read-only.
4302 ;; We should beep, in case the user just isn't aware of this.
4303 ;; However, there's no harm in putting
4304 ;; the region's text in the kill ring, anyway.
4305 (copy-region-as-kill beg end region)
4306 ;; Set this-command now, so it will be set even if we get an error.
4307 (setq this-command 'kill-region)
4308 ;; This should barf, if appropriate, and give us the correct error.
4309 (if kill-read-only-ok
4310 (progn (message "Read only text copied to kill ring") nil)
4311 ;; Signal an error if the buffer is read-only.
4312 (barf-if-buffer-read-only)
4313 ;; If the buffer isn't read-only, the text is.
4314 (signal 'text-read-only (list (current-buffer)))))))
4316 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4317 ;; to get two copies of the text when the user accidentally types M-w and
4318 ;; then corrects it with the intended C-w.
4319 (defun copy-region-as-kill (beg end &optional region)
4320 "Save the region as if killed, but don't kill it.
4321 In Transient Mark mode, deactivate the mark.
4322 If `interprogram-cut-function' is non-nil, also save the text for a window
4323 system cut and paste.
4325 The copied text is filtered by `filter-buffer-substring' before it is
4326 saved in the kill ring, so the actual saved text might be different
4327 from what was in the buffer.
4329 When called from Lisp, save in the kill ring the stretch of text
4330 between BEG and END, unless the optional argument REGION is
4331 non-nil, in which case ignore BEG and END, and save the current
4334 This command's old key binding has been given to `kill-ring-save'."
4335 ;; Pass mark first, then point, because the order matters when
4336 ;; calling `kill-append'.
4337 (interactive (list (mark) (point)
4338 (prefix-numeric-value current-prefix-arg)))
4339 (let ((str (if region
4340 (funcall region-extract-function nil)
4341 (filter-buffer-substring beg end))))
4342 (if (eq last-command 'kill-region)
4343 (kill-append str (< end beg))
4345 (setq deactivate-mark t)
4348 (defun kill-ring-save (beg end &optional region)
4349 "Save the region as if killed, but don't kill it.
4350 In Transient Mark mode, deactivate the mark.
4351 If `interprogram-cut-function' is non-nil, also save the text for a window
4352 system cut and paste.
4354 If you want to append the killed line to the last killed text,
4355 use \\[append-next-kill] before \\[kill-ring-save].
4357 The copied text is filtered by `filter-buffer-substring' before it is
4358 saved in the kill ring, so the actual saved text might be different
4359 from what was in the buffer.
4361 When called from Lisp, save in the kill ring the stretch of text
4362 between BEG and END, unless the optional argument REGION is
4363 non-nil, in which case ignore BEG and END, and save the current
4366 This command is similar to `copy-region-as-kill', except that it gives
4367 visual feedback indicating the extent of the region being copied."
4368 ;; Pass mark first, then point, because the order matters when
4369 ;; calling `kill-append'.
4370 (interactive (list (mark) (point)
4371 (prefix-numeric-value current-prefix-arg)))
4372 (copy-region-as-kill beg end region)
4373 ;; This use of called-interactively-p is correct because the code it
4374 ;; controls just gives the user visual feedback.
4375 (if (called-interactively-p 'interactive)
4376 (indicate-copied-region)))
4378 (defun indicate-copied-region (&optional message-len)
4379 "Indicate that the region text has been copied interactively.
4380 If the mark is visible in the selected window, blink the cursor
4381 between point and mark if there is currently no active region
4384 If the mark lies outside the selected window, display an
4385 informative message containing a sample of the copied text. The
4386 optional argument MESSAGE-LEN, if non-nil, specifies the length
4387 of this sample text; it defaults to 40."
4388 (let ((mark (mark t))
4390 ;; Inhibit quitting so we can make a quit here
4391 ;; look like a C-g typed as a command.
4393 (if (pos-visible-in-window-p mark (selected-window))
4394 ;; Swap point-and-mark quickly so as to show the region that
4395 ;; was selected. Don't do it if the region is highlighted.
4396 (unless (and (region-active-p)
4397 (face-background 'region))
4398 ;; Swap point and mark.
4399 (set-marker (mark-marker) (point) (current-buffer))
4401 (sit-for blink-matching-delay)
4403 (set-marker (mark-marker) mark (current-buffer))
4405 ;; If user quit, deactivate the mark
4406 ;; as C-g would as a command.
4407 (and quit-flag (region-active-p)
4409 (let ((len (min (abs (- mark point))
4410 (or message-len 40))))
4412 ;; Don't say "killed"; that is misleading.
4413 (message "Saved text until \"%s\""
4414 (buffer-substring-no-properties (- mark len) mark))
4415 (message "Saved text from \"%s\""
4416 (buffer-substring-no-properties mark (+ mark len))))))))
4418 (defun append-next-kill (&optional interactive)
4419 "Cause following command, if it kills, to add to previous kill.
4420 If the next command kills forward from point, the kill is
4421 appended to the previous killed text. If the command kills
4422 backward, the kill is prepended. Kill commands that act on the
4423 region, such as `kill-region', are regarded as killing forward if
4424 point is after mark, and killing backward if point is before
4427 If the next command is not a kill command, `append-next-kill' has
4430 The argument is used for internal purposes; do not supply one."
4432 ;; We don't use (interactive-p), since that breaks kbd macros.
4435 (setq this-command 'kill-region)
4436 (message "If the next command is a kill, it will append"))
4437 (setq last-command 'kill-region)))
4439 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4440 "Character set that matches bidirectional formatting control characters.")
4442 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4443 "Character set that matches any character except bidirectional controls.")
4445 (defun squeeze-bidi-context-1 (from to category replacement)
4446 "A subroutine of `squeeze-bidi-context'.
4447 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4448 (let ((pt (copy-marker from))
4449 (limit (copy-marker to))
4458 ;; L and R categories include embedding and
4459 ;; override controls, but we don't want to
4460 ;; replace them, because that might change
4461 ;; the visual order. Likewise with PDF and
4462 ;; isolate controls.
4463 (+ pt (skip-chars-forward
4464 bidi-directional-non-controls-chars
4466 ;; Replace any run of non-RTL characters by a single LRM.
4467 (if (null (re-search-forward category lim1 t))
4468 ;; No more characters of CATEGORY, we are done.
4470 (replace-match replacement nil t)
4471 (move-marker pt (point)))
4473 ;; Skip directional controls, if any.
4475 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4477 (defun squeeze-bidi-context (from to)
4478 "Replace characters between FROM and TO while keeping bidi context.
4480 This function replaces the region of text with as few characters
4481 as possible, while preserving the effect that region will have on
4482 bidirectional display before and after the region."
4483 (let ((start (set-marker (make-marker)
4484 (if (> from 0) from (+ (point-max) from))))
4485 (end (set-marker (make-marker) to))
4486 ;; This is for when they copy text with read-only text
4488 (inhibit-read-only t))
4489 (if (null (marker-position end))
4490 (setq end (point-max-marker)))
4491 ;; Replace each run of non-RTL characters with a single LRM.
4492 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4493 ;; Replace each run of non-LTR characters with a single RLM. Note
4494 ;; that the \cR category includes both the Arabic Letter (AL) and
4495 ;; R characters; here we ignore the distinction between them,
4496 ;; because that distinction only affects Arabic Number (AN)
4497 ;; characters, which are weak and don't affect the reordering.
4498 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4500 (defun line-substring-with-bidi-context (start end &optional no-properties)
4501 "Return buffer text between START and END with its bidi context.
4503 START and END are assumed to belong to the same physical line
4504 of buffer text. This function prepends and appends to the text
4505 between START and END bidi control characters that preserve the
4506 visual order of that text when it is inserted at some other place."
4507 (if (or (< start (point-min))
4508 (> end (point-max)))
4509 (signal 'args-out-of-range (list (current-buffer) start end)))
4510 (let ((buf (current-buffer))
4511 substr para-dir from to)
4514 (setq para-dir (current-bidi-paragraph-direction))
4515 (setq from (line-beginning-position)
4516 to (line-end-position))
4518 ;; If we don't have any mixed directional characters in the
4519 ;; entire line, we can just copy the substring without adding
4521 (if (or (looking-at-p "\\CR*$")
4522 (looking-at-p "\\CL*$"))
4523 (setq substr (if no-properties
4524 (buffer-substring-no-properties start end)
4525 (buffer-substring start end)))
4529 (insert-buffer-substring-no-properties buf from to)
4530 (insert-buffer-substring buf from to))
4531 (squeeze-bidi-context 1 (1+ (- start from)))
4532 (squeeze-bidi-context (- end to) nil)
4533 (buffer-substring 1 (point-max)))))
4535 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4536 ;; (1) force the string to have the same base embedding
4537 ;; direction as the paragraph direction at the source, no matter
4538 ;; what is the paragraph direction at destination; and (2) avoid
4539 ;; affecting the visual order of the surrounding text at
4540 ;; destination if there are characters of different
4541 ;; directionality there.
4542 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4545 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4546 "Return portion of current buffer between START and END with bidi context.
4548 This function works similar to `buffer-substring', but it prepends and
4549 appends to the text bidi directional control characters necessary to
4550 preserve the visual appearance of the text if it is inserted at another
4551 place. This is useful when the buffer substring includes bidirectional
4552 text and control characters that cause non-trivial reordering on display.
4553 If copied verbatim, such text can have a very different visual appearance,
4554 and can also change the visual appearance of the surrounding text at the
4555 destination of the copy.
4557 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4558 the text properties."
4559 (let (line-end substr)
4560 (if (or (< start (point-min))
4561 (> end (point-max)))
4562 (signal 'args-out-of-range (list (current-buffer) start end)))
4565 (setq line-end (min end (line-end-position)))
4566 (while (< start end)
4570 (line-substring-with-bidi-context start line-end
4573 (setq start (point))
4574 (setq line-end (min end (line-end-position))))
4579 (defcustom yank-handled-properties
4580 '((font-lock-face . yank-handle-font-lock-face-property)
4581 (category . yank-handle-category-property))
4582 "List of special text property handling conditions for yanking.
4583 Each element should have the form (PROP . FUN), where PROP is a
4584 property symbol and FUN is a function. When the `yank' command
4585 inserts text into the buffer, it scans the inserted text for
4586 stretches of text that have `eq' values of the text property
4587 PROP; for each such stretch of text, FUN is called with three
4588 arguments: the property's value in that text, and the start and
4589 end positions of the text.
4591 This is done prior to removing the properties specified by
4592 `yank-excluded-properties'."
4594 :type '(repeat (cons (symbol :tag "property symbol")
4598 ;; This is actually used in subr.el but defcustom does not work there.
4599 (defcustom yank-excluded-properties
4600 '(category field follow-link fontified font-lock-face help-echo
4601 intangible invisible keymap local-map mouse-face read-only
4603 "Text properties to discard when yanking.
4604 The value should be a list of text properties to discard or t,
4605 which means to discard all text properties.
4607 See also `yank-handled-properties'."
4608 :type '(choice (const :tag "All" t) (repeat symbol))
4612 (defvar yank-window-start nil)
4613 (defvar yank-undo-function nil
4614 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4615 Function is called with two parameters, START and END corresponding to
4616 the value of the mark and point; it is guaranteed that START <= END.
4617 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4619 (defun yank-pop (&optional arg)
4620 "Replace just-yanked stretch of killed text with a different stretch.
4621 This command is allowed only immediately after a `yank' or a `yank-pop'.
4622 At such a time, the region contains a stretch of reinserted
4623 previously-killed text. `yank-pop' deletes that text and inserts in its
4624 place a different stretch of killed text.
4626 With no argument, the previous kill is inserted.
4627 With argument N, insert the Nth previous kill.
4628 If N is negative, this is a more recent kill.
4630 The sequence of kills wraps around, so that after the oldest one
4631 comes the newest one.
4633 When this command inserts killed text into the buffer, it honors
4634 `yank-excluded-properties' and `yank-handler' as described in the
4635 doc string for `insert-for-yank-1', which see."
4637 (if (not (eq last-command 'yank))
4638 (user-error "Previous command was not a yank"))
4639 (setq this-command 'yank)
4640 (unless arg (setq arg 1))
4641 (let ((inhibit-read-only t)
4642 (before (< (point) (mark t))))
4644 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4645 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4646 (setq yank-undo-function nil)
4647 (set-marker (mark-marker) (point) (current-buffer))
4648 (insert-for-yank (current-kill arg))
4649 ;; Set the window start back where it was in the yank command,
4651 (set-window-start (selected-window) yank-window-start t)
4653 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4654 ;; It is cleaner to avoid activation, even though the command
4655 ;; loop would deactivate the mark because we inserted text.
4656 (goto-char (prog1 (mark t)
4657 (set-marker (mark-marker) (point) (current-buffer))))))
4660 (defun yank (&optional arg)
4661 "Reinsert (\"paste\") the last stretch of killed text.
4662 More precisely, reinsert the most recent kill, which is the
4663 stretch of killed text most recently killed OR yanked. Put point
4664 at the end, and set mark at the beginning without activating it.
4665 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4666 With argument N, reinsert the Nth most recent kill.
4668 When this command inserts text into the buffer, it honors the
4669 `yank-handled-properties' and `yank-excluded-properties'
4670 variables, and the `yank-handler' text property. See
4671 `insert-for-yank-1' for details.
4673 See also the command `yank-pop' (\\[yank-pop])."
4675 (setq yank-window-start (window-start))
4676 ;; If we don't get all the way thru, make last-command indicate that
4677 ;; for the following command.
4678 (setq this-command t)
4680 (insert-for-yank (current-kill (cond
4685 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4686 ;; It is cleaner to avoid activation, even though the command
4687 ;; loop would deactivate the mark because we inserted text.
4688 (goto-char (prog1 (mark t)
4689 (set-marker (mark-marker) (point) (current-buffer)))))
4690 ;; If we do get all the way thru, make this-command indicate that.
4691 (if (eq this-command t)
4692 (setq this-command 'yank))
4695 (defun rotate-yank-pointer (arg)
4696 "Rotate the yanking point in the kill ring.
4697 With ARG, rotate that many kills forward (or backward, if negative)."
4701 ;; Some kill commands.
4703 ;; Internal subroutine of delete-char
4704 (defun kill-forward-chars (arg)
4705 (if (listp arg) (setq arg (car arg)))
4706 (if (eq arg '-) (setq arg -1))
4707 (kill-region (point) (+ (point) arg)))
4709 ;; Internal subroutine of backward-delete-char
4710 (defun kill-backward-chars (arg)
4711 (if (listp arg) (setq arg (car arg)))
4712 (if (eq arg '-) (setq arg -1))
4713 (kill-region (point) (- (point) arg)))
4715 (defcustom backward-delete-char-untabify-method 'untabify
4716 "The method for untabifying when deleting backward.
4717 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4718 `hungry' -- delete all whitespace, both tabs and spaces;
4719 `all' -- delete all whitespace, including tabs, spaces and newlines;
4720 nil -- just delete one character."
4721 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4725 (defun backward-delete-char-untabify (arg &optional killp)
4726 "Delete characters backward, changing tabs into spaces.
4727 The exact behavior depends on `backward-delete-char-untabify-method'.
4728 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4729 Interactively, ARG is the prefix arg (default 1)
4730 and KILLP is t if a prefix arg was specified."
4731 (interactive "*p\nP")
4732 (when (eq backward-delete-char-untabify-method 'untabify)
4735 (while (and (> count 0) (not (bobp)))
4736 (if (= (preceding-char) ?\t)
4737 (let ((col (current-column)))
4739 (setq col (- col (current-column)))
4740 (insert-char ?\s col)
4743 (setq count (1- count))))))
4744 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4745 ((eq backward-delete-char-untabify-method 'all)
4748 (let* ((oldpt (point))
4749 (wh (- oldpt (save-excursion
4750 (skip-chars-backward skip)
4751 (constrain-to-field nil oldpt)))))
4752 (+ arg (if (zerop wh) 0 (1- wh))))
4754 ;; Avoid warning about delete-backward-char
4755 (with-no-warnings (delete-backward-char n killp))))
4757 (defun zap-to-char (arg char)
4758 "Kill up to and including ARGth occurrence of CHAR.
4759 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4760 Goes backward if ARG is negative; error if CHAR not found."
4761 (interactive (list (prefix-numeric-value current-prefix-arg)
4762 (read-char "Zap to char: " t)))
4763 ;; Avoid "obsolete" warnings for translation-table-for-input.
4765 (if (char-table-p translation-table-for-input)
4766 (setq char (or (aref translation-table-for-input char) char))))
4767 (kill-region (point) (progn
4768 (search-forward (char-to-string char) nil nil arg)
4771 ;; kill-line and its subroutines.
4773 (defcustom kill-whole-line nil
4774 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4778 (defun kill-line (&optional arg)
4779 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4780 With prefix argument ARG, kill that many lines from point.
4781 Negative arguments kill lines backward.
4782 With zero argument, kills the text before point on the current line.
4784 When calling from a program, nil means \"no arg\",
4785 a number counts as a prefix arg.
4787 To kill a whole line, when point is not at the beginning, type \
4788 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4790 If `show-trailing-whitespace' is non-nil, this command will just
4791 kill the rest of the current line, even if there are only
4794 If option `kill-whole-line' is non-nil, then this command kills the whole line
4795 including its terminating newline, when used at the beginning of a line
4796 with no argument. As a consequence, you can always kill a whole line
4797 by typing \\[move-beginning-of-line] \\[kill-line].
4799 If you want to append the killed line to the last killed text,
4800 use \\[append-next-kill] before \\[kill-line].
4802 If the buffer is read-only, Emacs will beep and refrain from deleting
4803 the line, but put the line in the kill ring anyway. This means that
4804 you can use this command to copy text from a read-only buffer.
4805 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4808 (kill-region (point)
4809 ;; It is better to move point to the other end of the kill
4810 ;; before killing. That way, in a read-only buffer, point
4811 ;; moves across the text that is copied to the kill ring.
4812 ;; The choice has no effect on undo now that undo records
4813 ;; the value of point from before the command was run.
4816 (forward-visible-line (prefix-numeric-value arg))
4818 (signal 'end-of-buffer nil))
4821 (end-of-visible-line) (point))))
4822 (if (or (save-excursion
4823 ;; If trailing whitespace is visible,
4824 ;; don't treat it as nothing.
4825 (unless show-trailing-whitespace
4826 (skip-chars-forward " \t" end))
4828 (and kill-whole-line (bolp)))
4829 (forward-visible-line 1)
4833 (defun kill-whole-line (&optional arg)
4835 With prefix ARG, kill that many lines starting from the current line.
4836 If ARG is negative, kill backward. Also kill the preceding newline.
4837 \(This is meant to make \\[repeat] work well with negative arguments.)
4838 If ARG is zero, kill current line but exclude the trailing newline."
4840 (or arg (setq arg 1))
4841 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4842 (signal 'end-of-buffer nil))
4843 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4844 (signal 'beginning-of-buffer nil))
4845 (unless (eq last-command 'kill-region)
4847 (setq last-command 'kill-region))
4849 ;; We need to kill in two steps, because the previous command
4850 ;; could have been a kill command, in which case the text
4851 ;; before point needs to be prepended to the current kill
4852 ;; ring entry and the text after point appended. Also, we
4853 ;; need to use save-excursion to avoid copying the same text
4854 ;; twice to the kill ring in read-only buffers.
4856 (kill-region (point) (progn (forward-visible-line 0) (point))))
4857 (kill-region (point) (progn (end-of-visible-line) (point))))
4860 (kill-region (point) (progn (end-of-visible-line) (point))))
4861 (kill-region (point)
4862 (progn (forward-visible-line (1+ arg))
4863 (unless (bobp) (backward-char))
4867 (kill-region (point) (progn (forward-visible-line 0) (point))))
4868 (kill-region (point)
4869 (progn (forward-visible-line arg) (point))))))
4871 (defun forward-visible-line (arg)
4872 "Move forward by ARG lines, ignoring currently invisible newlines only.
4873 If ARG is negative, move backward -ARG lines.
4874 If ARG is zero, move to the beginning of the current line."
4879 (or (zerop (forward-line 1))
4880 (signal 'end-of-buffer nil))
4881 ;; If the newline we just skipped is invisible,
4884 (get-char-property (1- (point)) 'invisible)))
4885 (if (if (eq buffer-invisibility-spec t)
4887 (or (memq prop buffer-invisibility-spec)
4888 (assq prop buffer-invisibility-spec)))
4889 (setq arg (1+ arg))))
4890 (setq arg (1- arg)))
4891 ;; If invisible text follows, and it is a number of complete lines,
4893 (let ((opoint (point)))
4894 (while (and (not (eobp))
4896 (get-char-property (point) 'invisible)))
4897 (if (eq buffer-invisibility-spec t)
4899 (or (memq prop buffer-invisibility-spec)
4900 (assq prop buffer-invisibility-spec)))))
4902 (if (get-text-property (point) 'invisible)
4903 (or (next-single-property-change (point) 'invisible)
4905 (next-overlay-change (point)))))
4907 (goto-char opoint))))
4909 (while (or first (<= arg 0))
4912 (or (zerop (forward-line -1))
4913 (signal 'beginning-of-buffer nil)))
4914 ;; If the newline we just moved to is invisible,
4918 (get-char-property (1- (point)) 'invisible)))
4919 (unless (if (eq buffer-invisibility-spec t)
4921 (or (memq prop buffer-invisibility-spec)
4922 (assq prop buffer-invisibility-spec)))
4923 (setq arg (1+ arg)))))
4925 ;; If invisible text follows, and it is a number of complete lines,
4927 (let ((opoint (point)))
4928 (while (and (not (bobp))
4930 (get-char-property (1- (point)) 'invisible)))
4931 (if (eq buffer-invisibility-spec t)
4933 (or (memq prop buffer-invisibility-spec)
4934 (assq prop buffer-invisibility-spec)))))
4936 (if (get-text-property (1- (point)) 'invisible)
4937 (or (previous-single-property-change (point) 'invisible)
4939 (previous-overlay-change (point)))))
4941 (goto-char opoint)))))
4942 ((beginning-of-buffer end-of-buffer)
4945 (defun end-of-visible-line ()
4946 "Move to end of current visible line."
4948 ;; If the following character is currently invisible,
4949 ;; skip all characters with that same `invisible' property value,
4950 ;; then find the next newline.
4951 (while (and (not (eobp))
4953 (skip-chars-forward "^\n")
4955 (get-char-property (point) 'invisible)))
4956 (if (eq buffer-invisibility-spec t)
4958 (or (memq prop buffer-invisibility-spec)
4959 (assq prop buffer-invisibility-spec))))))
4960 (skip-chars-forward "^\n")
4961 (if (get-text-property (point) 'invisible)
4962 (goto-char (or (next-single-property-change (point) 'invisible)
4964 (goto-char (next-overlay-change (point))))
4967 (defun insert-buffer (buffer)
4968 "Insert after point the contents of BUFFER.
4969 Puts mark after the inserted text.
4970 BUFFER may be a buffer or a buffer name."
4971 (declare (interactive-only insert-buffer-substring))
4975 (barf-if-buffer-read-only)
4976 (read-buffer "Insert buffer: "
4977 (if (eq (selected-window) (next-window))
4978 (other-buffer (current-buffer))
4979 (window-buffer (next-window)))
4983 (insert-buffer-substring (get-buffer buffer))
4987 (defun append-to-buffer (buffer start end)
4988 "Append to specified buffer the text of the region.
4989 It is inserted into that buffer before its point.
4991 When calling from a program, give three arguments:
4992 BUFFER (or buffer name), START and END.
4993 START and END specify the portion of the current buffer to be copied."
4995 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
4996 (region-beginning) (region-end)))
4997 (let* ((oldbuf (current-buffer))
4998 (append-to (get-buffer-create buffer))
4999 (windows (get-buffer-window-list append-to t t))
5002 (with-current-buffer append-to
5003 (setq point (point))
5004 (barf-if-buffer-read-only)
5005 (insert-buffer-substring oldbuf start end)
5006 (dolist (window windows)
5007 (when (= (window-point window) point)
5008 (set-window-point window (point))))))))
5010 (defun prepend-to-buffer (buffer start end)
5011 "Prepend to specified buffer the text of the region.
5012 It is inserted into that buffer after its point.
5014 When calling from a program, give three arguments:
5015 BUFFER (or buffer name), START and END.
5016 START and END specify the portion of the current buffer to be copied."
5017 (interactive "BPrepend to buffer: \nr")
5018 (let ((oldbuf (current-buffer)))
5019 (with-current-buffer (get-buffer-create buffer)
5020 (barf-if-buffer-read-only)
5022 (insert-buffer-substring oldbuf start end)))))
5024 (defun copy-to-buffer (buffer start end)
5025 "Copy to specified buffer the text of the region.
5026 It is inserted into that buffer, replacing existing text there.
5028 When calling from a program, give three arguments:
5029 BUFFER (or buffer name), START and END.
5030 START and END specify the portion of the current buffer to be copied."
5031 (interactive "BCopy to buffer: \nr")
5032 (let ((oldbuf (current-buffer)))
5033 (with-current-buffer (get-buffer-create buffer)
5034 (barf-if-buffer-read-only)
5037 (insert-buffer-substring oldbuf start end)))))
5039 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5041 (defvar activate-mark-hook nil
5042 "Hook run when the mark becomes active.
5043 It is also run at the end of a command, if the mark is active and
5044 it is possible that the region may have changed.")
5046 (defvar deactivate-mark-hook nil
5047 "Hook run when the mark becomes inactive.")
5049 (defun mark (&optional force)
5050 "Return this buffer's mark value as integer, or nil if never set.
5052 In Transient Mark mode, this function signals an error if
5053 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5054 or the argument FORCE is non-nil, it disregards whether the mark
5055 is active, and returns an integer or nil in the usual way.
5057 If you are using this in an editing command, you are most likely making
5058 a mistake; see the documentation of `set-mark'."
5059 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5060 (marker-position (mark-marker))
5061 (signal 'mark-inactive nil)))
5063 ;; Behind display-selections-p.
5065 (defun deactivate-mark (&optional force)
5066 "Deactivate the mark.
5067 If Transient Mark mode is disabled, this function normally does
5068 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5070 Deactivating the mark sets `mark-active' to nil, updates the
5071 primary selection according to `select-active-regions', and runs
5072 `deactivate-mark-hook'.
5074 If Transient Mark mode was temporarily enabled, reset the value
5075 of the variable `transient-mark-mode'; if this causes Transient
5076 Mark mode to be disabled, don't change `mark-active' to nil or
5077 run `deactivate-mark-hook'."
5078 (when (or (region-active-p) force)
5079 (when (and (if (eq select-active-regions 'only)
5080 (eq (car-safe transient-mark-mode) 'only)
5081 select-active-regions)
5083 (display-selections-p))
5084 ;; The var `saved-region-selection', if non-nil, is the text in
5085 ;; the region prior to the last command modifying the buffer.
5086 ;; Set the selection to that, or to the current region.
5087 (cond (saved-region-selection
5088 (if (gui-backend-selection-owner-p 'PRIMARY)
5089 (gui-set-selection 'PRIMARY saved-region-selection))
5090 (setq saved-region-selection nil))
5091 ;; If another program has acquired the selection, region
5092 ;; deactivation should not clobber it (Bug#11772).
5093 ((and (/= (region-beginning) (region-end))
5094 (or (gui-backend-selection-owner-p 'PRIMARY)
5095 (null (gui-backend-selection-exists-p 'PRIMARY))))
5096 (gui-set-selection 'PRIMARY
5097 (funcall region-extract-function nil)))))
5098 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5100 ((eq (car-safe transient-mark-mode) 'only)
5101 (setq transient-mark-mode (cdr transient-mark-mode))
5102 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5103 (kill-local-variable 'transient-mark-mode)))
5104 ((eq transient-mark-mode 'lambda)
5105 (kill-local-variable 'transient-mark-mode)))
5106 (setq mark-active nil)
5107 (run-hooks 'deactivate-mark-hook)
5108 (redisplay--update-region-highlight (selected-window))))
5110 (defun activate-mark (&optional no-tmm)
5112 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5114 (unless (region-active-p)
5115 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5116 (setq mark-active t)
5117 (unless (or transient-mark-mode no-tmm)
5118 (setq-local transient-mark-mode 'lambda))
5119 (run-hooks 'activate-mark-hook))))
5121 (defun set-mark (pos)
5122 "Set this buffer's mark to POS. Don't use this function!
5123 That is to say, don't use this function unless you want
5124 the user to see that the mark has moved, and you want the previous
5125 mark position to be lost.
5127 Normally, when a new mark is set, the old one should go on the stack.
5128 This is why most applications should use `push-mark', not `set-mark'.
5130 Novice Emacs Lisp programmers often try to use the mark for the wrong
5131 purposes. The mark saves a location for the user's convenience.
5132 Most editing commands should not alter the mark.
5133 To remember a location for internal use in the Lisp program,
5134 store it in a Lisp variable. Example:
5136 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5139 (set-marker (mark-marker) pos (current-buffer))
5140 (activate-mark 'no-tmm))
5141 ;; Normally we never clear mark-active except in Transient Mark mode.
5142 ;; But when we actually clear out the mark value too, we must
5143 ;; clear mark-active in any mode.
5145 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5146 ;; it should never be nil if the mark is nil.
5147 (setq mark-active nil)
5148 (set-marker (mark-marker) nil)))
5150 (defun save-mark-and-excursion--save ()
5152 (let ((mark (mark-marker)))
5153 (and (marker-position mark) (copy-marker mark)))
5156 (defun save-mark-and-excursion--restore (saved-mark-info)
5157 (let ((saved-mark (car saved-mark-info))
5158 (omark (marker-position (mark-marker)))
5160 (saved-mark-active (cdr saved-mark-info)))
5162 (if (null saved-mark)
5163 (set-marker (mark-marker) nil)
5164 (setf nmark (marker-position saved-mark))
5165 (set-marker (mark-marker) nmark)
5166 (set-marker saved-mark nil))
5168 (let ((cur-mark-active mark-active))
5169 (setq mark-active saved-mark-active)
5170 ;; If mark is active now, and either was not active or was at a
5171 ;; different place, run the activate hook.
5172 (if saved-mark-active
5173 (when (or (not cur-mark-active)
5174 (not (eq omark nmark)))
5175 (run-hooks 'activate-mark-hook))
5176 ;; If mark has ceased to be active, run deactivate hook.
5177 (when cur-mark-active
5178 (run-hooks 'deactivate-mark-hook))))))
5180 (defmacro save-mark-and-excursion (&rest body)
5181 "Like `save-excursion', but also save and restore the mark state.
5182 This macro does what `save-excursion' did before Emacs 25.1."
5183 (let ((saved-marker-sym (make-symbol "saved-marker")))
5184 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5186 (save-excursion ,@body)
5187 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5189 (defcustom use-empty-active-region nil
5190 "Whether \"region-aware\" commands should act on empty regions.
5191 If nil, region-aware commands treat empty regions as inactive.
5192 If non-nil, region-aware commands treat the region as active as
5193 long as the mark is active, even if the region is empty.
5195 Region-aware commands are those that act on the region if it is
5196 active and Transient Mark mode is enabled, and on the text near
5200 :group 'editing-basics)
5202 (defun use-region-p ()
5203 "Return t if the region is active and it is appropriate to act on it.
5204 This is used by commands that act specially on the region under
5205 Transient Mark mode.
5207 The return value is t if Transient Mark mode is enabled and the
5208 mark is active; furthermore, if `use-empty-active-region' is nil,
5209 the region must not be empty. Otherwise, the return value is nil.
5211 For some commands, it may be appropriate to ignore the value of
5212 `use-empty-active-region'; in that case, use `region-active-p'."
5213 (and (region-active-p)
5214 (or use-empty-active-region (> (region-end) (region-beginning)))))
5216 (defun region-active-p ()
5217 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5219 Some commands act specially on the region when Transient Mark
5220 mode is enabled. Usually, such commands should use
5221 `use-region-p' instead of this function, because `use-region-p'
5222 also checks the value of `use-empty-active-region'."
5223 (and transient-mark-mode mark-active
5224 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5225 ;; without the mark being set (e.g. bug#17324). We really should fix
5226 ;; that problem, but in the mean time, let's make sure we don't say the
5227 ;; region is active when there's no mark.
5228 (progn (cl-assert (mark)) t)))
5230 (defun region-noncontiguous-p ()
5231 "Return non-nil if the region contains several pieces.
5232 An example is a rectangular region handled as a list of
5233 separate contiguous regions for each line."
5234 (> (length (funcall region-extract-function 'bounds)) 1))
5236 (defvar redisplay-unhighlight-region-function
5237 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5239 (defvar redisplay-highlight-region-function
5240 (lambda (start end window rol)
5241 (if (not (overlayp rol))
5242 (let ((nrol (make-overlay start end)))
5243 (funcall redisplay-unhighlight-region-function rol)
5244 (overlay-put nrol 'window window)
5245 (overlay-put nrol 'face 'region)
5246 ;; Normal priority so that a large region doesn't hide all the
5247 ;; overlays within it, but high secondary priority so that if it
5248 ;; ends/starts in the middle of a small overlay, that small overlay
5249 ;; won't hide the region's boundaries.
5250 (overlay-put nrol 'priority '(nil . 100))
5252 (unless (and (eq (overlay-buffer rol) (current-buffer))
5253 (eq (overlay-start rol) start)
5254 (eq (overlay-end rol) end))
5255 (move-overlay rol start end (current-buffer)))
5258 (defun redisplay--update-region-highlight (window)
5259 (let ((rol (window-parameter window 'internal-region-overlay)))
5260 (if (not (and (region-active-p)
5261 (or highlight-nonselected-windows
5262 (eq window (selected-window))
5263 (and (window-minibuffer-p)
5264 (eq window (minibuffer-selected-window))))))
5265 (funcall redisplay-unhighlight-region-function rol)
5266 (let* ((pt (window-point window))
5268 (start (min pt mark))
5271 (funcall redisplay-highlight-region-function
5272 start end window rol)))
5273 (unless (equal new rol)
5274 (set-window-parameter window 'internal-region-overlay
5277 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5278 "Hook run just before redisplay.
5279 It is called in each window that is to be redisplayed. It takes one argument,
5280 which is the window that will be redisplayed. When run, the `current-buffer'
5281 is set to the buffer displayed in that window.")
5283 (defun redisplay--pre-redisplay-functions (windows)
5284 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5286 (with-current-buffer (window-buffer (selected-window))
5287 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5288 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5289 (with-current-buffer (window-buffer win)
5290 (run-hook-with-args 'pre-redisplay-functions win))))))
5292 (add-function :before pre-redisplay-function
5293 #'redisplay--pre-redisplay-functions)
5296 (defvar-local mark-ring nil
5297 "The list of former marks of the current buffer, most recent first.")
5298 (put 'mark-ring 'permanent-local t)
5300 (defcustom mark-ring-max 16
5301 "Maximum size of mark ring. Start discarding off end if gets this big."
5303 :group 'editing-basics)
5305 (defvar global-mark-ring nil
5306 "The list of saved global marks, most recent first.")
5308 (defcustom global-mark-ring-max 16
5309 "Maximum size of global mark ring. \
5310 Start discarding off end if gets this big."
5312 :group 'editing-basics)
5314 (defun pop-to-mark-command ()
5315 "Jump to mark, and pop a new position for mark off the ring.
5316 \(Does not affect global mark ring)."
5319 (user-error "No mark set in this buffer")
5320 (if (= (point) (mark t))
5321 (message "Mark popped"))
5322 (goto-char (mark t))
5325 (defun push-mark-command (arg &optional nomsg)
5326 "Set mark at where point is.
5327 If no prefix ARG and mark is already set there, just activate it.
5328 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5330 (let ((mark (mark t)))
5331 (if (or arg (null mark) (/= mark (point)))
5332 (push-mark nil nomsg t)
5333 (activate-mark 'no-tmm)
5335 (message "Mark activated")))))
5337 (defcustom set-mark-command-repeat-pop nil
5338 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5339 That means that C-u \\[set-mark-command] \\[set-mark-command]
5340 will pop the mark twice, and
5341 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5342 will pop the mark three times.
5344 A value of nil means \\[set-mark-command]'s behavior does not change
5345 after C-u \\[set-mark-command]."
5347 :group 'editing-basics)
5349 (defun set-mark-command (arg)
5350 "Set the mark where point is, or jump to the mark.
5351 Setting the mark also alters the region, which is the text
5352 between point and mark; this is the closest equivalent in
5353 Emacs to what some editors call the \"selection\".
5355 With no prefix argument, set the mark at point, and push the
5356 old mark position on local mark ring. Also push the old mark on
5357 global mark ring, if the previous mark was set in another buffer.
5359 When Transient Mark Mode is off, immediately repeating this
5360 command activates `transient-mark-mode' temporarily.
5362 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5363 jump to the mark, and set the mark from
5364 position popped off the local mark ring (this does not affect the global
5365 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5366 mark ring (see `pop-global-mark').
5368 If `set-mark-command-repeat-pop' is non-nil, repeating
5369 the \\[set-mark-command] command with no prefix argument pops the next position
5370 off the local (or global) mark ring and jumps there.
5372 With \\[universal-argument] \\[universal-argument] as prefix
5373 argument, unconditionally set mark where point is, even if
5374 `set-mark-command-repeat-pop' is non-nil.
5376 Novice Emacs Lisp programmers often try to use the mark for the wrong
5377 purposes. See the documentation of `set-mark' for more information."
5379 (cond ((eq transient-mark-mode 'lambda)
5380 (kill-local-variable 'transient-mark-mode))
5381 ((eq (car-safe transient-mark-mode) 'only)
5384 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5385 (push-mark-command nil))
5386 ((not (eq this-command 'set-mark-command))
5388 (pop-to-mark-command)
5389 (push-mark-command t)))
5390 ((and set-mark-command-repeat-pop
5391 (eq last-command 'pop-global-mark)
5393 (setq this-command 'pop-global-mark)
5395 ((or (and set-mark-command-repeat-pop
5396 (eq last-command 'pop-to-mark-command))
5398 (setq this-command 'pop-to-mark-command)
5399 (pop-to-mark-command))
5400 ((eq last-command 'set-mark-command)
5401 (if (region-active-p)
5404 (message "Mark deactivated"))
5406 (message "Mark activated")))
5408 (push-mark-command nil))))
5410 (defun push-mark (&optional location nomsg activate)
5411 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5412 If the last global mark pushed was not in the current buffer,
5413 also push LOCATION on the global mark ring.
5414 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5416 Novice Emacs Lisp programmers often try to use the mark for the wrong
5417 purposes. See the documentation of `set-mark' for more information.
5419 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5420 (unless (null (mark t))
5421 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5422 (when (> (length mark-ring) mark-ring-max)
5423 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5424 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5425 (set-marker (mark-marker) (or location (point)) (current-buffer))
5426 ;; Now push the mark on the global mark ring.
5427 (if (and global-mark-ring
5428 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5429 ;; The last global mark pushed was in this same buffer.
5430 ;; Don't push another one.
5432 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5433 (when (> (length global-mark-ring) global-mark-ring-max)
5434 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5435 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5436 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5437 (message "Mark set"))
5438 (if (or activate (not transient-mark-mode))
5439 (set-mark (mark t)))
5443 "Pop off mark ring into the buffer's actual mark.
5444 Does not set point. Does nothing if mark ring is empty."
5446 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5447 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5448 (move-marker (car mark-ring) nil)
5449 (if (null (mark t)) (ding))
5450 (setq mark-ring (cdr mark-ring)))
5453 (define-obsolete-function-alias
5454 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5455 (defun exchange-point-and-mark (&optional arg)
5456 "Put the mark where point is now, and point where the mark is now.
5457 This command works even when the mark is not active,
5458 and it reactivates the mark.
5460 If Transient Mark mode is on, a prefix ARG deactivates the mark
5461 if it is active, and otherwise avoids reactivating it. If
5462 Transient Mark mode is off, a prefix ARG enables Transient Mark
5465 (let ((omark (mark t))
5466 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5468 (user-error "No mark set in this buffer"))
5471 (cond (temp-highlight
5472 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5473 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5474 (not (or arg (region-active-p))))
5476 (t (activate-mark)))
5479 (defcustom shift-select-mode t
5480 "When non-nil, shifted motion keys activate the mark momentarily.
5482 While the mark is activated in this way, any shift-translated point
5483 motion key extends the region, and if Transient Mark mode was off, it
5484 is temporarily turned on. Furthermore, the mark will be deactivated
5485 by any subsequent point motion key that was not shift-translated, or
5486 by any action that normally deactivates the mark in Transient Mark mode.
5488 See `this-command-keys-shift-translated' for the meaning of
5491 :group 'editing-basics)
5493 (defun handle-shift-selection ()
5494 "Activate/deactivate mark depending on invocation thru shift translation.
5495 This function is called by `call-interactively' when a command
5496 with a `^' character in its `interactive' spec is invoked, before
5497 running the command itself.
5499 If `shift-select-mode' is enabled and the command was invoked
5500 through shift translation, set the mark and activate the region
5501 temporarily, unless it was already set in this way. See
5502 `this-command-keys-shift-translated' for the meaning of shift
5505 Otherwise, if the region has been activated temporarily,
5506 deactivate it, and restore the variable `transient-mark-mode' to
5508 (cond ((and shift-select-mode this-command-keys-shift-translated)
5509 (unless (and mark-active
5510 (eq (car-safe transient-mark-mode) 'only))
5511 (setq-local transient-mark-mode
5513 (unless (eq transient-mark-mode 'lambda)
5514 transient-mark-mode)))
5515 (push-mark nil nil t)))
5516 ((eq (car-safe transient-mark-mode) 'only)
5517 (setq transient-mark-mode (cdr transient-mark-mode))
5518 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5519 (kill-local-variable 'transient-mark-mode))
5520 (deactivate-mark))))
5522 (define-minor-mode transient-mark-mode
5523 "Toggle Transient Mark mode.
5524 With a prefix argument ARG, enable Transient Mark mode if ARG is
5525 positive, and disable it otherwise. If called from Lisp, enable
5526 Transient Mark mode if ARG is omitted or nil.
5528 Transient Mark mode is a global minor mode. When enabled, the
5529 region is highlighted with the `region' face whenever the mark
5530 is active. The mark is \"deactivated\" by changing the buffer,
5531 and after certain other operations that set the mark but whose
5532 main purpose is something else--for example, incremental search,
5533 \\[beginning-of-buffer], and \\[end-of-buffer].
5535 You can also deactivate the mark by typing \\[keyboard-quit] or
5536 \\[keyboard-escape-quit].
5538 Many commands change their behavior when Transient Mark mode is
5539 in effect and the mark is active, by acting on the region instead
5540 of their usual default part of the buffer's text. Examples of
5541 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5542 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5543 To see the documentation of commands which are sensitive to the
5544 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5545 or \"mark.*active\" at the prompt."
5547 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5548 :variable (default-value 'transient-mark-mode))
5550 (defvar widen-automatically t
5551 "Non-nil means it is ok for commands to call `widen' when they want to.
5552 Some commands will do this in order to go to positions outside
5553 the current accessible part of the buffer.
5555 If `widen-automatically' is nil, these commands will do something else
5556 as a fallback, and won't change the buffer bounds.")
5558 (defvar non-essential nil
5559 "Whether the currently executing code is performing an essential task.
5560 This variable should be non-nil only when running code which should not
5561 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5562 user for a password when we are simply scanning a set of files in the
5563 background or displaying possible completions before the user even asked
5566 (defun pop-global-mark ()
5567 "Pop off global mark ring and jump to the top location."
5569 ;; Pop entries which refer to non-existent buffers.
5570 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5571 (setq global-mark-ring (cdr global-mark-ring)))
5572 (or global-mark-ring
5573 (error "No global mark set"))
5574 (let* ((marker (car global-mark-ring))
5575 (buffer (marker-buffer marker))
5576 (position (marker-position marker)))
5577 (setq global-mark-ring (nconc (cdr global-mark-ring)
5578 (list (car global-mark-ring))))
5580 (or (and (>= position (point-min))
5581 (<= position (point-max)))
5582 (if widen-automatically
5584 (error "Global mark position is outside accessible part of buffer")))
5585 (goto-char position)
5586 (switch-to-buffer buffer)))
5588 (defcustom next-line-add-newlines nil
5589 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5592 :group 'editing-basics)
5594 (defun next-line (&optional arg try-vscroll)
5595 "Move cursor vertically down ARG lines.
5596 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5597 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5598 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5599 function will not vscroll.
5603 If there is no character in the target line exactly under the current column,
5604 the cursor is positioned after the character in that line which spans this
5605 column, or at the end of the line if it is not long enough.
5606 If there is no line in the buffer after this one, behavior depends on the
5607 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5608 to create a line, and moves the cursor to that line. Otherwise it moves the
5609 cursor to the end of the buffer.
5611 If the variable `line-move-visual' is non-nil, this command moves
5612 by display lines. Otherwise, it moves by buffer lines, without
5613 taking variable-width characters or continued lines into account.
5615 The command \\[set-goal-column] can be used to create
5616 a semipermanent goal column for this command.
5617 Then instead of trying to move exactly vertically (or as close as possible),
5618 this command moves to the specified goal column (or as close as possible).
5619 The goal column is stored in the variable `goal-column', which is nil
5620 when there is no goal column. Note that setting `goal-column'
5621 overrides `line-move-visual' and causes this command to move by buffer
5622 lines rather than by display lines."
5623 (declare (interactive-only forward-line))
5624 (interactive "^p\np")
5625 (or arg (setq arg 1))
5626 (if (and next-line-add-newlines (= arg 1))
5627 (if (save-excursion (end-of-line) (eobp))
5628 ;; When adding a newline, don't expand an abbrev.
5629 (let ((abbrev-mode nil))
5631 (insert (if use-hard-newlines hard-newline "\n")))
5632 (line-move arg nil nil try-vscroll))
5633 (if (called-interactively-p 'interactive)
5635 (line-move arg nil nil try-vscroll)
5636 ((beginning-of-buffer end-of-buffer)
5637 (signal (car err) (cdr err))))
5638 (line-move arg nil nil try-vscroll)))
5641 (defun previous-line (&optional arg try-vscroll)
5642 "Move cursor vertically up ARG lines.
5643 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5644 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5645 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5646 function will not vscroll.
5650 If there is no character in the target line exactly over the current column,
5651 the cursor is positioned after the character in that line which spans this
5652 column, or at the end of the line if it is not long enough.
5654 If the variable `line-move-visual' is non-nil, this command moves
5655 by display lines. Otherwise, it moves by buffer lines, without
5656 taking variable-width characters or continued lines into account.
5658 The command \\[set-goal-column] can be used to create
5659 a semipermanent goal column for this command.
5660 Then instead of trying to move exactly vertically (or as close as possible),
5661 this command moves to the specified goal column (or as close as possible).
5662 The goal column is stored in the variable `goal-column', which is nil
5663 when there is no goal column. Note that setting `goal-column'
5664 overrides `line-move-visual' and causes this command to move by buffer
5665 lines rather than by display lines."
5666 (declare (interactive-only
5667 "use `forward-line' with negative argument instead."))
5668 (interactive "^p\np")
5669 (or arg (setq arg 1))
5670 (if (called-interactively-p 'interactive)
5672 (line-move (- arg) nil nil try-vscroll)
5673 ((beginning-of-buffer end-of-buffer)
5674 (signal (car err) (cdr err))))
5675 (line-move (- arg) nil nil try-vscroll))
5678 (defcustom track-eol nil
5679 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5680 This means moving to the end of each line moved onto.
5681 The beginning of a blank line does not count as the end of a line.
5682 This has no effect when the variable `line-move-visual' is non-nil."
5684 :group 'editing-basics)
5686 (defcustom goal-column nil
5687 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5688 A non-nil setting overrides the variable `line-move-visual', which see."
5689 :type '(choice integer
5690 (const :tag "None" nil))
5691 :group 'editing-basics)
5692 (make-variable-buffer-local 'goal-column)
5694 (defvar temporary-goal-column 0
5695 "Current goal column for vertical motion.
5696 It is the column where point was at the start of the current run
5697 of vertical motion commands.
5699 When moving by visual lines via the function `line-move-visual', it is a cons
5700 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5701 divided by the default column width, and HSCROLL is the number of
5702 columns by which window is scrolled from left margin.
5704 When the `track-eol' feature is doing its job, the value is
5705 `most-positive-fixnum'.")
5707 (defcustom line-move-ignore-invisible t
5708 "Non-nil means commands that move by lines ignore invisible newlines.
5709 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5710 as if newlines that are invisible didn't exist, and count
5711 only visible newlines. Thus, moving across across 2 newlines
5712 one of which is invisible will be counted as a one-line move.
5713 Also, a non-nil value causes invisible text to be ignored when
5714 counting columns for the purposes of keeping point in the same
5715 column by \\[next-line] and \\[previous-line].
5717 Outline mode sets this."
5719 :group 'editing-basics)
5721 (defcustom line-move-visual t
5722 "When non-nil, `line-move' moves point by visual lines.
5723 This movement is based on where the cursor is displayed on the
5724 screen, instead of relying on buffer contents alone. It takes
5725 into account variable-width characters and line continuation.
5726 If nil, `line-move' moves point by logical lines.
5727 A non-nil setting of `goal-column' overrides the value of this variable
5728 and forces movement by logical lines.
5729 A window that is horizontally scrolled also forces movement by logical
5732 :group 'editing-basics
5735 ;; Only used if display-graphic-p.
5736 (declare-function font-info "font.c" (name &optional frame))
5738 (defun default-font-height ()
5739 "Return the height in pixels of the current buffer's default face font.
5741 If the default font is remapped (see `face-remapping-alist'), the
5742 function returns the height of the remapped face."
5743 (let ((default-font (face-font 'default)))
5745 ((and (display-multi-font-p)
5746 ;; Avoid calling font-info if the frame's default font was
5747 ;; not changed since the frame was created. That's because
5748 ;; font-info is expensive for some fonts, see bug #14838.
5749 (not (string= (frame-parameter nil 'font) default-font)))
5750 (aref (font-info default-font) 3))
5751 (t (frame-char-height)))))
5753 (defun default-font-width ()
5754 "Return the width in pixels of the current buffer's default face font.
5756 If the default font is remapped (see `face-remapping-alist'), the
5757 function returns the width of the remapped face."
5758 (let ((default-font (face-font 'default)))
5760 ((and (display-multi-font-p)
5761 ;; Avoid calling font-info if the frame's default font was
5762 ;; not changed since the frame was created. That's because
5763 ;; font-info is expensive for some fonts, see bug #14838.
5764 (not (string= (frame-parameter nil 'font) default-font)))
5765 (let* ((info (font-info (face-font 'default)))
5766 (width (aref info 11)))
5770 (t (frame-char-width)))))
5772 (defun default-line-height ()
5773 "Return the pixel height of current buffer's default-face text line.
5775 The value includes `line-spacing', if any, defined for the buffer
5777 (let ((dfh (default-font-height))
5778 (lsp (if (display-graphic-p)
5780 (default-value 'line-spacing)
5781 (frame-parameter nil 'line-spacing)
5785 (setq lsp (truncate (* (frame-char-height) lsp))))
5788 (defun window-screen-lines ()
5789 "Return the number of screen lines in the text area of the selected window.
5791 This is different from `window-text-height' in that this function counts
5792 lines in units of the height of the font used by the default face displayed
5793 in the window, not in units of the frame's default font, and also accounts
5794 for `line-spacing', if any, defined for the window's buffer or frame.
5796 The value is a floating-point number."
5797 (let ((edges (window-inside-pixel-edges))
5798 (dlh (default-line-height)))
5799 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5801 ;; Returns non-nil if partial move was done.
5802 (defun line-move-partial (arg noerror to-end)
5804 ;; Move backward (up).
5805 ;; If already vscrolled, reduce vscroll
5806 (let ((vs (window-vscroll nil t))
5807 (dlh (default-line-height)))
5809 (set-window-vscroll nil (- vs dlh) t)))
5811 ;; Move forward (down).
5812 (let* ((lh (window-line-height -1))
5817 (this-lh (window-line-height))
5818 (this-height (car this-lh))
5819 (this-ypos (nth 2 this-lh))
5820 (dlh (default-line-height))
5821 (wslines (window-screen-lines))
5822 (edges (window-inside-pixel-edges))
5823 (winh (- (nth 3 edges) (nth 1 edges) 1))
5825 (if (> (mod wslines 1.0) 0.0)
5826 (setq wslines (round (+ wslines 0.5))))
5831 (<= this-ypos (- dlh)))
5833 (let ((wend (pos-visible-in-window-p t nil t)))
5834 (setq rbot (nth 3 wend)
5836 vpos (nth 5 wend))))
5838 (let ((wstart (pos-visible-in-window-p nil nil t)))
5839 (setq this-ypos (nth 2 wstart)
5840 this-height (nth 4 wstart))))
5843 (let ((ppos (posn-at-point))
5845 (setq col-row (posn-actual-col-row ppos))
5847 (- (cdr col-row) (window-vscroll))
5848 (cdr (posn-col-row ppos))))))
5849 ;; VPOS > 0 means the last line is only partially visible.
5850 ;; But if the part that is visible is at least as tall as the
5851 ;; default font, that means the line is actually fully
5852 ;; readable, and something like line-spacing is hidden. So in
5853 ;; that case we accept the last line in the window as still
5854 ;; visible, and consider the margin as starting one line
5856 (if (and vpos (> vpos 0))
5858 (>= rowh (default-font-height))
5860 (setq last-line (min (- wslines scroll-margin) vpos))
5861 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5863 ;; If last line of window is fully visible, and vscrolling
5864 ;; more would make this line invisible, move forward.
5865 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5867 (<= this-height dlh))
5868 (or (null rbot) (= rbot 0)))
5870 ;; If cursor is not in the bottom scroll margin, and the
5871 ;; current line is is not too tall, move forward.
5872 ((and (or (null this-height) (<= this-height winh))
5877 ;; When already vscrolled, we vscroll some more if we can,
5878 ;; or clear vscroll and move forward at end of tall image.
5880 (when (or (and rbot (> rbot 0))
5881 (and this-height (> this-height dlh)))
5882 (set-window-vscroll nil (+ vs dlh) t)))
5883 ;; If cursor just entered the bottom scroll margin, move forward,
5884 ;; but also optionally vscroll one line so redisplay won't recenter.
5888 ;; Don't vscroll if the partially-visible line at window
5889 ;; bottom is not too tall (a.k.a. "just one more text
5890 ;; line"): in that case, we do want redisplay to behave
5891 ;; normally, i.e. recenter or whatever.
5893 ;; Note: ROWH + RBOT from the value returned by
5894 ;; pos-visible-in-window-p give the total height of the
5895 ;; partially-visible glyph row at the end of the window. As
5896 ;; we are dealing with floats, we disregard sub-pixel
5897 ;; discrepancies between that and DLH.
5898 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5899 (set-window-vscroll nil dlh t))
5900 (line-move-1 arg noerror to-end)
5902 ;; If there are lines above the last line, scroll-up one line.
5903 ((and vpos (> vpos 0))
5906 ;; Finally, start vscroll.
5908 (set-window-vscroll nil dlh t)))))))
5911 ;; This is like line-move-1 except that it also performs
5912 ;; vertical scrolling of tall images if appropriate.
5913 ;; That is not really a clean thing to do, since it mixes
5914 ;; scrolling with cursor motion. But so far we don't have
5915 ;; a cleaner solution to the problem of making C-n do something
5916 ;; useful given a tall image.
5917 (defun line-move (arg &optional noerror to-end try-vscroll)
5918 "Move forward ARG lines.
5919 If NOERROR, don't signal an error if we can't move ARG lines.
5921 TRY-VSCROLL controls whether to vscroll tall lines: if either
5922 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5925 (line-move-1 arg noerror to-end)
5926 (unless (and auto-window-vscroll try-vscroll
5927 ;; Only vscroll for single line moves
5929 ;; Under scroll-conservatively, the display engine
5930 ;; does this better.
5931 (zerop scroll-conservatively)
5932 ;; But don't vscroll in a keyboard macro.
5933 (not defining-kbd-macro)
5934 (not executing-kbd-macro)
5935 (line-move-partial arg noerror to-end))
5936 (set-window-vscroll nil 0 t)
5937 (if (and line-move-visual
5938 ;; Display-based column are incompatible with goal-column.
5940 ;; When the text in the window is scrolled to the left,
5941 ;; display-based motion doesn't make sense (because each
5942 ;; logical line occupies exactly one screen line).
5943 (not (> (window-hscroll) 0))
5944 ;; Likewise when the text _was_ scrolled to the left
5945 ;; when the current run of vertical motion commands
5947 (not (and (memq last-command
5948 `(next-line previous-line ,this-command))
5950 (numberp temporary-goal-column)
5951 (>= temporary-goal-column
5952 (- (window-width) hscroll-margin)))))
5953 (prog1 (line-move-visual arg noerror)
5954 ;; If we moved into a tall line, set vscroll to make
5955 ;; scrolling through tall images more smooth.
5956 (let ((lh (line-pixel-height))
5957 (edges (window-inside-pixel-edges))
5958 (dlh (default-line-height))
5960 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5962 (< (point) (window-start))
5967 (line-move-1 arg noerror to-end)))))
5969 ;; Display-based alternative to line-move-1.
5970 ;; Arg says how many lines to move. The value is t if we can move the
5971 ;; specified number of lines.
5972 (defun line-move-visual (arg &optional noerror)
5973 "Move ARG lines forward.
5974 If NOERROR, don't signal an error if we can't move that many lines."
5975 (let ((opoint (point))
5976 (hscroll (window-hscroll))
5978 ;; Check if the previous command was a line-motion command, or if
5979 ;; we were called from some other command.
5980 (if (and (consp temporary-goal-column)
5981 (memq last-command `(next-line previous-line ,this-command)))
5982 ;; If so, there's no need to reset `temporary-goal-column',
5983 ;; but we may need to hscroll.
5984 (if (or (/= (cdr temporary-goal-column) hscroll)
5985 (> (cdr temporary-goal-column) 0))
5986 (setq target-hscroll (cdr temporary-goal-column)))
5987 ;; Otherwise, we should reset `temporary-goal-column'.
5988 (let ((posn (posn-at-point))
5991 ;; Handle the `overflow-newline-into-fringe' case:
5992 ((eq (nth 1 posn) 'right-fringe)
5993 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
5994 ((car (posn-x-y posn))
5995 (setq x-pos (car (posn-x-y posn)))
5996 ;; In R2L lines, the X pixel coordinate is measured from the
5997 ;; left edge of the window, but columns are still counted
5998 ;; from the logical-order beginning of the line, i.e. from
5999 ;; the right edge in this case. We need to adjust for that.
6000 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6001 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6002 (setq temporary-goal-column
6003 (cons (/ (float x-pos)
6007 (set-window-hscroll (selected-window) target-hscroll))
6008 ;; vertical-motion can move more than it was asked to if it moves
6009 ;; across display strings with newlines. We don't want to ring
6010 ;; the bell and announce beginning/end of buffer in that case.
6011 (or (and (or (and (>= arg 0)
6012 (>= (vertical-motion
6013 (cons (or goal-column
6014 (if (consp temporary-goal-column)
6015 (car temporary-goal-column)
6016 temporary-goal-column))
6020 (<= (vertical-motion
6021 (cons (or goal-column
6022 (if (consp temporary-goal-column)
6023 (car temporary-goal-column)
6024 temporary-goal-column))
6029 ;; If the goal column lies on a display string,
6030 ;; `vertical-motion' advances the cursor to the end
6031 ;; of the string. For arg < 0, this can cause the
6032 ;; cursor to get stuck. (Bug#3020).
6033 (= (vertical-motion arg) arg)))
6035 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6038 ;; This is the guts of next-line and previous-line.
6039 ;; Arg says how many lines to move.
6040 ;; The value is t if we can move the specified number of lines.
6041 (defun line-move-1 (arg &optional noerror _to-end)
6042 ;; Don't run any point-motion hooks, and disregard intangibility,
6043 ;; for intermediate positions.
6044 (let ((inhibit-point-motion-hooks t)
6047 (if (consp temporary-goal-column)
6048 (setq temporary-goal-column (+ (car temporary-goal-column)
6049 (cdr temporary-goal-column))))
6052 (if (not (memq last-command '(next-line previous-line)))
6053 (setq temporary-goal-column
6054 (if (and track-eol (eolp)
6055 ;; Don't count beg of empty line as end of line
6056 ;; unless we just did explicit end-of-line.
6057 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6058 most-positive-fixnum
6061 (if (not (or (integerp selective-display)
6062 line-move-ignore-invisible))
6063 ;; Use just newline characters.
6064 ;; Set ARG to 0 if we move as many lines as requested.
6066 (progn (if (> arg 1) (forward-line (1- arg)))
6067 ;; This way of moving forward ARG lines
6068 ;; verifies that we have a newline after the last one.
6069 ;; It doesn't get confused by intangible text.
6071 (if (zerop (forward-line 1))
6073 (and (zerop (forward-line arg))
6077 (signal (if (< arg 0)
6078 'beginning-of-buffer
6081 ;; Move by arg lines, but ignore invisible ones.
6083 (while (and (> arg 0) (not done))
6084 ;; If the following character is currently invisible,
6085 ;; skip all characters with that same `invisible' property value.
6086 (while (and (not (eobp)) (invisible-p (point)))
6087 (goto-char (next-char-property-change (point))))
6089 ;; We don't use `end-of-line', since we want to escape
6090 ;; from field boundaries occurring exactly at point.
6091 (goto-char (constrain-to-field
6092 (let ((inhibit-field-text-motion t))
6093 (line-end-position))
6095 'inhibit-line-move-field-capture))
6096 ;; If there's no invisibility here, move over the newline.
6100 (signal 'end-of-buffer nil)
6102 ((and (> arg 1) ;; Use vertical-motion for last move
6103 (not (integerp selective-display))
6104 (not (invisible-p (point))))
6105 ;; We avoid vertical-motion when possible
6106 ;; because that has to fontify.
6108 ;; Otherwise move a more sophisticated way.
6109 ((zerop (vertical-motion 1))
6111 (signal 'end-of-buffer nil)
6114 (setq arg (1- arg))))
6115 ;; The logic of this is the same as the loop above,
6116 ;; it just goes in the other direction.
6117 (while (and (< arg 0) (not done))
6118 ;; For completely consistency with the forward-motion
6119 ;; case, we should call beginning-of-line here.
6120 ;; However, if point is inside a field and on a
6121 ;; continued line, the call to (vertical-motion -1)
6122 ;; below won't move us back far enough; then we return
6123 ;; to the same column in line-move-finish, and point
6124 ;; gets stuck -- cyd
6129 (signal 'beginning-of-buffer nil)
6131 ((and (< arg -1) ;; Use vertical-motion for last move
6132 (not (integerp selective-display))
6133 (not (invisible-p (1- (point)))))
6135 ((zerop (vertical-motion -1))
6137 (signal 'beginning-of-buffer nil)
6141 (while (and ;; Don't move over previous invis lines
6142 ;; if our target is the middle of this line.
6143 (or (zerop (or goal-column temporary-goal-column))
6145 (not (bobp)) (invisible-p (1- (point))))
6146 (goto-char (previous-char-property-change (point))))))))
6147 ;; This is the value the function returns.
6151 ;; If we did not move down as far as desired, at least go
6152 ;; to end of line. Be sure to call point-entered and
6153 ;; point-left-hooks.
6154 (let* ((npoint (prog1 (line-end-position)
6155 (goto-char opoint)))
6156 (inhibit-point-motion-hooks nil))
6157 (goto-char npoint)))
6159 ;; If we did not move up as far as desired,
6160 ;; at least go to beginning of line.
6161 (let* ((npoint (prog1 (line-beginning-position)
6162 (goto-char opoint)))
6163 (inhibit-point-motion-hooks nil))
6164 (goto-char npoint)))
6166 (line-move-finish (or goal-column temporary-goal-column)
6167 opoint (> orig-arg 0)))))))
6169 (defun line-move-finish (column opoint forward)
6172 ;; Set REPEAT to t to repeat the whole thing.
6177 (line-beg (line-beginning-position))
6179 ;; Compute the end of the line
6180 ;; ignoring effectively invisible newlines.
6182 ;; Like end-of-line but ignores fields.
6183 (skip-chars-forward "^\n")
6184 (while (and (not (eobp)) (invisible-p (point)))
6185 (goto-char (next-char-property-change (point)))
6186 (skip-chars-forward "^\n"))
6189 ;; Move to the desired column.
6190 (line-move-to-column (truncate column))
6192 ;; Corner case: suppose we start out in a field boundary in
6193 ;; the middle of a continued line. When we get to
6194 ;; line-move-finish, point is at the start of a new *screen*
6195 ;; line but the same text line; then line-move-to-column would
6196 ;; move us backwards. Test using C-n with point on the "x" in
6197 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6204 ;; Process intangibility within a line.
6205 ;; With inhibit-point-motion-hooks bound to nil, a call to
6206 ;; goto-char moves point past intangible text.
6208 ;; However, inhibit-point-motion-hooks controls both the
6209 ;; intangibility and the point-entered/point-left hooks. The
6210 ;; following hack avoids calling the point-* hooks
6211 ;; unnecessarily. Note that we move *forward* past intangible
6212 ;; text when the initial and final points are the same.
6214 (let ((inhibit-point-motion-hooks nil))
6217 ;; If intangibility moves us to a different (later) place
6218 ;; in the same line, use that as the destination.
6219 (if (<= (point) line-end)
6221 ;; If that position is "too late",
6222 ;; try the previous allowable position.
6226 ;; If going forward, don't accept the previous
6227 ;; allowable position if it is before the target line.
6228 (< line-beg (point))
6229 ;; If going backward, don't accept the previous
6230 ;; allowable position if it is still after the target line.
6231 (<= (point) line-end))
6233 ;; As a last resort, use the end of the line.
6234 (setq new line-end))))
6236 ;; Now move to the updated destination, processing fields
6237 ;; as well as intangibility.
6239 (let ((inhibit-point-motion-hooks nil))
6241 ;; Ignore field boundaries if the initial and final
6242 ;; positions have the same `field' property, even if the
6243 ;; fields are non-contiguous. This seems to be "nicer"
6244 ;; behavior in many situations.
6245 (if (eq (get-char-property new 'field)
6246 (get-char-property opoint 'field))
6248 (constrain-to-field new opoint t t
6249 'inhibit-line-move-field-capture))))
6251 ;; If all this moved us to a different line,
6252 ;; retry everything within that new line.
6253 (when (or (< (point) line-beg) (> (point) line-end))
6254 ;; Repeat the intangibility and field processing.
6255 (setq repeat t))))))
6257 (defun line-move-to-column (col)
6258 "Try to find column COL, considering invisibility.
6259 This function works only in certain cases,
6260 because what we really need is for `move-to-column'
6261 and `current-column' to be able to ignore invisible text."
6264 (move-to-column col))
6266 (when (and line-move-ignore-invisible
6267 (not (bolp)) (invisible-p (1- (point))))
6268 (let ((normal-location (point))
6269 (normal-column (current-column)))
6270 ;; If the following character is currently invisible,
6271 ;; skip all characters with that same `invisible' property value.
6272 (while (and (not (eobp))
6273 (invisible-p (point)))
6274 (goto-char (next-char-property-change (point))))
6275 ;; Have we advanced to a larger column position?
6276 (if (> (current-column) normal-column)
6277 ;; We have made some progress towards the desired column.
6278 ;; See if we can make any further progress.
6279 (line-move-to-column (+ (current-column) (- col normal-column)))
6280 ;; Otherwise, go to the place we originally found
6281 ;; and move back over invisible text.
6282 ;; that will get us to the same place on the screen
6283 ;; but with a more reasonable buffer position.
6284 (goto-char normal-location)
6286 ;; We want the real line beginning, so it's consistent
6287 ;; with bolp below, otherwise we might infloop.
6288 (let ((inhibit-field-text-motion t))
6289 (line-beginning-position))))
6290 (while (and (not (bolp)) (invisible-p (1- (point))))
6291 (goto-char (previous-char-property-change (point) line-beg))))))))
6293 (defun move-end-of-line (arg)
6294 "Move point to end of current line as displayed.
6295 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6296 If point reaches the beginning or end of buffer, it stops there.
6298 To ignore the effects of the `intangible' text or overlay
6299 property, bind `inhibit-point-motion-hooks' to t.
6300 If there is an image in the current line, this function
6301 disregards newlines that are part of the text on which the image
6304 (or arg (setq arg 1))
6309 (let ((goal-column 0)
6310 (line-move-visual nil))
6311 (and (line-move arg t)
6312 ;; With bidi reordering, we may not be at bol,
6313 ;; so make sure we are.
6314 (skip-chars-backward "^\n")
6317 (while (and (not (bobp)) (invisible-p (1- (point))))
6318 (goto-char (previous-single-char-property-change
6319 (point) 'invisible)))
6323 (if (and (> (point) newpos)
6324 (eq (preceding-char) ?\n))
6326 (if (and (> (point) newpos) (not (eobp))
6327 (not (eq (following-char) ?\n)))
6328 ;; If we skipped something intangible and now we're not
6329 ;; really at eol, keep going.
6333 (defun move-beginning-of-line (arg)
6334 "Move point to beginning of current line as displayed.
6335 \(If there's an image in the line, this disregards newlines
6336 which are part of the text that the image rests on.)
6338 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6339 If point reaches the beginning or end of buffer, it stops there.
6340 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6342 (or arg (setq arg 1))
6344 (let ((orig (point))
6345 first-vis first-vis-field-value)
6347 ;; Move by lines, if ARG is not 1 (the default).
6349 (let ((line-move-visual nil))
6350 (line-move (1- arg) t)))
6352 ;; Move to beginning-of-line, ignoring fields and invisible text.
6353 (skip-chars-backward "^\n")
6354 (while (and (not (bobp)) (invisible-p (1- (point))))
6355 (goto-char (previous-char-property-change (point)))
6356 (skip-chars-backward "^\n"))
6358 ;; Now find first visible char in the line.
6359 (while (and (< (point) orig) (invisible-p (point)))
6360 (goto-char (next-char-property-change (point) orig)))
6361 (setq first-vis (point))
6363 ;; See if fields would stop us from reaching FIRST-VIS.
6364 (setq first-vis-field-value
6365 (constrain-to-field first-vis orig (/= arg 1) t nil))
6367 (goto-char (if (/= first-vis-field-value first-vis)
6368 ;; If yes, obey them.
6369 first-vis-field-value
6370 ;; Otherwise, move to START with attention to fields.
6371 ;; (It is possible that fields never matter in this case.)
6372 (constrain-to-field (point) orig
6373 (/= arg 1) t nil)))))
6376 ;; Many people have said they rarely use this feature, and often type
6377 ;; it by accident. Maybe it shouldn't even be on a key.
6378 (put 'set-goal-column 'disabled t)
6380 (defun set-goal-column (arg)
6381 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6382 Those commands will move to this position in the line moved to
6383 rather than trying to keep the same horizontal position.
6384 With a non-nil argument ARG, clears out the goal column
6385 so that \\[next-line] and \\[previous-line] resume vertical motion.
6386 The goal column is stored in the variable `goal-column'."
6390 (setq goal-column nil)
6391 (message "No goal column"))
6392 (setq goal-column (current-column))
6393 ;; The older method below can be erroneous if `set-goal-column' is bound
6394 ;; to a sequence containing %
6395 ;;(message (substitute-command-keys
6396 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6400 (format "Goal column %d " goal-column)
6401 (substitute-command-keys
6402 "(use \\[set-goal-column] with an arg to unset it)")))
6407 ;;; Editing based on visual lines, as opposed to logical lines.
6409 (defun end-of-visual-line (&optional n)
6410 "Move point to end of current visual line.
6411 With argument N not nil or 1, move forward N - 1 visual lines first.
6412 If point reaches the beginning or end of buffer, it stops there.
6413 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6417 (let ((line-move-visual t))
6418 (line-move (1- n) t)))
6419 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6420 ;; constrain to field boundaries, so we don't either.
6421 (vertical-motion (cons (window-width) 0)))
6423 (defun beginning-of-visual-line (&optional n)
6424 "Move point to beginning of current visual line.
6425 With argument N not nil or 1, move forward N - 1 visual lines first.
6426 If point reaches the beginning or end of buffer, it stops there.
6427 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6430 (let ((opoint (point)))
6432 (let ((line-move-visual t))
6433 (line-move (1- n) t)))
6435 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6436 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6438 (defun kill-visual-line (&optional arg)
6439 "Kill the rest of the visual line.
6440 With prefix argument ARG, kill that many visual lines from point.
6441 If ARG is negative, kill visual lines backward.
6442 If ARG is zero, kill the text before point on the current visual
6445 If you want to append the killed line to the last killed text,
6446 use \\[append-next-kill] before \\[kill-line].
6448 If the buffer is read-only, Emacs will beep and refrain from deleting
6449 the line, but put the line in the kill ring anyway. This means that
6450 you can use this command to copy text from a read-only buffer.
6451 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6454 ;; Like in `kill-line', it's better to move point to the other end
6455 ;; of the kill before killing.
6456 (let ((opoint (point))
6457 (kill-whole-line (and kill-whole-line (bolp))))
6459 (vertical-motion (prefix-numeric-value arg))
6460 (end-of-visual-line 1)
6461 (if (= (point) opoint)
6463 ;; Skip any trailing whitespace at the end of the visual line.
6464 ;; We used to do this only if `show-trailing-whitespace' is
6465 ;; nil, but that's wrong; the correct thing would be to check
6466 ;; whether the trailing whitespace is highlighted. But, it's
6467 ;; OK to just do this unconditionally.
6468 (skip-chars-forward " \t")))
6469 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6473 (defun next-logical-line (&optional arg try-vscroll)
6474 "Move cursor vertically down ARG lines.
6475 This is identical to `next-line', except that it always moves
6476 by logical lines instead of visual lines, ignoring the value of
6477 the variable `line-move-visual'."
6478 (interactive "^p\np")
6479 (let ((line-move-visual nil))
6481 (next-line arg try-vscroll))))
6483 (defun previous-logical-line (&optional arg try-vscroll)
6484 "Move cursor vertically up ARG lines.
6485 This is identical to `previous-line', except that it always moves
6486 by logical lines instead of visual lines, ignoring the value of
6487 the variable `line-move-visual'."
6488 (interactive "^p\np")
6489 (let ((line-move-visual nil))
6491 (previous-line arg try-vscroll))))
6493 (defgroup visual-line nil
6494 "Editing based on visual lines."
6498 (defvar visual-line-mode-map
6499 (let ((map (make-sparse-keymap)))
6500 (define-key map [remap kill-line] 'kill-visual-line)
6501 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6502 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6503 ;; These keybindings interfere with xterm function keys. Are
6504 ;; there any other suitable bindings?
6505 ;; (define-key map "\M-[" 'previous-logical-line)
6506 ;; (define-key map "\M-]" 'next-logical-line)
6509 (defcustom visual-line-fringe-indicators '(nil nil)
6510 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6511 The value should be a list of the form (LEFT RIGHT), where LEFT
6512 and RIGHT are symbols representing the bitmaps to display, to
6513 indicate wrapped lines, in the left and right fringes respectively.
6514 See also `fringe-indicator-alist'.
6515 The default is not to display fringe indicators for wrapped lines.
6516 This variable does not affect fringe indicators displayed for
6518 :type '(list (choice (const :tag "Hide left indicator" nil)
6519 (const :tag "Left curly arrow" left-curly-arrow)
6520 (symbol :tag "Other bitmap"))
6521 (choice (const :tag "Hide right indicator" nil)
6522 (const :tag "Right curly arrow" right-curly-arrow)
6523 (symbol :tag "Other bitmap")))
6524 :set (lambda (symbol value)
6525 (dolist (buf (buffer-list))
6526 (with-current-buffer buf
6527 (when (and (boundp 'visual-line-mode)
6528 (symbol-value 'visual-line-mode))
6529 (setq fringe-indicator-alist
6530 (cons (cons 'continuation value)
6533 (copy-tree fringe-indicator-alist)))))))
6534 (set-default symbol value)))
6536 (defvar visual-line--saved-state nil)
6538 (define-minor-mode visual-line-mode
6539 "Toggle visual line based editing (Visual Line mode).
6540 With a prefix argument ARG, enable Visual Line mode if ARG is
6541 positive, and disable it otherwise. If called from Lisp, enable
6542 the mode if ARG is omitted or nil.
6544 When Visual Line mode is enabled, `word-wrap' is turned on in
6545 this buffer, and simple editing commands are redefined to act on
6546 visual lines, not logical lines. See Info node `Visual Line
6548 :keymap visual-line-mode-map
6551 (if visual-line-mode
6553 (set (make-local-variable 'visual-line--saved-state) nil)
6554 ;; Save the local values of some variables, to be restored if
6555 ;; visual-line-mode is turned off.
6556 (dolist (var '(line-move-visual truncate-lines
6557 truncate-partial-width-windows
6558 word-wrap fringe-indicator-alist))
6559 (if (local-variable-p var)
6560 (push (cons var (symbol-value var))
6561 visual-line--saved-state)))
6562 (set (make-local-variable 'line-move-visual) t)
6563 (set (make-local-variable 'truncate-partial-width-windows) nil)
6564 (setq truncate-lines nil
6566 fringe-indicator-alist
6567 (cons (cons 'continuation visual-line-fringe-indicators)
6568 fringe-indicator-alist)))
6569 (kill-local-variable 'line-move-visual)
6570 (kill-local-variable 'word-wrap)
6571 (kill-local-variable 'truncate-lines)
6572 (kill-local-variable 'truncate-partial-width-windows)
6573 (kill-local-variable 'fringe-indicator-alist)
6574 (dolist (saved visual-line--saved-state)
6575 (set (make-local-variable (car saved)) (cdr saved)))
6576 (kill-local-variable 'visual-line--saved-state)))
6578 (defun turn-on-visual-line-mode ()
6579 (visual-line-mode 1))
6581 (define-globalized-minor-mode global-visual-line-mode
6582 visual-line-mode turn-on-visual-line-mode)
6585 (defun transpose-chars (arg)
6586 "Interchange characters around point, moving forward one character.
6587 With prefix arg ARG, effect is to take character before point
6588 and drag it forward past ARG other characters (backward if ARG negative).
6589 If no argument and at end of line, the previous two chars are exchanged."
6591 (when (and (null arg) (eolp) (not (bobp))
6592 (not (get-text-property (1- (point)) 'read-only)))
6594 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6596 (defun transpose-words (arg)
6597 "Interchange words around point, leaving point at end of them.
6598 With prefix arg ARG, effect is to take word before or around point
6599 and drag it forward past ARG other words (backward if ARG negative).
6600 If ARG is zero, the words around or after point and around or after mark
6602 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6604 (transpose-subr 'forward-word arg))
6606 (defun transpose-sexps (arg)
6607 "Like \\[transpose-words] but applies to sexps.
6608 Does not work on a sexp that point is in the middle of
6609 if it is a list or string."
6613 ;; Here we should try to simulate the behavior of
6614 ;; (cons (progn (forward-sexp x) (point))
6615 ;; (progn (forward-sexp (- x)) (point)))
6616 ;; Except that we don't want to rely on the second forward-sexp
6617 ;; putting us back to where we want to be, since forward-sexp-function
6618 ;; might do funny things like infix-precedence.
6620 (looking-at "\\sw\\|\\s_")
6622 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6623 ;; Jumping over a symbol. We might be inside it, mind you.
6624 (progn (funcall (if (> arg 0)
6625 'skip-syntax-backward 'skip-syntax-forward)
6627 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6628 ;; Otherwise, we're between sexps. Take a step back before jumping
6629 ;; to make sure we'll obey the same precedence no matter which direction
6631 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6632 (cons (save-excursion (forward-sexp arg) (point))
6633 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6634 (not (zerop (funcall (if (> arg 0)
6635 'skip-syntax-forward
6636 'skip-syntax-backward)
6641 (defun transpose-lines (arg)
6642 "Exchange current line and previous line, leaving point after both.
6643 With argument ARG, takes previous line and moves it past ARG lines.
6644 With argument 0, interchanges line point is in with line mark is in."
6646 (transpose-subr (function
6650 ;; Move forward over ARG lines,
6651 ;; but create newlines if necessary.
6652 (setq arg (forward-line arg))
6653 (if (/= (preceding-char) ?\n)
6654 (setq arg (1+ arg)))
6657 (forward-line arg))))
6660 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6661 ;; which seems inconsistent with the ARG /= 0 case.
6662 ;; FIXME document SPECIAL.
6663 (defun transpose-subr (mover arg &optional special)
6664 "Subroutine to do the work of transposing objects.
6665 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6666 moves forward by units of the given object (e.g. forward-sentence,
6667 forward-paragraph). If ARG is zero, exchanges the current object
6668 with the one containing mark. If ARG is an integer, moves the
6669 current object past ARG following (if ARG is positive) or
6670 preceding (if ARG is negative) objects, leaving point after the
6672 (let ((aux (if special mover
6674 (cons (progn (funcall mover x) (point))
6675 (progn (funcall mover (- x)) (point))))))
6680 (setq pos1 (funcall aux 1))
6681 (goto-char (or (mark) (error "No mark set in this buffer")))
6682 (setq pos2 (funcall aux 1))
6683 (transpose-subr-1 pos1 pos2))
6684 (exchange-point-and-mark))
6686 (setq pos1 (funcall aux -1))
6687 (setq pos2 (funcall aux arg))
6688 (transpose-subr-1 pos1 pos2)
6689 (goto-char (car pos2)))
6691 (setq pos1 (funcall aux -1))
6692 (goto-char (car pos1))
6693 (setq pos2 (funcall aux arg))
6694 (transpose-subr-1 pos1 pos2)
6695 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6697 (defun transpose-subr-1 (pos1 pos2)
6698 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6699 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6700 (when (> (car pos1) (car pos2))
6702 (setq pos1 pos2 pos2 swap)))
6703 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6704 (atomic-change-group
6705 ;; This sequence of insertions attempts to preserve marker
6706 ;; positions at the start and end of the transposed objects.
6707 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6708 (len1 (- (cdr pos1) (car pos1)))
6709 (len2 (length word))
6710 (boundary (make-marker)))
6711 (set-marker boundary (car pos2))
6712 (goto-char (cdr pos1))
6713 (insert-before-markers word)
6714 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6715 (goto-char boundary)
6717 (goto-char (+ boundary len1))
6718 (delete-region (point) (+ (point) len2))
6719 (set-marker boundary nil))))
6721 (defun backward-word (&optional arg)
6722 "Move backward until encountering the beginning of a word.
6723 With argument ARG, do this that many times.
6724 If ARG is omitted or nil, move point backward one word."
6726 (forward-word (- (or arg 1))))
6728 (defun mark-word (&optional arg allow-extend)
6729 "Set mark ARG words away from point.
6730 The place mark goes is the same place \\[forward-word] would
6731 move to with the same argument.
6732 Interactively, if this command is repeated
6733 or (in Transient Mark mode) if the mark is active,
6734 it marks the next ARG words after the ones already marked."
6735 (interactive "P\np")
6736 (cond ((and allow-extend
6737 (or (and (eq last-command this-command) (mark t))
6739 (setq arg (if arg (prefix-numeric-value arg)
6740 (if (< (mark) (point)) -1 1)))
6749 (forward-word (prefix-numeric-value arg))
6753 (defun kill-word (arg)
6754 "Kill characters forward until encountering the end of a word.
6755 With argument ARG, do this that many times."
6757 (kill-region (point) (progn (forward-word arg) (point))))
6759 (defun backward-kill-word (arg)
6760 "Kill characters backward until encountering the beginning of a word.
6761 With argument ARG, do this that many times."
6763 (kill-word (- arg)))
6765 (defun current-word (&optional strict really-word)
6766 "Return the symbol or word that point is on (or a nearby one) as a string.
6767 The return value includes no text properties.
6768 If optional arg STRICT is non-nil, return nil unless point is within
6769 or adjacent to a symbol or word. In all cases the value can be nil
6770 if there is no word nearby.
6771 The function, belying its name, normally finds a symbol.
6772 If optional arg REALLY-WORD is non-nil, it finds just a word."
6774 (let* ((oldpoint (point)) (start (point)) (end (point))
6775 (syntaxes (if really-word "w" "w_"))
6776 (not-syntaxes (concat "^" syntaxes)))
6777 (skip-syntax-backward syntaxes) (setq start (point))
6778 (goto-char oldpoint)
6779 (skip-syntax-forward syntaxes) (setq end (point))
6780 (when (and (eq start oldpoint) (eq end oldpoint)
6781 ;; Point is neither within nor adjacent to a word.
6783 ;; Look for preceding word in same line.
6784 (skip-syntax-backward not-syntaxes (line-beginning-position))
6786 ;; No preceding word in same line.
6787 ;; Look for following word in same line.
6789 (skip-syntax-forward not-syntaxes (line-end-position))
6790 (setq start (point))
6791 (skip-syntax-forward syntaxes)
6794 (skip-syntax-backward syntaxes)
6795 (setq start (point))))
6796 ;; If we found something nonempty, return it as a string.
6797 (unless (= start end)
6798 (buffer-substring-no-properties start end)))))
6800 (defcustom fill-prefix nil
6801 "String for filling to insert at front of new line, or nil for none."
6802 :type '(choice (const :tag "None" nil)
6805 (make-variable-buffer-local 'fill-prefix)
6806 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6808 (defcustom auto-fill-inhibit-regexp nil
6809 "Regexp to match lines which should not be auto-filled."
6810 :type '(choice (const :tag "None" nil)
6814 (defun do-auto-fill ()
6815 "The default value for `normal-auto-fill-function'.
6816 This is the default auto-fill function, some major modes use a different one.
6817 Returns t if it really did any work."
6818 (let (fc justify give-up
6819 (fill-prefix fill-prefix))
6820 (if (or (not (setq justify (current-justification)))
6821 (null (setq fc (current-fill-column)))
6822 (and (eq justify 'left)
6823 (<= (current-column) fc))
6824 (and auto-fill-inhibit-regexp
6825 (save-excursion (beginning-of-line)
6826 (looking-at auto-fill-inhibit-regexp))))
6827 nil ;; Auto-filling not required
6828 (if (memq justify '(full center right))
6829 (save-excursion (unjustify-current-line)))
6831 ;; Choose a fill-prefix automatically.
6832 (when (and adaptive-fill-mode
6833 (or (null fill-prefix) (string= fill-prefix "")))
6835 (fill-context-prefix
6836 (save-excursion (fill-forward-paragraph -1) (point))
6837 (save-excursion (fill-forward-paragraph 1) (point)))))
6838 (and prefix (not (equal prefix ""))
6839 ;; Use auto-indentation rather than a guessed empty prefix.
6840 (not (and fill-indent-according-to-mode
6841 (string-match "\\`[ \t]*\\'" prefix)))
6842 (setq fill-prefix prefix))))
6844 (while (and (not give-up) (> (current-column) fc))
6845 ;; Determine where to split the line.
6850 (setq after-prefix (point))
6852 (looking-at (regexp-quote fill-prefix))
6853 (setq after-prefix (match-end 0)))
6854 (move-to-column (1+ fc))
6855 (fill-move-to-break-point after-prefix)
6858 ;; See whether the place we found is any good.
6860 (goto-char fill-point)
6862 ;; There is no use breaking at end of line.
6863 (save-excursion (skip-chars-forward " ") (eolp))
6864 ;; It is futile to split at the end of the prefix
6865 ;; since we would just insert the prefix again.
6866 (and after-prefix (<= (point) after-prefix))
6867 ;; Don't split right after a comment starter
6868 ;; since we would just make another comment starter.
6869 (and comment-start-skip
6870 (let ((limit (point)))
6872 (and (re-search-forward comment-start-skip
6874 (eq (point) limit))))))
6875 ;; No good place to break => stop trying.
6877 ;; Ok, we have a useful place to break the line. Do it.
6878 (let ((prev-column (current-column)))
6879 ;; If point is at the fill-point, do not `save-excursion'.
6880 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6881 ;; point will end up before it rather than after it.
6883 (skip-chars-backward " \t")
6884 (= (point) fill-point))
6885 (default-indent-new-line t)
6887 (goto-char fill-point)
6888 (default-indent-new-line t)))
6889 ;; Now do justification, if required
6890 (if (not (eq justify 'left))
6893 (justify-current-line justify nil t)))
6894 ;; If making the new line didn't reduce the hpos of
6895 ;; the end of the line, then give up now;
6896 ;; trying again will not help.
6897 (if (>= (current-column) prev-column)
6898 (setq give-up t))))))
6899 ;; Justify last line.
6900 (justify-current-line justify t t)
6903 (defvar comment-line-break-function 'comment-indent-new-line
6904 "Mode-specific function which line breaks and continues a comment.
6905 This function is called during auto-filling when a comment syntax
6907 The function should take a single optional argument, which is a flag
6908 indicating whether it should use soft newlines.")
6910 (defun default-indent-new-line (&optional soft)
6911 "Break line at point and indent.
6912 If a comment syntax is defined, call `comment-indent-new-line'.
6914 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6915 unless optional argument SOFT is non-nil."
6918 (funcall comment-line-break-function soft)
6919 ;; Insert the newline before removing empty space so that markers
6920 ;; get preserved better.
6921 (if soft (insert-and-inherit ?\n) (newline 1))
6922 (save-excursion (forward-char -1) (delete-horizontal-space))
6923 (delete-horizontal-space)
6925 (if (and fill-prefix (not adaptive-fill-mode))
6926 ;; Blindly trust a non-adaptive fill-prefix.
6928 (indent-to-left-margin)
6929 (insert-before-markers-and-inherit fill-prefix))
6932 ;; If there's an adaptive prefix, use it unless we're inside
6933 ;; a comment and the prefix is not a comment starter.
6935 (indent-to-left-margin)
6936 (insert-and-inherit fill-prefix))
6937 ;; If we're not inside a comment, just try to indent.
6938 (t (indent-according-to-mode))))))
6940 (defvar normal-auto-fill-function 'do-auto-fill
6941 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6942 Some major modes set this.")
6944 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6945 ;; `functions' and `hooks' are usually unsafe to set, but setting
6946 ;; auto-fill-function to nil in a file-local setting is safe and
6947 ;; can be useful to prevent auto-filling.
6948 (put 'auto-fill-function 'safe-local-variable 'null)
6950 (define-minor-mode auto-fill-mode
6951 "Toggle automatic line breaking (Auto Fill mode).
6952 With a prefix argument ARG, enable Auto Fill mode if ARG is
6953 positive, and disable it otherwise. If called from Lisp, enable
6954 the mode if ARG is omitted or nil.
6956 When Auto Fill mode is enabled, inserting a space at a column
6957 beyond `current-fill-column' automatically breaks the line at a
6960 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6963 The value of `normal-auto-fill-function' specifies the function to use
6964 for `auto-fill-function' when turning Auto Fill mode on."
6965 :variable (auto-fill-function
6966 . (lambda (v) (setq auto-fill-function
6967 (if v normal-auto-fill-function)))))
6969 ;; This holds a document string used to document auto-fill-mode.
6970 (defun auto-fill-function ()
6971 "Automatically break line at a previous space, in insertion of text."
6974 (defun turn-on-auto-fill ()
6975 "Unconditionally turn on Auto Fill mode."
6978 (defun turn-off-auto-fill ()
6979 "Unconditionally turn off Auto Fill mode."
6980 (auto-fill-mode -1))
6982 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
6984 (defun set-fill-column (arg)
6985 "Set `fill-column' to specified argument.
6986 Use \\[universal-argument] followed by a number to specify a column.
6987 Just \\[universal-argument] as argument means to use the current column."
6989 (list (or current-prefix-arg
6990 ;; We used to use current-column silently, but C-x f is too easily
6991 ;; typed as a typo for C-x C-f, so we turned it into an error and
6992 ;; now an interactive prompt.
6993 (read-number "Set fill-column to: " (current-column)))))
6995 (setq arg (current-column)))
6996 (if (not (integerp arg))
6997 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6998 (error "set-fill-column requires an explicit argument")
6999 (message "Fill column set to %d (was %d)" arg fill-column)
7000 (setq fill-column arg)))
7002 (defun set-selective-display (arg)
7003 "Set `selective-display' to ARG; clear it if no arg.
7004 When the value of `selective-display' is a number > 0,
7005 lines whose indentation is >= that value are not displayed.
7006 The variable `selective-display' has a separate value for each buffer."
7008 (if (eq selective-display t)
7009 (error "selective-display already in use for marked lines"))
7012 (narrow-to-region (point-min) (point))
7013 (goto-char (window-start))
7014 (vertical-motion (window-height)))))
7015 (setq selective-display
7016 (and arg (prefix-numeric-value arg)))
7017 (recenter current-vpos))
7018 (set-window-start (selected-window) (window-start))
7019 (princ "selective-display set to " t)
7020 (prin1 selective-display t)
7023 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7025 (defun toggle-truncate-lines (&optional arg)
7026 "Toggle truncating of long lines for the current buffer.
7027 When truncating is off, long lines are folded.
7028 With prefix argument ARG, truncate long lines if ARG is positive,
7029 otherwise fold them. Note that in side-by-side windows, this
7030 command has no effect if `truncate-partial-width-windows' is
7033 (setq truncate-lines
7035 (not truncate-lines)
7036 (> (prefix-numeric-value arg) 0)))
7037 (force-mode-line-update)
7038 (unless truncate-lines
7039 (let ((buffer (current-buffer)))
7040 (walk-windows (lambda (window)
7041 (if (eq buffer (window-buffer window))
7042 (set-window-hscroll window 0)))
7044 (message "Truncate long lines %s"
7045 (if truncate-lines "enabled" "disabled")))
7047 (defun toggle-word-wrap (&optional arg)
7048 "Toggle whether to use word-wrapping for continuation lines.
7049 With prefix argument ARG, wrap continuation lines at word boundaries
7050 if ARG is positive, otherwise wrap them at the right screen edge.
7051 This command toggles the value of `word-wrap'. It has no effect
7052 if long lines are truncated."
7057 (> (prefix-numeric-value arg) 0)))
7058 (force-mode-line-update)
7059 (message "Word wrapping %s"
7060 (if word-wrap "enabled" "disabled")))
7062 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7063 "The string displayed in the mode line when in overwrite mode.")
7064 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7065 "The string displayed in the mode line when in binary overwrite mode.")
7067 (define-minor-mode overwrite-mode
7068 "Toggle Overwrite mode.
7069 With a prefix argument ARG, enable Overwrite mode if ARG is
7070 positive, and disable it otherwise. If called from Lisp, enable
7071 the mode if ARG is omitted or nil.
7073 When Overwrite mode is enabled, printing characters typed in
7074 replace existing text on a one-for-one basis, rather than pushing
7075 it to the right. At the end of a line, such characters extend
7076 the line. Before a tab, such characters insert until the tab is
7077 filled in. \\[quoted-insert] still inserts characters in
7078 overwrite mode; this is supposed to make it easier to insert
7079 characters when necessary."
7080 :variable (overwrite-mode
7081 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7083 (define-minor-mode binary-overwrite-mode
7084 "Toggle Binary Overwrite mode.
7085 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7086 is positive, and disable it otherwise. If called from Lisp,
7087 enable the mode if ARG is omitted or nil.
7089 When Binary Overwrite mode is enabled, printing characters typed
7090 in replace existing text. Newlines are not treated specially, so
7091 typing at the end of a line joins the line to the next, with the
7092 typed character between them. Typing before a tab character
7093 simply replaces the tab with the character typed.
7094 \\[quoted-insert] replaces the text at the cursor, just as
7095 ordinary typing characters do.
7097 Note that Binary Overwrite mode is not its own minor mode; it is
7098 a specialization of overwrite mode, entered by setting the
7099 `overwrite-mode' variable to `overwrite-mode-binary'."
7100 :variable (overwrite-mode
7101 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7103 (define-minor-mode line-number-mode
7104 "Toggle line number display in the mode line (Line Number mode).
7105 With a prefix argument ARG, enable Line Number mode if ARG is
7106 positive, and disable it otherwise. If called from Lisp, enable
7107 the mode if ARG is omitted or nil.
7109 Line numbers do not appear for very large buffers and buffers
7110 with very long lines; see variables `line-number-display-limit'
7111 and `line-number-display-limit-width'."
7112 :init-value t :global t :group 'mode-line)
7114 (define-minor-mode column-number-mode
7115 "Toggle column number display in the mode line (Column Number mode).
7116 With a prefix argument ARG, enable Column Number mode if ARG is
7117 positive, and disable it otherwise.
7119 If called from Lisp, enable the mode if ARG is omitted or nil."
7120 :global t :group 'mode-line)
7122 (define-minor-mode size-indication-mode
7123 "Toggle buffer size display in the mode line (Size Indication mode).
7124 With a prefix argument ARG, enable Size Indication mode if ARG is
7125 positive, and disable it otherwise.
7127 If called from Lisp, enable the mode if ARG is omitted or nil."
7128 :global t :group 'mode-line)
7130 (define-minor-mode auto-save-mode
7131 "Toggle auto-saving in the current buffer (Auto Save mode).
7132 With a prefix argument ARG, enable Auto Save mode if ARG is
7133 positive, and disable it otherwise.
7135 If called from Lisp, enable the mode if ARG is omitted or nil."
7136 :variable ((and buffer-auto-save-file-name
7137 ;; If auto-save is off because buffer has shrunk,
7138 ;; then toggling should turn it on.
7139 (>= buffer-saved-size 0))
7141 (setq buffer-auto-save-file-name
7144 ((and buffer-file-name auto-save-visited-file-name
7145 (not buffer-read-only))
7147 (t (make-auto-save-file-name))))))
7148 ;; If -1 was stored here, to temporarily turn off saving,
7150 (and (< buffer-saved-size 0)
7151 (setq buffer-saved-size 0)))
7153 (defgroup paren-blinking nil
7154 "Blinking matching of parens and expressions."
7155 :prefix "blink-matching-"
7156 :group 'paren-matching)
7158 (defcustom blink-matching-paren t
7159 "Non-nil means show matching open-paren when close-paren is inserted.
7160 If t, highlight the paren. If `jump', briefly move cursor to its
7161 position. If `jump-offscreen', move cursor there even if the
7162 position is off screen. With any other non-nil value, the
7163 off-screen position of the opening paren will be shown in the
7166 (const :tag "Disable" nil)
7167 (const :tag "Highlight" t)
7168 (const :tag "Move cursor" jump)
7169 (const :tag "Move cursor, even if off screen" jump-offscreen))
7170 :group 'paren-blinking)
7172 (defcustom blink-matching-paren-on-screen t
7173 "Non-nil means show matching open-paren when it is on screen.
7174 If nil, don't show it (but the open-paren can still be shown
7175 in the echo area when it is off screen).
7177 This variable has no effect if `blink-matching-paren' is nil.
7178 \(In that case, the open-paren is never shown.)
7179 It is also ignored if `show-paren-mode' is enabled."
7181 :group 'paren-blinking)
7183 (defcustom blink-matching-paren-distance (* 100 1024)
7184 "If non-nil, maximum distance to search backwards for matching open-paren.
7185 If nil, search stops at the beginning of the accessible portion of the buffer."
7186 :version "23.2" ; 25->100k
7187 :type '(choice (const nil) integer)
7188 :group 'paren-blinking)
7190 (defcustom blink-matching-delay 1
7191 "Time in seconds to delay after showing a matching paren."
7193 :group 'paren-blinking)
7195 (defcustom blink-matching-paren-dont-ignore-comments nil
7196 "If nil, `blink-matching-paren' ignores comments.
7197 More precisely, when looking for the matching parenthesis,
7198 it skips the contents of comments that end before point."
7200 :group 'paren-blinking)
7202 (defun blink-matching-check-mismatch (start end)
7203 "Return whether or not START...END are matching parens.
7204 END is the current point and START is the blink position.
7205 START might be nil if no matching starter was found.
7206 Returns non-nil if we find there is a mismatch."
7207 (let* ((end-syntax (syntax-after (1- end)))
7208 (matching-paren (and (consp end-syntax)
7209 (eq (syntax-class end-syntax) 5)
7211 ;; For self-matched chars like " and $, we can't know when they're
7212 ;; mismatched or unmatched, so we can only do it for parens.
7213 (when matching-paren
7216 (eq (char-after start) matching-paren)
7217 ;; The cdr might hold a new paren-class info rather than
7218 ;; a matching-char info, in which case the two CDRs
7220 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7222 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7223 "Function to check parentheses mismatches.
7224 The function takes two arguments (START and END) where START is the
7225 position just before the opening token and END is the position right after.
7226 START can be nil, if it was not found.
7227 The function should return non-nil if the two tokens do not match.")
7229 (defvar blink-matching--overlay
7230 (let ((ol (make-overlay (point) (point) nil t)))
7231 (overlay-put ol 'face 'show-paren-match)
7234 "Overlay used to highlight the matching paren.")
7236 (defun blink-matching-open ()
7237 "Momentarily highlight the beginning of the sexp before point."
7239 (when (and (not (bobp))
7240 blink-matching-paren)
7241 (let* ((oldpos (point))
7242 (message-log-max nil) ; Don't log messages about paren matching.
7246 (if blink-matching-paren-distance
7248 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7249 (- (point) blink-matching-paren-distance))
7251 (let ((parse-sexp-ignore-comments
7252 (and parse-sexp-ignore-comments
7253 (not blink-matching-paren-dont-ignore-comments))))
7256 (syntax-propertize (point))
7258 ;; backward-sexp skips backward over prefix chars,
7259 ;; so move back to the matching paren.
7260 (while (and (< (point) (1- oldpos))
7261 (let ((code (syntax-after (point))))
7262 (or (eq (syntax-class code) 6)
7263 (eq (logand 1048576 (car code))
7268 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7273 (minibuffer-message "Mismatched parentheses")
7274 (message "Mismatched parentheses"))
7276 (minibuffer-message "No matching parenthesis found")
7277 (message "No matching parenthesis found"))))
7278 ((not blinkpos) nil)
7280 (eq blink-matching-paren 'jump-offscreen)
7281 (pos-visible-in-window-p blinkpos))
7282 ;; Matching open within window, temporarily move to or highlight
7283 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7285 (and blink-matching-paren-on-screen
7286 (not show-paren-mode)
7287 (if (memq blink-matching-paren '(jump jump-offscreen))
7289 (goto-char blinkpos)
7290 (sit-for blink-matching-delay))
7293 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7295 (sit-for blink-matching-delay))
7296 (delete-overlay blink-matching--overlay)))))
7298 (let ((open-paren-line-string
7300 (goto-char blinkpos)
7301 ;; Show what precedes the open in its line, if anything.
7303 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7304 (buffer-substring (line-beginning-position)
7306 ;; Show what follows the open in its line, if anything.
7309 (skip-chars-forward " \t")
7311 (buffer-substring blinkpos
7312 (line-end-position)))
7313 ;; Otherwise show the previous nonblank line,
7315 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7317 (buffer-substring (progn
7318 (skip-chars-backward "\n \t")
7319 (line-beginning-position))
7320 (progn (end-of-line)
7321 (skip-chars-backward " \t")
7323 ;; Replace the newline and other whitespace with `...'.
7325 (buffer-substring blinkpos (1+ blinkpos))))
7326 ;; There is nothing to show except the char itself.
7327 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7330 (substring-no-properties open-paren-line-string))))))))
7332 (defvar blink-paren-function 'blink-matching-open
7333 "Function called, if non-nil, whenever a close parenthesis is inserted.
7334 More precisely, a char with closeparen syntax is self-inserted.")
7336 (defun blink-paren-post-self-insert-function ()
7337 (when (and (eq (char-before) last-command-event) ; Sanity check.
7338 (memq (char-syntax last-command-event) '(?\) ?\$))
7339 blink-paren-function
7340 (not executing-kbd-macro)
7341 (not noninteractive)
7342 ;; Verify an even number of quoting characters precede the close.
7343 ;; FIXME: Also check if this parenthesis closes a comment as
7344 ;; can happen in Pascal and SML.
7345 (= 1 (logand 1 (- (point)
7348 (skip-syntax-backward "/\\")
7350 (funcall blink-paren-function)))
7352 (put 'blink-paren-post-self-insert-function 'priority 100)
7354 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7355 ;; Most likely, this hook is nil, so this arg doesn't matter,
7356 ;; but I use it as a reminder that this function usually
7357 ;; likes to be run after others since it does
7358 ;; `sit-for'. That's also the reason it get a `priority' prop
7362 ;; This executes C-g typed while Emacs is waiting for a command.
7363 ;; Quitting out of a program does not go through here;
7364 ;; that happens in the QUIT macro at the C code level.
7365 (defun keyboard-quit ()
7366 "Signal a `quit' condition.
7367 During execution of Lisp code, this character causes a quit directly.
7368 At top-level, as an editor command, this simply beeps."
7370 ;; Avoid adding the region to the window selection.
7371 (setq saved-region-selection nil)
7372 (let (select-active-regions)
7374 (if (fboundp 'kmacro-keyboard-quit)
7375 (kmacro-keyboard-quit))
7376 (when completion-in-region-mode
7377 (completion-in-region-mode -1))
7378 ;; Force the next redisplay cycle to remove the "Def" indicator from
7379 ;; all the mode lines.
7380 (if defining-kbd-macro
7381 (force-mode-line-update t))
7382 (setq defining-kbd-macro nil)
7383 (let ((debug-on-quit nil))
7384 (signal 'quit nil)))
7386 (defvar buffer-quit-function nil
7387 "Function to call to \"quit\" the current buffer, or nil if none.
7388 \\[keyboard-escape-quit] calls this function when its more local actions
7389 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7391 (defun keyboard-escape-quit ()
7392 "Exit the current \"mode\" (in a generalized sense of the word).
7393 This command can exit an interactive command such as `query-replace',
7394 can clear out a prefix argument or a region,
7395 can get out of the minibuffer or other recursive edit,
7396 cancel the use of the current buffer (for special-purpose buffers),
7397 or go back to just one window (by deleting all but the selected window)."
7399 (cond ((eq last-command 'mode-exited) nil)
7402 ((> (minibuffer-depth) 0)
7403 (abort-recursive-edit))
7406 ((> (recursion-depth) 0)
7407 (exit-recursive-edit))
7408 (buffer-quit-function
7409 (funcall buffer-quit-function))
7410 ((not (one-window-p t))
7411 (delete-other-windows))
7412 ((string-match "^ \\*" (buffer-name (current-buffer)))
7415 (defun play-sound-file (file &optional volume device)
7416 "Play sound stored in FILE.
7417 VOLUME and DEVICE correspond to the keywords of the sound
7418 specification for `play-sound'."
7419 (interactive "fPlay sound file: ")
7420 (let ((sound (list :file file)))
7422 (plist-put sound :volume volume))
7424 (plist-put sound :device device))
7426 (play-sound sound)))
7429 (defcustom read-mail-command 'rmail
7430 "Your preference for a mail reading package.
7431 This is used by some keybindings which support reading mail.
7432 See also `mail-user-agent' concerning sending mail."
7433 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7434 (function-item :tag "Gnus" :format "%t\n" gnus)
7435 (function-item :tag "Emacs interface to MH"
7436 :format "%t\n" mh-rmail)
7437 (function :tag "Other"))
7441 (defcustom mail-user-agent 'message-user-agent
7442 "Your preference for a mail composition package.
7443 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7444 outgoing email message. This variable lets you specify which
7445 mail-sending package you prefer.
7447 Valid values include:
7449 `message-user-agent' -- use the Message package.
7450 See Info node `(message)'.
7451 `sendmail-user-agent' -- use the Mail package.
7452 See Info node `(emacs)Sending Mail'.
7453 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7454 See Info node `(mh-e)'.
7455 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7456 paraphernalia if Gnus is running, particularly
7457 the Gcc: header for archiving.
7459 Additional valid symbols may be available; check with the author of
7460 your package for details. The function should return non-nil if it
7463 See also `read-mail-command' concerning reading mail."
7464 :type '(radio (function-item :tag "Message package"
7467 (function-item :tag "Mail package"
7469 sendmail-user-agent)
7470 (function-item :tag "Emacs interface to MH"
7473 (function-item :tag "Message with full Gnus features"
7476 (function :tag "Other"))
7477 :version "23.2" ; sendmail->message
7480 (defcustom compose-mail-user-agent-warnings t
7481 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7482 If the value of `mail-user-agent' is the default, and the user
7483 appears to have customizations applying to the old default,
7484 `compose-mail' issues a warning."
7489 (defun rfc822-goto-eoh ()
7490 "If the buffer starts with a mail header, move point to the header's end.
7491 Otherwise, moves to `point-min'.
7492 The end of the header is the start of the next line, if there is one,
7493 else the end of the last line. This function obeys RFC822."
7494 (goto-char (point-min))
7495 (when (re-search-forward
7496 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7497 (goto-char (match-beginning 0))))
7499 ;; Used by Rmail (e.g., rmail-forward).
7500 (defvar mail-encode-mml nil
7501 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7502 the outgoing message before sending it.")
7504 (defun compose-mail (&optional to subject other-headers continue
7505 switch-function yank-action send-actions
7507 "Start composing a mail message to send.
7508 This uses the user's chosen mail composition package
7509 as selected with the variable `mail-user-agent'.
7510 The optional arguments TO and SUBJECT specify recipients
7511 and the initial Subject field, respectively.
7513 OTHER-HEADERS is an alist specifying additional
7514 header fields. Elements look like (HEADER . VALUE) where both
7515 HEADER and VALUE are strings.
7517 CONTINUE, if non-nil, says to continue editing a message already
7518 being composed. Interactively, CONTINUE is the prefix argument.
7520 SWITCH-FUNCTION, if non-nil, is a function to use to
7521 switch to and display the buffer used for mail composition.
7523 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7524 to insert the raw text of the message being replied to.
7525 It has the form (FUNCTION . ARGS). The user agent will apply
7526 FUNCTION to ARGS, to insert the raw text of the original message.
7527 \(The user agent will also run `mail-citation-hook', *after* the
7528 original text has been inserted in this way.)
7530 SEND-ACTIONS is a list of actions to call when the message is sent.
7531 Each action has the form (FUNCTION . ARGS).
7533 RETURN-ACTION, if non-nil, is an action for returning to the
7534 caller. It has the form (FUNCTION . ARGS). The function is
7535 called after the mail has been sent or put aside, and the mail
7538 (list nil nil nil current-prefix-arg))
7540 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7541 ;; from sendmail-user-agent to message-user-agent. Some users may
7542 ;; encounter incompatibilities. This hack tries to detect problems
7543 ;; and warn about them.
7544 (and compose-mail-user-agent-warnings
7545 (eq mail-user-agent 'message-user-agent)
7547 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7548 mail-yank-hooks mail-archive-file-name
7549 mail-default-reply-to mail-mailing-lists
7553 (push var warn-vars)))
7555 (display-warning 'mail
7557 The default mail mode is now Message mode.
7558 You have the following Mail mode variable%s customized:
7559 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7560 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7561 (if (> (length warn-vars) 1) "s" "")
7562 (mapconcat 'symbol-name
7565 (let ((function (get mail-user-agent 'composefunc)))
7566 (funcall function to subject other-headers continue switch-function
7567 yank-action send-actions return-action)))
7569 (defun compose-mail-other-window (&optional to subject other-headers continue
7570 yank-action send-actions
7572 "Like \\[compose-mail], but edit the outgoing message in another window."
7573 (interactive (list nil nil nil current-prefix-arg))
7574 (compose-mail to subject other-headers continue
7575 'switch-to-buffer-other-window yank-action send-actions
7578 (defun compose-mail-other-frame (&optional to subject other-headers continue
7579 yank-action send-actions
7581 "Like \\[compose-mail], but edit the outgoing message in another frame."
7582 (interactive (list nil nil nil current-prefix-arg))
7583 (compose-mail to subject other-headers continue
7584 'switch-to-buffer-other-frame yank-action send-actions
7588 (defvar set-variable-value-history nil
7589 "History of values entered with `set-variable'.
7591 Maximum length of the history list is determined by the value
7592 of `history-length', which see.")
7594 (defun set-variable (variable value &optional make-local)
7595 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7596 VARIABLE should be a user option variable name, a Lisp variable
7597 meant to be customized by users. You should enter VALUE in Lisp syntax,
7598 so if you want VALUE to be a string, you must surround it with doublequotes.
7599 VALUE is used literally, not evaluated.
7601 If VARIABLE has a `variable-interactive' property, that is used as if
7602 it were the arg to `interactive' (which see) to interactively read VALUE.
7604 If VARIABLE has been defined with `defcustom', then the type information
7605 in the definition is used to check that VALUE is valid.
7607 Note that this function is at heart equivalent to the basic `set' function.
7608 For a variable defined with `defcustom', it does not pay attention to
7609 any :set property that the variable might have (if you want that, use
7610 \\[customize-set-variable] instead).
7612 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7614 (let* ((default-var (variable-at-point))
7615 (var (if (custom-variable-p default-var)
7616 (read-variable (format "Set variable (default %s): " default-var)
7618 (read-variable "Set variable: ")))
7619 (minibuffer-help-form '(describe-variable var))
7620 (prop (get var 'variable-interactive))
7621 (obsolete (car (get var 'byte-obsolete-variable)))
7622 (prompt (format "Set %s %s to value: " var
7623 (cond ((local-variable-p var)
7625 ((or current-prefix-arg
7626 (local-variable-if-set-p var))
7631 (message (concat "`%S' is obsolete; "
7632 (if (symbolp obsolete) "use `%S' instead" "%s"))
7636 ;; Use VAR's `variable-interactive' property
7637 ;; as an interactive spec for prompting.
7638 (call-interactively `(lambda (arg)
7641 (read-from-minibuffer prompt nil
7642 read-expression-map t
7643 'set-variable-value-history
7644 (format "%S" (symbol-value var)))))))
7645 (list var val current-prefix-arg)))
7647 (and (custom-variable-p variable)
7648 (not (get variable 'custom-type))
7649 (custom-load-symbol variable))
7650 (let ((type (get variable 'custom-type)))
7652 ;; Match with custom type.
7654 (setq type (widget-convert type))
7655 (unless (widget-apply type :match value)
7656 (user-error "Value `%S' does not match type %S of %S"
7657 value (car type) variable))))
7660 (make-local-variable variable))
7662 (set variable value)
7664 ;; Force a thorough redisplay for the case that the variable
7665 ;; has an effect on the display, like `tab-width' has.
7666 (force-mode-line-update))
7668 ;; Define the major mode for lists of completions.
7670 (defvar completion-list-mode-map
7671 (let ((map (make-sparse-keymap)))
7672 (define-key map [mouse-2] 'choose-completion)
7673 (define-key map [follow-link] 'mouse-face)
7674 (define-key map [down-mouse-2] nil)
7675 (define-key map "\C-m" 'choose-completion)
7676 (define-key map "\e\e\e" 'delete-completion-window)
7677 (define-key map [left] 'previous-completion)
7678 (define-key map [right] 'next-completion)
7679 (define-key map [?\t] 'next-completion)
7680 (define-key map [backtab] 'previous-completion)
7681 (define-key map "q" 'quit-window)
7682 (define-key map "z" 'kill-this-buffer)
7684 "Local map for completion list buffers.")
7686 ;; Completion mode is suitable only for specially formatted data.
7687 (put 'completion-list-mode 'mode-class 'special)
7689 (defvar completion-reference-buffer nil
7690 "Record the buffer that was current when the completion list was requested.
7691 This is a local variable in the completion list buffer.
7692 Initial value is nil to avoid some compiler warnings.")
7694 (defvar completion-no-auto-exit nil
7695 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7696 This also applies to other functions such as `choose-completion'.")
7698 (defvar completion-base-position nil
7699 "Position of the base of the text corresponding to the shown completions.
7700 This variable is used in the *Completions* buffers.
7701 Its value is a list of the form (START END) where START is the place
7702 where the completion should be inserted and END (if non-nil) is the end
7703 of the text to replace. If END is nil, point is used instead.")
7705 (defvar completion-list-insert-choice-function #'completion--replace
7706 "Function to use to insert the text chosen in *Completions*.
7707 Called with three arguments (BEG END TEXT), it should replace the text
7708 between BEG and END with TEXT. Expected to be set buffer-locally
7709 in the *Completions* buffer.")
7711 (defvar completion-base-size nil
7712 "Number of chars before point not involved in completion.
7713 This is a local variable in the completion list buffer.
7714 It refers to the chars in the minibuffer if completing in the
7715 minibuffer, or in `completion-reference-buffer' otherwise.
7716 Only characters in the field at point are included.
7718 If nil, Emacs determines which part of the tail end of the
7719 buffer's text is involved in completion by comparing the text
7721 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7723 (defun delete-completion-window ()
7724 "Delete the completion list window.
7725 Go to the window from which completion was requested."
7727 (let ((buf completion-reference-buffer))
7728 (if (one-window-p t)
7729 (if (window-dedicated-p) (delete-frame))
7730 (delete-window (selected-window))
7731 (if (get-buffer-window buf)
7732 (select-window (get-buffer-window buf))))))
7734 (defun previous-completion (n)
7735 "Move to the previous item in the completion list."
7737 (next-completion (- n)))
7739 (defun next-completion (n)
7740 "Move to the next item in the completion list.
7741 With prefix argument N, move N items (negative N means move backward)."
7743 (let ((beg (point-min)) (end (point-max)))
7744 (while (and (> n 0) (not (eobp)))
7745 ;; If in a completion, move to the end of it.
7746 (when (get-text-property (point) 'mouse-face)
7747 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7748 ;; Move to start of next one.
7749 (unless (get-text-property (point) 'mouse-face)
7750 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7752 (while (and (< n 0) (not (bobp)))
7753 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7754 ;; If in a completion, move to the start of it.
7755 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7756 (goto-char (previous-single-property-change
7757 (point) 'mouse-face nil beg)))
7758 ;; Move to end of the previous completion.
7759 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7760 (goto-char (previous-single-property-change
7761 (point) 'mouse-face nil beg)))
7762 ;; Move to the start of that one.
7763 (goto-char (previous-single-property-change
7764 (point) 'mouse-face nil beg))
7767 (defun choose-completion (&optional event)
7768 "Choose the completion at point.
7769 If EVENT, use EVENT's position to determine the starting position."
7770 (interactive (list last-nonmenu-event))
7771 ;; In case this is run via the mouse, give temporary modes such as
7772 ;; isearch a chance to turn off.
7773 (run-hooks 'mouse-leave-buffer-hook)
7774 (with-current-buffer (window-buffer (posn-window (event-start event)))
7775 (let ((buffer completion-reference-buffer)
7776 (base-size completion-base-size)
7777 (base-position completion-base-position)
7778 (insert-function completion-list-insert-choice-function)
7781 (goto-char (posn-point (event-start event)))
7784 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7785 (setq end (point) beg (1+ (point))))
7787 (get-text-property (1- (point)) 'mouse-face))
7788 (setq end (1- (point)) beg (point)))
7789 (t (error "No completion here")))
7790 (setq beg (previous-single-property-change beg 'mouse-face))
7791 (setq end (or (next-single-property-change end 'mouse-face)
7793 (buffer-substring-no-properties beg end)))))
7795 (unless (buffer-live-p buffer)
7796 (error "Destination buffer is dead"))
7797 (quit-window nil (posn-window (event-start event)))
7799 (with-current-buffer buffer
7800 (choose-completion-string
7804 ;; Someone's using old completion code that doesn't know
7805 ;; about base-position yet.
7806 (list (+ base-size (field-beginning))))
7807 ;; If all else fails, just guess.
7808 (list (choose-completion-guess-base-position choice)))
7809 insert-function)))))
7811 ;; Delete the longest partial match for STRING
7812 ;; that can be found before POINT.
7813 (defun choose-completion-guess-base-position (string)
7815 (let ((opoint (point))
7817 ;; Try moving back by the length of the string.
7818 (goto-char (max (- (point) (length string))
7819 (minibuffer-prompt-end)))
7820 ;; See how far back we were actually able to move. That is the
7821 ;; upper bound on how much we can match and delete.
7822 (setq len (- opoint (point)))
7823 (if completion-ignore-case
7824 (setq string (downcase string)))
7825 (while (and (> len 0)
7826 (let ((tail (buffer-substring (point) opoint)))
7827 (if completion-ignore-case
7828 (setq tail (downcase tail)))
7829 (not (string= tail (substring string 0 len)))))
7834 (defun choose-completion-delete-max-match (string)
7835 (declare (obsolete choose-completion-guess-base-position "23.2"))
7836 (delete-region (choose-completion-guess-base-position string) (point)))
7838 (defvar choose-completion-string-functions nil
7839 "Functions that may override the normal insertion of a completion choice.
7840 These functions are called in order with three arguments:
7841 CHOICE - the string to insert in the buffer,
7842 BUFFER - the buffer in which the choice should be inserted,
7843 BASE-POSITION - where to insert the completion.
7845 If a function in the list returns non-nil, that function is supposed
7846 to have inserted the CHOICE in the BUFFER, and possibly exited
7847 the minibuffer; no further functions will be called.
7849 If all functions in the list return nil, that means to use
7850 the default method of inserting the completion in BUFFER.")
7852 (defun choose-completion-string (choice &optional
7853 buffer base-position insert-function)
7854 "Switch to BUFFER and insert the completion choice CHOICE.
7855 BASE-POSITION says where to insert the completion.
7856 INSERT-FUNCTION says how to insert the completion and falls
7857 back on `completion-list-insert-choice-function' when nil."
7859 ;; If BUFFER is the minibuffer, exit the minibuffer
7860 ;; unless it is reading a file name and CHOICE is a directory,
7861 ;; or completion-no-auto-exit is non-nil.
7863 ;; Some older code may call us passing `base-size' instead of
7864 ;; `base-position'. It's difficult to make any use of `base-size',
7865 ;; so we just ignore it.
7866 (unless (consp base-position)
7867 (message "Obsolete `base-size' passed to choose-completion-string")
7868 (setq base-position nil))
7870 (let* ((buffer (or buffer completion-reference-buffer))
7871 (mini-p (minibufferp buffer)))
7872 ;; If BUFFER is a minibuffer, barf unless it's the currently
7873 ;; active minibuffer.
7875 (not (and (active-minibuffer-window)
7877 (window-buffer (active-minibuffer-window))))))
7878 (error "Minibuffer is not active for completion")
7879 ;; Set buffer so buffer-local choose-completion-string-functions works.
7881 (unless (run-hook-with-args-until-success
7882 'choose-completion-string-functions
7883 ;; The fourth arg used to be `mini-p' but was useless
7884 ;; (since minibufferp can be used on the `buffer' arg)
7885 ;; and indeed unused. The last used to be `base-size', so we
7886 ;; keep it to try and avoid breaking old code.
7887 choice buffer base-position nil)
7888 ;; This remove-text-properties should be unnecessary since `choice'
7889 ;; comes from buffer-substring-no-properties.
7890 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7891 ;; Insert the completion into the buffer where it was requested.
7892 (funcall (or insert-function completion-list-insert-choice-function)
7893 (or (car base-position) (point))
7894 (or (cadr base-position) (point))
7896 ;; Update point in the window that BUFFER is showing in.
7897 (let ((window (get-buffer-window buffer t)))
7898 (set-window-point window (point)))
7899 ;; If completing for the minibuffer, exit it with this choice.
7900 (and (not completion-no-auto-exit)
7901 (minibufferp buffer)
7902 minibuffer-completion-table
7903 ;; If this is reading a file name, and the file name chosen
7904 ;; is a directory, don't exit the minibuffer.
7905 (let* ((result (buffer-substring (field-beginning) (point)))
7907 (completion-boundaries result minibuffer-completion-table
7908 minibuffer-completion-predicate
7910 (if (eq (car bounds) (length result))
7911 ;; The completion chosen leads to a new set of completions
7912 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7913 (let ((mini (active-minibuffer-window)))
7914 (select-window mini)
7915 (when minibuffer-auto-raise
7916 (raise-frame (window-frame mini))))
7917 (exit-minibuffer))))))))
7919 (define-derived-mode completion-list-mode nil "Completion List"
7920 "Major mode for buffers showing lists of possible completions.
7921 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7922 to select the completion near point.
7923 Or click to select one with the mouse.
7925 \\{completion-list-mode-map}"
7926 (set (make-local-variable 'completion-base-size) nil))
7928 (defun completion-list-mode-finish ()
7929 "Finish setup of the completions buffer.
7930 Called from `temp-buffer-show-hook'."
7931 (when (eq major-mode 'completion-list-mode)
7932 (setq buffer-read-only t)))
7934 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7937 ;; Variables and faces used in `completion-setup-function'.
7939 (defcustom completion-show-help t
7940 "Non-nil means show help message in *Completions* buffer."
7945 ;; This function goes in completion-setup-hook, so that it is called
7946 ;; after the text of the completion list buffer is written.
7947 (defun completion-setup-function ()
7948 (let* ((mainbuf (current-buffer))
7950 ;; FIXME: This is a bad hack. We try to set the default-directory
7951 ;; in the *Completions* buffer so that the relative file names
7952 ;; displayed there can be treated as valid file names, independently
7953 ;; from the completion context. But this suffers from many problems:
7954 ;; - It's not clear when the completions are file names. With some
7955 ;; completion tables (e.g. bzr revision specs), the listed
7956 ;; completions can mix file names and other things.
7957 ;; - It doesn't pay attention to possible quoting.
7958 ;; - With fancy completion styles, the code below will not always
7959 ;; find the right base directory.
7960 (if minibuffer-completing-file-name
7961 (file-name-as-directory
7963 (buffer-substring (minibuffer-prompt-end)
7964 (- (point) (or completion-base-size 0))))))))
7965 (with-current-buffer standard-output
7966 (let ((base-size completion-base-size) ;Read before killing localvars.
7967 (base-position completion-base-position)
7968 (insert-fun completion-list-insert-choice-function))
7969 (completion-list-mode)
7970 (set (make-local-variable 'completion-base-size) base-size)
7971 (set (make-local-variable 'completion-base-position) base-position)
7972 (set (make-local-variable 'completion-list-insert-choice-function)
7974 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7975 (if base-dir (setq default-directory base-dir))
7976 ;; Maybe insert help string.
7977 (when completion-show-help
7978 (goto-char (point-min))
7979 (if (display-mouse-p)
7980 (insert "Click on a completion to select it.\n"))
7981 (insert (substitute-command-keys
7982 "In this buffer, type \\[choose-completion] to \
7983 select the completion near point.\n\n"))))))
7985 (add-hook 'completion-setup-hook 'completion-setup-function)
7987 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7988 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7990 (defun switch-to-completions ()
7991 "Select the completion list window."
7993 (let ((window (or (get-buffer-window "*Completions*" 0)
7994 ;; Make sure we have a completions window.
7995 (progn (minibuffer-completion-help)
7996 (get-buffer-window "*Completions*" 0)))))
7998 (select-window window)
7999 ;; In the new buffer, go to the first completion.
8000 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8002 (next-completion 1)))))
8004 ;;; Support keyboard commands to turn on various modifiers.
8006 ;; These functions -- which are not commands -- each add one modifier
8007 ;; to the following event.
8009 (defun event-apply-alt-modifier (_ignore-prompt)
8010 "\\<function-key-map>Add the Alt modifier to the following event.
8011 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8012 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8013 (defun event-apply-super-modifier (_ignore-prompt)
8014 "\\<function-key-map>Add the Super modifier to the following event.
8015 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8016 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8017 (defun event-apply-hyper-modifier (_ignore-prompt)
8018 "\\<function-key-map>Add the Hyper modifier to the following event.
8019 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8020 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8021 (defun event-apply-shift-modifier (_ignore-prompt)
8022 "\\<function-key-map>Add the Shift modifier to the following event.
8023 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8024 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8025 (defun event-apply-control-modifier (_ignore-prompt)
8026 "\\<function-key-map>Add the Ctrl modifier to the following event.
8027 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8028 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8029 (defun event-apply-meta-modifier (_ignore-prompt)
8030 "\\<function-key-map>Add the Meta modifier to the following event.
8031 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8032 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8034 (defun event-apply-modifier (event symbol lshiftby prefix)
8035 "Apply a modifier flag to event EVENT.
8036 SYMBOL is the name of this modifier, as a symbol.
8037 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8038 PREFIX is the string that represents this modifier in an event type symbol."
8040 (cond ((eq symbol 'control)
8041 (if (and (<= (downcase event) ?z)
8042 (>= (downcase event) ?a))
8043 (- (downcase event) ?a -1)
8044 (if (and (<= (downcase event) ?Z)
8045 (>= (downcase event) ?A))
8046 (- (downcase event) ?A -1)
8047 (logior (lsh 1 lshiftby) event))))
8049 (if (and (<= (downcase event) ?z)
8050 (>= (downcase event) ?a))
8052 (logior (lsh 1 lshiftby) event)))
8054 (logior (lsh 1 lshiftby) event)))
8055 (if (memq symbol (event-modifiers event))
8057 (let ((event-type (if (symbolp event) event (car event))))
8058 (setq event-type (intern (concat prefix (symbol-name event-type))))
8061 (cons event-type (cdr event)))))))
8063 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8064 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8065 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8066 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8067 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8068 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8070 ;;;; Keypad support.
8072 ;; Make the keypad keys act like ordinary typing keys. If people add
8073 ;; bindings for the function key symbols, then those bindings will
8074 ;; override these, so this shouldn't interfere with any existing
8077 ;; Also tell read-char how to handle these keys.
8079 (lambda (keypad-normal)
8080 (let ((keypad (nth 0 keypad-normal))
8081 (normal (nth 1 keypad-normal)))
8082 (put keypad 'ascii-character normal)
8083 (define-key function-key-map (vector keypad) (vector normal))))
8084 ;; See also kp-keys bound in bindings.el.
8090 ;; Do the same for various keys that are represented as symbols under
8091 ;; GUIs but naturally correspond to characters.
8102 ;;;; forking a twin copy of a buffer.
8105 (defvar clone-buffer-hook nil
8106 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8108 (defvar clone-indirect-buffer-hook nil
8109 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8111 (defun clone-process (process &optional newname)
8112 "Create a twin copy of PROCESS.
8113 If NEWNAME is nil, it defaults to PROCESS' name;
8114 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8115 If PROCESS is associated with a buffer, the new process will be associated
8116 with the current buffer instead.
8117 Returns nil if PROCESS has already terminated."
8118 (setq newname (or newname (process-name process)))
8119 (if (string-match "<[0-9]+>\\'" newname)
8120 (setq newname (substring newname 0 (match-beginning 0))))
8121 (when (memq (process-status process) '(run stop open))
8122 (let* ((process-connection-type (process-tty-name process))
8124 (if (memq (process-status process) '(open))
8125 (let ((args (process-contact process t)))
8126 (setq args (plist-put args :name newname))
8127 (setq args (plist-put args :buffer
8128 (if (process-buffer process)
8130 (apply 'make-network-process args))
8131 (apply 'start-process newname
8132 (if (process-buffer process) (current-buffer))
8133 (process-command process)))))
8134 (set-process-query-on-exit-flag
8135 new-process (process-query-on-exit-flag process))
8136 (set-process-inherit-coding-system-flag
8137 new-process (process-inherit-coding-system-flag process))
8138 (set-process-filter new-process (process-filter process))
8139 (set-process-sentinel new-process (process-sentinel process))
8140 (set-process-plist new-process (copy-sequence (process-plist process)))
8143 ;; things to maybe add (currently partly covered by `funcall mode'):
8146 (defun clone-buffer (&optional newname display-flag)
8147 "Create and return a twin copy of the current buffer.
8148 Unlike an indirect buffer, the new buffer can be edited
8149 independently of the old one (if it is not read-only).
8150 NEWNAME is the name of the new buffer. It may be modified by
8151 adding or incrementing <N> at the end as necessary to create a
8152 unique buffer name. If nil, it defaults to the name of the
8153 current buffer, with the proper suffix. If DISPLAY-FLAG is
8154 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8155 clone a file-visiting buffer, or a buffer whose major mode symbol
8156 has a non-nil `no-clone' property, results in an error.
8158 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8159 current buffer with appropriate suffix. However, if a prefix
8160 argument is given, then the command prompts for NEWNAME in the
8163 This runs the normal hook `clone-buffer-hook' in the new buffer
8164 after it has been set up properly in other respects."
8167 (if buffer-file-name
8168 (error "Cannot clone a file-visiting buffer"))
8169 (if (get major-mode 'no-clone)
8170 (error "Cannot clone a buffer in %s mode" mode-name))
8171 (list (if current-prefix-arg
8172 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8174 (if buffer-file-name
8175 (error "Cannot clone a file-visiting buffer"))
8176 (if (get major-mode 'no-clone)
8177 (error "Cannot clone a buffer in %s mode" mode-name))
8178 (setq newname (or newname (buffer-name)))
8179 (if (string-match "<[0-9]+>\\'" newname)
8180 (setq newname (substring newname 0 (match-beginning 0))))
8181 (let ((buf (current-buffer))
8185 (mk (if mark-active (mark t)))
8186 (modified (buffer-modified-p))
8188 (lvars (buffer-local-variables))
8189 (process (get-buffer-process (current-buffer)))
8190 (new (generate-new-buffer (or newname (buffer-name)))))
8193 (with-current-buffer new
8194 (insert-buffer-substring buf)))
8195 (with-current-buffer new
8196 (narrow-to-region ptmin ptmax)
8198 (if mk (set-mark mk))
8199 (set-buffer-modified-p modified)
8201 ;; Clone the old buffer's process, if any.
8202 (when process (clone-process process))
8204 ;; Now set up the major mode.
8207 ;; Set up other local variables.
8209 (condition-case () ;in case var is read-only
8212 (set (make-local-variable (car v)) (cdr v)))
8216 ;; Run any hooks (typically set up by the major mode
8217 ;; for cloning to work properly).
8218 (run-hooks 'clone-buffer-hook))
8220 ;; Presumably the current buffer is shown in the selected frame, so
8221 ;; we want to display the clone elsewhere.
8222 (let ((same-window-regexps nil)
8223 (same-window-buffer-names))
8224 (pop-to-buffer new)))
8228 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8229 "Create an indirect buffer that is a twin copy of the current buffer.
8231 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8232 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8233 or if not called with a prefix arg, NEWNAME defaults to the current
8234 buffer's name. The name is modified by adding a `<N>' suffix to it
8235 or by incrementing the N in an existing suffix. Trying to clone a
8236 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8237 property results in an error.
8239 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8240 This is always done when called interactively.
8242 Optional third arg NORECORD non-nil means do not put this buffer at the
8243 front of the list of recently selected ones.
8245 Returns the newly created indirect buffer."
8248 (if (get major-mode 'no-clone-indirect)
8249 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8250 (list (if current-prefix-arg
8251 (read-buffer "Name of indirect buffer: " (current-buffer)))
8253 (if (get major-mode 'no-clone-indirect)
8254 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8255 (setq newname (or newname (buffer-name)))
8256 (if (string-match "<[0-9]+>\\'" newname)
8257 (setq newname (substring newname 0 (match-beginning 0))))
8258 (let* ((name (generate-new-buffer-name newname))
8259 (buffer (make-indirect-buffer (current-buffer) name t)))
8260 (with-current-buffer buffer
8261 (run-hooks 'clone-indirect-buffer-hook))
8263 (pop-to-buffer buffer norecord))
8267 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8268 "Like `clone-indirect-buffer' but display in another window."
8271 (if (get major-mode 'no-clone-indirect)
8272 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8273 (list (if current-prefix-arg
8274 (read-buffer "Name of indirect buffer: " (current-buffer)))
8276 (let ((pop-up-windows t))
8277 (clone-indirect-buffer newname display-flag norecord)))
8280 ;;; Handling of Backspace and Delete keys.
8282 (defcustom normal-erase-is-backspace 'maybe
8283 "Set the default behavior of the Delete and Backspace keys.
8285 If set to t, Delete key deletes forward and Backspace key deletes
8288 If set to nil, both Delete and Backspace keys delete backward.
8290 If set to `maybe' (which is the default), Emacs automatically
8291 selects a behavior. On window systems, the behavior depends on
8292 the keyboard used. If the keyboard has both a Backspace key and
8293 a Delete key, and both are mapped to their usual meanings, the
8294 option's default value is set to t, so that Backspace can be used
8295 to delete backward, and Delete can be used to delete forward.
8297 If not running under a window system, customizing this option
8298 accomplishes a similar effect by mapping C-h, which is usually
8299 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8300 via `keyboard-translate'. The former functionality of C-h is
8301 available on the F1 key. You should probably not use this
8302 setting if you don't have both Backspace, Delete and F1 keys.
8304 Setting this variable with setq doesn't take effect. Programmatically,
8305 call `normal-erase-is-backspace-mode' (which see) instead."
8306 :type '(choice (const :tag "Off" nil)
8307 (const :tag "Maybe" maybe)
8308 (other :tag "On" t))
8309 :group 'editing-basics
8311 :set (lambda (symbol value)
8312 ;; The fboundp is because of a problem with :set when
8313 ;; dumping Emacs. It doesn't really matter.
8314 (if (fboundp 'normal-erase-is-backspace-mode)
8315 (normal-erase-is-backspace-mode (or value 0))
8316 (set-default symbol value))))
8318 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8319 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8320 (unless frame (setq frame (selected-frame)))
8321 (with-selected-frame frame
8322 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8323 (normal-erase-is-backspace-mode
8324 (if (if (eq normal-erase-is-backspace 'maybe)
8325 (and (not noninteractive)
8326 (or (memq system-type '(ms-dos windows-nt))
8327 (memq window-system '(w32 ns))
8328 (and (memq window-system '(x))
8329 (fboundp 'x-backspace-delete-keys-p)
8330 (x-backspace-delete-keys-p))
8331 ;; If the terminal Emacs is running on has erase char
8332 ;; set to ^H, use the Backspace key for deleting
8333 ;; backward, and the Delete key for deleting forward.
8334 (and (null window-system)
8335 (eq tty-erase-char ?\^H))))
8336 normal-erase-is-backspace)
8339 (define-minor-mode normal-erase-is-backspace-mode
8340 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8341 With a prefix argument ARG, enable this feature if ARG is
8342 positive, and disable it otherwise. If called from Lisp, enable
8343 the mode if ARG is omitted or nil.
8345 On window systems, when this mode is on, Delete is mapped to C-d
8346 and Backspace is mapped to DEL; when this mode is off, both
8347 Delete and Backspace are mapped to DEL. (The remapping goes via
8348 `local-function-key-map', so binding Delete or Backspace in the
8349 global or local keymap will override that.)
8351 In addition, on window systems, the bindings of C-Delete, M-Delete,
8352 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8353 the global keymap in accordance with the functionality of Delete and
8354 Backspace. For example, if Delete is remapped to C-d, which deletes
8355 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8356 to DEL, which deletes backward, C-Delete is bound to
8357 `backward-kill-word'.
8359 If not running on a window system, a similar effect is accomplished by
8360 remapping C-h (normally produced by the Backspace key) and DEL via
8361 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8362 to C-d; if it's off, the keys are not remapped.
8364 When not running on a window system, and this mode is turned on, the
8365 former functionality of C-h is available on the F1 key. You should
8366 probably not turn on this mode on a text-only terminal if you don't
8367 have both Backspace, Delete and F1 keys.
8369 See also `normal-erase-is-backspace'."
8370 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8372 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8374 (let ((enabled (eq 1 (terminal-parameter
8375 nil 'normal-erase-is-backspace))))
8377 (cond ((or (memq window-system '(x w32 ns pc))
8378 (memq system-type '(ms-dos windows-nt)))
8380 `(([M-delete] [M-backspace])
8381 ([C-M-delete] [C-M-backspace])
8382 ([?\e C-delete] [?\e C-backspace]))))
8386 (define-key local-function-key-map [delete] [deletechar])
8387 (define-key local-function-key-map [kp-delete] [deletechar])
8388 (define-key local-function-key-map [backspace] [?\C-?])
8389 (dolist (b bindings)
8390 ;; Not sure if input-decode-map is really right, but
8391 ;; keyboard-translate-table (used below) only works
8392 ;; for integer events, and key-translation-table is
8393 ;; global (like the global-map, used earlier).
8394 (define-key input-decode-map (car b) nil)
8395 (define-key input-decode-map (cadr b) nil)))
8396 (define-key local-function-key-map [delete] [?\C-?])
8397 (define-key local-function-key-map [kp-delete] [?\C-?])
8398 (define-key local-function-key-map [backspace] [?\C-?])
8399 (dolist (b bindings)
8400 (define-key input-decode-map (car b) (cadr b))
8401 (define-key input-decode-map (cadr b) (car b))))))
8405 (keyboard-translate ?\C-h ?\C-?)
8406 (keyboard-translate ?\C-? ?\C-d))
8407 (keyboard-translate ?\C-h ?\C-h)
8408 (keyboard-translate ?\C-? ?\C-?))))
8410 (if (called-interactively-p 'interactive)
8411 (message "Delete key deletes %s"
8412 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8413 "forward" "backward")))))
8415 (defvar vis-mode-saved-buffer-invisibility-spec nil
8416 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8418 (define-minor-mode read-only-mode
8419 "Change whether the current buffer is read-only.
8420 With prefix argument ARG, make the buffer read-only if ARG is
8421 positive, otherwise make it writable. If buffer is read-only
8422 and `view-read-only' is non-nil, enter view mode.
8424 Do not call this from a Lisp program unless you really intend to
8425 do the same thing as the \\[read-only-mode] command, including
8426 possibly enabling or disabling View mode. Also, note that this
8427 command works by setting the variable `buffer-read-only', which
8428 does not affect read-only regions caused by text properties. To
8429 ignore read-only status in a Lisp program (whether due to text
8430 properties or buffer state), bind `inhibit-read-only' temporarily
8431 to a non-nil value."
8432 :variable buffer-read-only
8434 ((and (not buffer-read-only) view-mode)
8435 (View-exit-and-edit)
8436 (make-local-variable 'view-read-only)
8437 (setq view-read-only t)) ; Must leave view mode.
8438 ((and buffer-read-only view-read-only
8439 ;; If view-mode is already active, `view-mode-enter' is a nop.
8441 (not (eq (get major-mode 'mode-class) 'special)))
8442 (view-mode-enter))))
8444 (define-minor-mode visible-mode
8445 "Toggle making all invisible text temporarily visible (Visible mode).
8446 With a prefix argument ARG, enable Visible mode if ARG is
8447 positive, and disable it otherwise. If called from Lisp, enable
8448 the mode if ARG is omitted or nil.
8450 This mode works by saving the value of `buffer-invisibility-spec'
8451 and setting it to nil."
8453 :group 'editing-basics
8454 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8455 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8456 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8458 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8459 buffer-invisibility-spec)
8460 (setq buffer-invisibility-spec nil)))
8462 (defvar messages-buffer-mode-map
8463 (let ((map (make-sparse-keymap)))
8464 (set-keymap-parent map special-mode-map)
8465 (define-key map "g" nil) ; nothing to revert
8468 (define-derived-mode messages-buffer-mode special-mode "Messages"
8469 "Major mode used in the \"*Messages*\" buffer.")
8471 (defun messages-buffer ()
8472 "Return the \"*Messages*\" buffer.
8473 If it does not exist, create and it switch it to `messages-buffer-mode'."
8474 (or (get-buffer "*Messages*")
8475 (with-current-buffer (get-buffer-create "*Messages*")
8476 (messages-buffer-mode)
8480 ;; Minibuffer prompt stuff.
8482 ;;(defun minibuffer-prompt-modification (start end)
8483 ;; (error "You cannot modify the prompt"))
8486 ;;(defun minibuffer-prompt-insertion (start end)
8487 ;; (let ((inhibit-modification-hooks t))
8488 ;; (delete-region start end)
8489 ;; ;; Discard undo information for the text insertion itself
8490 ;; ;; and for the text deletion.above.
8491 ;; (when (consp buffer-undo-list)
8492 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8493 ;; (message "You cannot modify the prompt")))
8496 ;;(setq minibuffer-prompt-properties
8497 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8498 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8501 ;;;; Problematic external packages.
8503 ;; rms says this should be done by specifying symbols that define
8504 ;; versions together with bad values. This is therefore not as
8505 ;; flexible as it could be. See the thread:
8506 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8507 (defconst bad-packages-alist
8508 ;; Not sure exactly which semantic versions have problems.
8509 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8510 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8511 "The version of `semantic' loaded does not work in Emacs 22.
8512 It can cause constant high CPU load.
8513 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8514 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8515 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8516 ;; provided the `CUA-mode' feature. Since this is no longer true,
8517 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8519 "CUA-mode is now part of the standard GNU Emacs distribution,
8520 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8522 You have loaded an older version of CUA-mode which does not work
8523 correctly with this version of Emacs. You should remove the old
8524 version and use the one distributed with Emacs."))
8525 "Alist of packages known to cause problems in this version of Emacs.
8526 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8527 PACKAGE is either a regular expression to match file names, or a
8528 symbol (a feature name), like for `with-eval-after-load'.
8529 SYMBOL is either the name of a string variable, or t. Upon
8530 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8531 warning using STRING as the message.")
8533 (defun bad-package-check (package)
8534 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8536 (let* ((list (assoc package bad-packages-alist))
8537 (symbol (nth 1 list)))
8541 (and (stringp (setq symbol (eval symbol)))
8542 (string-match-p (nth 2 list) symbol)))
8543 (display-warning package (nth 3 list) :warning)))
8546 (dolist (elem bad-packages-alist)
8547 (let ((pkg (car elem)))
8548 (with-eval-after-load pkg
8549 (bad-package-check pkg))))
8552 ;;; Generic dispatcher commands
8554 ;; Macro `define-alternatives' is used to create generic commands.
8555 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8556 ;; that can have different alternative implementations where choosing
8557 ;; among them is exclusively a matter of user preference.
8559 ;; (define-alternatives COMMAND) creates a new interactive command
8560 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8561 ;; Typically, the user will not need to customize this variable; packages
8562 ;; wanting to add alternative implementations should use
8564 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8566 (defmacro define-alternatives (command &rest customizations)
8567 "Define the new command `COMMAND'.
8569 The argument `COMMAND' should be a symbol.
8571 Running `M-x COMMAND RET' for the first time prompts for which
8572 alternative to use and records the selected command as a custom
8575 Running `C-u M-x COMMAND RET' prompts again for an alternative
8576 and overwrites the previous choice.
8578 The variable `COMMAND-alternatives' contains an alist with
8579 alternative implementations of COMMAND. `define-alternatives'
8580 does not have any effect until this variable is set.
8582 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8583 `defcustom' keywords and values to add to the declaration of
8584 `COMMAND-alternatives' (typically :group and :version)."
8585 (let* ((command-name (symbol-name command))
8586 (varalt-name (concat command-name "-alternatives"))
8587 (varalt-sym (intern varalt-name))
8588 (varimp-sym (intern (concat command-name "--implementation"))))
8591 (defcustom ,varalt-sym nil
8592 ,(format "Alist of alternative implementations for the `%s' command.
8594 Each entry must be a pair (ALTNAME . ALTFUN), where:
8595 ALTNAME - The name shown at user to describe the alternative implementation.
8596 ALTFUN - The function called to implement this alternative."
8598 :type '(alist :key-type string :value-type function)
8601 (put ',varalt-sym 'definition-name ',command)
8602 (defvar ,varimp-sym nil "Internal use only.")
8604 (defun ,command (&optional arg)
8605 ,(format "Run generic command `%s'.
8606 If used for the first time, or with interactive ARG, ask the user which
8607 implementation to use for `%s'. The variable `%s'
8608 contains the list of implementations currently supported for this command."
8609 command-name command-name varalt-name)
8611 (when (or arg (null ,varimp-sym))
8612 (let ((val (completing-read
8614 "Select implementation for command `%s': "
8616 ,varalt-sym nil t)))
8617 (unless (string-equal val "")
8618 (when (null ,varimp-sym)
8620 "Use C-u M-x %s RET`to select another implementation"
8623 (customize-save-variable ',varimp-sym
8624 (cdr (assoc-string val ,varalt-sym))))))
8626 (call-interactively ,varimp-sym)
8627 (message "%s" ,(format-message
8628 "No implementation selected for command `%s'"
8632 ;;; Functions for changing capitalization that Do What I Mean
8633 (defun upcase-dwim (arg)
8634 "Upcase words in the region, if active; if not, upcase word at point.
8635 If the region is active, this function calls `upcase-region'.
8636 Otherwise, it calls `upcase-word', with prefix argument passed to it
8637 to upcase ARG words."
8640 (upcase-region (region-beginning) (region-end))
8643 (defun downcase-dwim (arg)
8644 "Downcase words in the region, if active; if not, downcase word at point.
8645 If the region is active, this function calls `downcase-region'.
8646 Otherwise, it calls `downcase-word', with prefix argument passed to it
8647 to downcase ARG words."
8650 (downcase-region (region-beginning) (region-end))
8651 (downcase-word arg)))
8653 (defun capitalize-dwim (arg)
8654 "Capitalize words in the region, if active; if not, capitalize word at point.
8655 If the region is active, this function calls `capitalize-region'.
8656 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8657 to capitalize ARG words."
8660 (capitalize-region (region-beginning) (region-end))
8661 (capitalize-word arg)))
8667 ;;; simple.el ends here