1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2016 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))
411 (arg (prefix-numeric-value arg))
413 ;; Do the rest in post-self-insert-hook, because we want to do it
414 ;; *before* other functions on that hook.
416 ;; We are not going to insert any newlines if arg is
418 (or (and (numberp arg) (<= arg 0))
419 (cl-assert (eq ?\n (char-before))))
420 ;; Mark the newline(s) `hard'.
421 (if use-hard-newlines
422 (set-hard-newline-properties
423 (- (point) arg) (point)))
424 ;; If the newline leaves the previous line blank, and we
425 ;; have a left margin, delete that from the blank line.
427 (goto-char beforepos)
429 (and (looking-at "[ \t]$")
430 (> (current-left-margin) 0)
431 (delete-region (point)
432 (line-end-position))))
433 ;; Indent the line after the newline, except in one case:
434 ;; when we added the newline at the beginning of a line which
437 (move-to-left-margin nil t)))))
439 (if (not interactive)
440 ;; FIXME: For non-interactive uses, many calls actually
441 ;; just want (insert "\n"), so maybe we should do just
442 ;; that, so as to avoid the risk of filling or running
443 ;; abbrevs unexpectedly.
444 (let ((post-self-insert-hook (list postproc)))
445 (self-insert-command arg))
448 (add-hook 'post-self-insert-hook postproc nil t)
449 (self-insert-command arg))
450 ;; We first used let-binding to protect the hook, but that
451 ;; was naive since add-hook affects the symbol-default
452 ;; value of the variable, whereas the let-binding might
453 ;; only protect the buffer-local value.
454 (remove-hook 'post-self-insert-hook postproc t)))
455 (cl-assert (not (member postproc post-self-insert-hook)))
456 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
459 (defun set-hard-newline-properties (from to)
460 (let ((sticky (get-text-property from 'rear-nonsticky)))
461 (put-text-property from to 'hard 't)
462 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
463 (if (and (listp sticky) (not (memq 'hard sticky)))
464 (put-text-property from (point) 'rear-nonsticky
465 (cons 'hard sticky)))))
468 "Insert a newline and leave point before it.
469 If there is a fill prefix and/or a `left-margin', insert them on
470 the new line if the line would have been blank.
471 With arg N, insert N newlines."
473 (let* ((do-fill-prefix (and fill-prefix (bolp)))
474 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
476 ;; Don't expand an abbrev before point.
482 (if do-left-margin (indent-to (current-left-margin)))
483 (if do-fill-prefix (insert-and-inherit fill-prefix))))
487 ;; Necessary in case a margin or prefix was inserted.
490 (defun split-line (&optional arg)
491 "Split current line, moving portion beyond point vertically down.
492 If the current line starts with `fill-prefix', insert it on the new
493 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
495 When called from Lisp code, ARG may be a prefix string to copy."
497 (skip-chars-forward " \t")
498 (let* ((col (current-column))
500 ;; What prefix should we check for (nil means don't).
501 (prefix (cond ((stringp arg) arg)
504 ;; Does this line start with it?
505 (have-prfx (and prefix
508 (looking-at (regexp-quote prefix))))))
510 (if have-prfx (insert-and-inherit prefix))
514 (defun delete-indentation (&optional arg)
515 "Join this line to previous and fix up whitespace at join.
516 If there is a fill prefix, delete it from the beginning of this line.
517 With argument, join this line to following line."
520 (if arg (forward-line 1))
521 (if (eq (preceding-char) ?\n)
523 (delete-region (point) (1- (point)))
524 ;; If the second line started with the fill prefix,
525 ;; delete the prefix.
527 (<= (+ (point) (length fill-prefix)) (point-max))
529 (buffer-substring (point)
530 (+ (point) (length fill-prefix)))))
531 (delete-region (point) (+ (point) (length fill-prefix))))
532 (fixup-whitespace))))
534 (defalias 'join-line #'delete-indentation) ; easier to find
536 (defun delete-blank-lines ()
537 "On blank line, delete all surrounding blank lines, leaving just one.
538 On isolated blank line, delete that one.
539 On nonblank line, delete any immediately following blank lines."
541 (let (thisblank singleblank)
544 (setq thisblank (looking-at "[ \t]*$"))
545 ;; Set singleblank if there is just one blank line here.
548 (not (looking-at "[ \t]*\n[ \t]*$"))
550 (progn (forward-line -1)
551 (not (looking-at "[ \t]*$")))))))
552 ;; Delete preceding blank lines, and this one too if it's the only one.
556 (if singleblank (forward-line 1))
557 (delete-region (point)
558 (if (re-search-backward "[^ \t\n]" nil t)
559 (progn (forward-line 1) (point))
561 ;; Delete following blank lines, unless the current line is blank
562 ;; and there are no following blank lines.
563 (if (not (and thisblank singleblank))
567 (delete-region (point)
568 (if (re-search-forward "[^ \t\n]" nil t)
569 (progn (beginning-of-line) (point))
571 ;; Handle the special case where point is followed by newline and eob.
572 ;; Delete the line, leaving point at eob.
573 (if (looking-at "^[ \t]*\n\\'")
574 (delete-region (point) (point-max)))))
576 (defcustom delete-trailing-lines t
577 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
578 Trailing lines are deleted only if `delete-trailing-whitespace'
579 is called on the entire buffer (rather than an active region)."
584 (defun delete-trailing-whitespace (&optional start end)
585 "Delete trailing whitespace between START and END.
586 If called interactively, START and END are the start/end of the
587 region if the mark is active, or of the buffer's accessible
588 portion if the mark is inactive.
590 This command deletes whitespace characters after the last
591 non-whitespace character in each line between START and END. It
592 does not consider formfeed characters to be whitespace.
594 If this command acts on the entire buffer (i.e. if called
595 interactively with the mark inactive, or called from Lisp with
596 END nil), it also deletes all trailing lines at the end of the
597 buffer if the variable `delete-trailing-lines' is non-nil."
599 (barf-if-buffer-read-only)
601 (list (region-beginning) (region-end))
605 (let ((end-marker (copy-marker (or end (point-max))))
606 (start (or start (point-min))))
608 (while (re-search-forward "\\s-$" end-marker t)
609 (skip-syntax-backward "-" (line-beginning-position))
610 ;; Don't delete formfeeds, even if they are considered whitespace.
611 (if (looking-at-p ".*\f")
612 (goto-char (match-end 0)))
613 (delete-region (point) (match-end 0)))
614 ;; Delete trailing empty lines.
615 (goto-char end-marker)
617 delete-trailing-lines
618 ;; Really the end of buffer.
619 (= (point-max) (1+ (buffer-size)))
620 (<= (skip-chars-backward "\n") -2))
621 (delete-region (1+ (point)) end-marker))
622 (set-marker end-marker nil))))
623 ;; Return nil for the benefit of `write-file-functions'.
626 (defun newline-and-indent ()
627 "Insert a newline, then indent according to major mode.
628 Indentation is done using the value of `indent-line-function'.
629 In programming language modes, this is the same as TAB.
630 In some text modes, where TAB inserts a tab, this command indents to the
631 column specified by the function `current-left-margin'."
633 (delete-horizontal-space t)
635 (indent-according-to-mode))
637 (defun reindent-then-newline-and-indent ()
638 "Reindent current line, insert newline, then indent the new line.
639 Indentation of both lines is done according to the current major mode,
640 which means calling the current value of `indent-line-function'.
641 In programming language modes, this is the same as TAB.
642 In some text modes, where TAB inserts a tab, this indents to the
643 column specified by the function `current-left-margin'."
646 ;; Be careful to insert the newline before indenting the line.
647 ;; Otherwise, the indentation might be wrong.
651 ;; We are at EOL before the call to indent-according-to-mode, and
652 ;; after it we usually are as well, but not always. We tried to
653 ;; address it with `save-excursion' but that uses a normal marker
654 ;; whereas we need `move after insertion', so we do the save/restore
656 (setq pos (copy-marker pos t))
657 (indent-according-to-mode)
659 ;; Remove the trailing white-space after indentation because
660 ;; indentation may introduce the whitespace.
661 (delete-horizontal-space t))
662 (indent-according-to-mode)))
664 (defcustom read-quoted-char-radix 8
665 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
666 Legitimate radix values are 8, 10 and 16."
667 :type '(choice (const 8) (const 10) (const 16))
668 :group 'editing-basics)
670 (defun read-quoted-char (&optional prompt)
671 "Like `read-char', but do not allow quitting.
672 Also, if the first character read is an octal digit,
673 we read any number of octal digits and return the
674 specified character code. Any nondigit terminates the sequence.
675 If the terminator is RET, it is discarded;
676 any other terminator is used itself as input.
678 The optional argument PROMPT specifies a string to use to prompt the user.
679 The variable `read-quoted-char-radix' controls which radix to use
681 (let ((message-log-max nil)
682 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
684 done (first t) (code 0) translated)
686 (let ((inhibit-quit first)
687 ;; Don't let C-h or other help chars get the help
688 ;; message--only help function keys. See bug#16617.
690 (help-event-list help-events)
692 "Type the special character you want to use,
693 or the octal character code.
694 RET terminates the character code and is discarded;
695 any other non-digit terminates the character code and is then used as input."))
696 (setq translated (read-key (and prompt (format "%s-" prompt))))
697 (if inhibit-quit (setq quit-flag nil)))
698 (if (integerp translated)
699 (setq translated (char-resolve-modifiers translated)))
700 (cond ((null translated))
701 ((not (integerp translated))
702 (setq unread-command-events
703 (nconc (listify-key-sequence (this-single-command-raw-keys))
704 unread-command-events)
706 ((/= (logand translated ?\M-\^@) 0)
707 ;; Turn a meta-character into a character with the 0200 bit set.
708 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
710 ((and (<= ?0 translated)
711 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
712 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
713 (and prompt (setq prompt (message "%s %c" prompt translated))))
714 ((and (<= ?a (downcase translated))
715 (< (downcase translated)
716 (+ ?a -10 (min 36 read-quoted-char-radix))))
717 (setq code (+ (* code read-quoted-char-radix)
718 (+ 10 (- (downcase translated) ?a))))
719 (and prompt (setq prompt (message "%s %c" prompt translated))))
720 ((and (not first) (eq translated ?\C-m))
723 (setq unread-command-events
724 (nconc (listify-key-sequence (this-single-command-raw-keys))
725 unread-command-events)
727 (t (setq code translated
732 (defun quoted-insert (arg)
733 "Read next input character and insert it.
734 This is useful for inserting control characters.
735 With argument, insert ARG copies of the character.
737 If the first character you type after this command is an octal digit,
738 you should type a sequence of octal digits which specify a character code.
739 Any nondigit terminates the sequence. If the terminator is a RET,
740 it is discarded; any other terminator is used itself as input.
741 The variable `read-quoted-char-radix' specifies the radix for this feature;
742 set it to 10 or 16 to use decimal or hex instead of octal.
744 In overwrite mode, this function inserts the character anyway, and
745 does not handle octal digits specially. This means that if you use
746 overwrite as your normal editing mode, you can use this function to
747 insert characters when necessary.
749 In binary overwrite mode, this function does overwrite, and octal
750 digits are interpreted as a character code. This is intended to be
751 useful for editing binary files."
754 ;; Avoid "obsolete" warnings for translation-table-for-input.
756 (let (translation-table-for-input input-method-function)
757 (if (or (not overwrite-mode)
758 (eq overwrite-mode 'overwrite-mode-binary))
761 ;; This used to assume character codes 0240 - 0377 stand for
762 ;; characters in some single-byte character set, and converted them
763 ;; to Emacs characters. But in 23.1 this feature is deprecated
764 ;; in favor of inserting the corresponding Unicode characters.
765 ;; (if (and enable-multibyte-characters
768 ;; (setq char (unibyte-char-to-multibyte char)))
769 (unless (characterp char)
770 (user-error "%s is not a valid character"
771 (key-description (vector char))))
773 (if (eq overwrite-mode 'overwrite-mode-binary)
776 (insert-and-inherit char)
777 (setq arg (1- arg)))))
779 (defun forward-to-indentation (&optional arg)
780 "Move forward ARG lines and position at first nonblank character."
782 (forward-line (or arg 1))
783 (skip-chars-forward " \t"))
785 (defun backward-to-indentation (&optional arg)
786 "Move backward ARG lines and position at first nonblank character."
788 (forward-line (- (or arg 1)))
789 (skip-chars-forward " \t"))
791 (defun back-to-indentation ()
792 "Move point to the first non-whitespace character on this line."
794 (beginning-of-line 1)
795 (skip-syntax-forward " " (line-end-position))
796 ;; Move back over chars that have whitespace syntax but have the p flag.
797 (backward-prefix-chars))
799 (defun fixup-whitespace ()
800 "Fixup white space between objects around point.
801 Leave one space or none, according to the context."
804 (delete-horizontal-space)
805 (if (or (looking-at "^\\|\\s)")
806 (save-excursion (forward-char -1)
807 (looking-at "$\\|\\s(\\|\\s'")))
811 (defun delete-horizontal-space (&optional backward-only)
812 "Delete all spaces and tabs around point.
813 If BACKWARD-ONLY is non-nil, only delete them before point."
815 (let ((orig-pos (point)))
820 (skip-chars-forward " \t")
821 (constrain-to-field nil orig-pos t)))
823 (skip-chars-backward " \t")
824 (constrain-to-field nil orig-pos)))))
826 (defun just-one-space (&optional n)
827 "Delete all spaces and tabs around point, leaving one space (or N spaces).
828 If N is negative, delete newlines as well, leaving -N spaces.
829 See also `cycle-spacing'."
831 (cycle-spacing n nil 'single-shot))
833 (defvar cycle-spacing--context nil
834 "Store context used in consecutive calls to `cycle-spacing' command.
835 The first time `cycle-spacing' runs, it saves in this variable:
836 its N argument, the original point position, and the original spacing
839 (defun cycle-spacing (&optional n preserve-nl-back mode)
840 "Manipulate whitespace around point in a smart way.
841 In interactive use, this function behaves differently in successive
844 The first call in a sequence acts like `just-one-space'.
845 It deletes all spaces and tabs around point, leaving one space
846 \(or N spaces). N is the prefix argument. If N is negative,
847 it deletes newlines as well, leaving -N spaces.
848 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
850 The second call in a sequence deletes all spaces.
852 The third call in a sequence restores the original whitespace (and point).
854 If MODE is `single-shot', it only performs the first step in the sequence.
855 If MODE is `fast' and the first step would not result in any change
856 \(i.e., there are exactly (abs N) spaces around point),
857 the function goes straight to the second step.
859 Repeatedly calling the function with different values of N starts a
860 new sequence each time."
862 (let ((orig-pos (point))
863 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
864 (num (abs (or n 1))))
865 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
866 (constrain-to-field nil orig-pos)
868 ;; Command run for the first time, single-shot mode or different argument
869 ((or (eq 'single-shot mode)
870 (not (equal last-command this-command))
871 (not cycle-spacing--context)
872 (not (eq (car cycle-spacing--context) n)))
873 (let* ((start (point))
874 (num (- num (skip-chars-forward " " (+ num (point)))))
877 (skip-chars-forward skip-characters)
878 (constrain-to-field nil orig-pos t))))
879 (setq cycle-spacing--context ;; Save for later.
880 ;; Special handling for case where there was no space at all.
881 (unless (= start end)
882 (cons n (cons orig-pos (buffer-substring start (point))))))
883 ;; If this run causes no change in buffer content, delete all spaces,
884 ;; otherwise delete all excess spaces.
885 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
887 (insert (make-string num ?\s))))
889 ;; Command run for the second time.
890 ((not (equal orig-pos (point)))
891 (delete-region (point) orig-pos))
893 ;; Command run for the third time.
895 (insert (cddr cycle-spacing--context))
896 (goto-char (cadr cycle-spacing--context))
897 (setq cycle-spacing--context nil)))))
899 (defun beginning-of-buffer (&optional arg)
900 "Move point to the beginning of the buffer.
901 With numeric arg N, put point N/10 of the way from the beginning.
902 If the buffer is narrowed, this command uses the beginning of the
903 accessible part of the buffer.
905 Push mark at previous position, unless either a \\[universal-argument] prefix
906 is supplied, or Transient Mark mode is enabled and the mark is active."
907 (declare (interactive-only "use `(goto-char (point-min))' instead."))
912 (let ((size (- (point-max) (point-min))))
913 (goto-char (if (and arg (not (consp arg)))
916 ;; Avoid overflow for large buffer sizes!
917 (* (prefix-numeric-value arg)
919 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
921 (if (and arg (not (consp arg))) (forward-line 1)))
923 (defun end-of-buffer (&optional arg)
924 "Move point to the end of the buffer.
925 With numeric arg N, put point N/10 of the way from the end.
926 If the buffer is narrowed, this command uses the end of the
927 accessible part of the buffer.
929 Push mark at previous position, unless either a \\[universal-argument] prefix
930 is supplied, or Transient Mark mode is enabled and the mark is active."
931 (declare (interactive-only "use `(goto-char (point-max))' instead."))
933 (or (consp arg) (region-active-p) (push-mark))
934 (let ((size (- (point-max) (point-min))))
935 (goto-char (if (and arg (not (consp arg)))
938 ;; Avoid overflow for large buffer sizes!
939 (* (prefix-numeric-value arg)
941 (/ (* size (prefix-numeric-value arg)) 10)))
943 ;; If we went to a place in the middle of the buffer,
944 ;; adjust it to the beginning of a line.
945 (cond ((and arg (not (consp arg))) (forward-line 1))
946 ((and (eq (current-buffer) (window-buffer))
947 (> (point) (window-end nil t)))
948 ;; If the end of the buffer is not already on the screen,
949 ;; then scroll specially to put it near, but not at, the bottom.
950 (overlay-recenter (point))
953 (defcustom delete-active-region t
954 "Whether single-char deletion commands delete an active region.
955 This has an effect only if Transient Mark mode is enabled, and
956 affects `delete-forward-char' and `delete-backward-char', though
959 If the value is the symbol `kill', the active region is killed
961 :type '(choice (const :tag "Delete active region" t)
962 (const :tag "Kill active region" kill)
963 (const :tag "Do ordinary deletion" nil))
967 (defvar region-extract-function
969 (when (region-beginning)
972 (list (cons (region-beginning) (region-end))))
973 ((eq delete 'delete-only)
974 (delete-region (region-beginning) (region-end)))
976 (filter-buffer-substring (region-beginning) (region-end) delete)))))
977 "Function to get the region's content.
978 Called with one argument DELETE.
979 If DELETE is `delete-only', then only delete the region and the return value
980 is undefined. If DELETE is nil, just return the content as a string.
981 If DELETE is `bounds', then don't delete, but just return the
982 boundaries of the region as a list of (START . END) positions.
983 If anything else, delete the region and return its content as a string,
984 after filtering it with `filter-buffer-substring'.")
986 (defvar region-insert-function
992 (insert-for-yank (car lines))
993 (setq lines (cdr lines)
995 "Function to insert the region's content.
996 Called with one argument LINES.
997 Insert the region as a list of lines.")
999 (defun delete-backward-char (n &optional killflag)
1000 "Delete the previous N characters (following if N is negative).
1001 If Transient Mark mode is enabled, the mark is active, and N is 1,
1002 delete the text in the region and deactivate the mark instead.
1003 To disable this, set option `delete-active-region' to nil.
1005 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1006 kill ring) instead of delete. Interactively, N is the prefix
1007 arg, and KILLFLAG is set if N is explicitly specified.
1009 When killing, the killed text is filtered by
1010 `filter-buffer-substring' before it is saved in the kill ring, so
1011 the actual saved text might be different from what was killed.
1013 In Overwrite mode, single character backward deletion may replace
1014 tabs with spaces so as to back over columns, unless point is at
1015 the end of the line."
1016 (declare (interactive-only delete-char))
1017 (interactive "p\nP")
1018 (unless (integerp n)
1019 (signal 'wrong-type-argument (list 'integerp n)))
1020 (cond ((and (use-region-p)
1021 delete-active-region
1023 ;; If a region is active, kill or delete it.
1024 (if (eq delete-active-region 'kill)
1025 (kill-region (region-beginning) (region-end) 'region)
1026 (funcall region-extract-function 'delete-only)))
1027 ;; In Overwrite mode, maybe untabify while deleting
1028 ((null (or (null overwrite-mode)
1030 (memq (char-before) '(?\t ?\n))
1032 (eq (char-after) ?\n)))
1033 (let ((ocol (current-column)))
1034 (delete-char (- n) killflag)
1036 (insert-char ?\s (- ocol (current-column)) nil))))
1037 ;; Otherwise, do simple deletion.
1038 (t (delete-char (- n) killflag))))
1040 (defun delete-forward-char (n &optional killflag)
1041 "Delete the following N characters (previous if N is negative).
1042 If Transient Mark mode is enabled, the mark is active, and N is 1,
1043 delete the text in the region and deactivate the mark instead.
1044 To disable this, set variable `delete-active-region' to nil.
1046 Optional second arg KILLFLAG non-nil means to kill (save in kill
1047 ring) instead of delete. Interactively, N is the prefix arg, and
1048 KILLFLAG is set if N was explicitly specified.
1050 When killing, the killed text is filtered by
1051 `filter-buffer-substring' before it is saved in the kill ring, so
1052 the actual saved text might be different from what was killed."
1053 (declare (interactive-only delete-char))
1054 (interactive "p\nP")
1055 (unless (integerp n)
1056 (signal 'wrong-type-argument (list 'integerp n)))
1057 (cond ((and (use-region-p)
1058 delete-active-region
1060 ;; If a region is active, kill or delete it.
1061 (if (eq delete-active-region 'kill)
1062 (kill-region (region-beginning) (region-end) 'region)
1063 (funcall region-extract-function 'delete-only)))
1065 ;; Otherwise, do simple deletion.
1066 (t (delete-char n killflag))))
1068 (defun mark-whole-buffer ()
1069 "Put point at beginning and mark at end of buffer.
1070 If narrowing is in effect, only uses the accessible part of the buffer.
1071 You probably should not use this function in Lisp programs;
1072 it is usually a mistake for a Lisp function to use any subroutine
1073 that uses or sets the mark."
1074 (declare (interactive-only t))
1077 (push-mark (point-max) nil t)
1078 ;; This is really `point-min' in most cases, but if we're in the
1079 ;; minibuffer, this is at the end of the prompt.
1080 (goto-char (minibuffer-prompt-end)))
1083 ;; Counting lines, one way or another.
1085 (defun goto-line (line &optional buffer)
1086 "Go to LINE, counting from line 1 at beginning of buffer.
1087 If called interactively, a numeric prefix argument specifies
1088 LINE; without a numeric prefix argument, read LINE from the
1091 If optional argument BUFFER is non-nil, switch to that buffer and
1092 move to line LINE there. If called interactively with \\[universal-argument]
1093 as argument, BUFFER is the most recently selected other buffer.
1095 Prior to moving point, this function sets the mark (without
1096 activating it), unless Transient Mark mode is enabled and the
1097 mark is already active.
1099 This function is usually the wrong thing to use in a Lisp program.
1100 What you probably want instead is something like:
1101 (goto-char (point-min))
1102 (forward-line (1- N))
1103 If at all possible, an even better solution is to use char counts
1104 rather than line counts."
1105 (declare (interactive-only forward-line))
1107 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1108 (list (prefix-numeric-value current-prefix-arg))
1109 ;; Look for a default, a number in the buffer at point.
1112 (skip-chars-backward "0-9")
1113 (if (looking-at "[0-9]")
1115 (buffer-substring-no-properties
1117 (progn (skip-chars-forward "0-9")
1119 ;; Decide if we're switching buffers.
1121 (if (consp current-prefix-arg)
1122 (other-buffer (current-buffer) t)))
1125 (concat " in " (buffer-name buffer))
1127 ;; Read the argument, offering that number (if any) as default.
1128 (list (read-number (format "Goto line%s: " buffer-prompt)
1129 (list default (line-number-at-pos)))
1131 ;; Switch to the desired buffer, one way or another.
1133 (let ((window (get-buffer-window buffer)))
1134 (if window (select-window window)
1135 (switch-to-buffer-other-window buffer))))
1136 ;; Leave mark at previous position
1137 (or (region-active-p) (push-mark))
1138 ;; Move to the specified line number in that buffer.
1141 (goto-char (point-min))
1142 (if (eq selective-display t)
1143 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1144 (forward-line (1- line)))))
1146 (defun count-words-region (start end &optional arg)
1147 "Count the number of words in the region.
1148 If called interactively, print a message reporting the number of
1149 lines, words, and characters in the region (whether or not the
1150 region is active); with prefix ARG, report for the entire buffer
1151 rather than the region.
1153 If called from Lisp, return the number of words between positions
1155 (interactive (if current-prefix-arg
1156 (list nil nil current-prefix-arg)
1157 (list (region-beginning) (region-end) nil)))
1158 (cond ((not (called-interactively-p 'any))
1159 (count-words start end))
1161 (count-words--buffer-message))
1163 (count-words--message "Region" start end))))
1165 (defun count-words (start end)
1166 "Count words between START and END.
1167 If called interactively, START and END are normally the start and
1168 end of the buffer; but if the region is active, START and END are
1169 the start and end of the region. Print a message reporting the
1170 number of lines, words, and chars.
1172 If called from Lisp, return the number of words between START and
1173 END, without printing any message."
1174 (interactive (list nil nil))
1175 (cond ((not (called-interactively-p 'any))
1179 (narrow-to-region start end)
1180 (goto-char (point-min))
1181 (while (forward-word-strictly 1)
1182 (setq words (1+ words)))))
1185 (call-interactively 'count-words-region))
1187 (count-words--buffer-message))))
1189 (defun count-words--buffer-message ()
1190 (count-words--message
1191 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1192 (point-min) (point-max)))
1194 (defun count-words--message (str start end)
1195 (let ((lines (count-lines start end))
1196 (words (count-words start end))
1197 (chars (- end start)))
1198 (message "%s has %d line%s, %d word%s, and %d character%s."
1200 lines (if (= lines 1) "" "s")
1201 words (if (= words 1) "" "s")
1202 chars (if (= chars 1) "" "s"))))
1204 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1207 "Print the current buffer line number and narrowed line number of point."
1209 (let ((start (point-min))
1210 (n (line-number-at-pos)))
1212 (message "Line %d" n)
1216 (message "line %d (narrowed line %d)"
1217 (+ n (line-number-at-pos start) -1) n))))))
1219 (defun count-lines (start end)
1220 "Return number of lines between START and END.
1221 This is usually the number of newlines between them,
1222 but can be one more if START is not equal to END
1223 and the greater of them is not at the start of a line."
1226 (narrow-to-region start end)
1227 (goto-char (point-min))
1228 (if (eq selective-display t)
1231 (while (re-search-forward "[\n\C-m]" nil t 40)
1232 (setq done (+ 40 done)))
1233 (while (re-search-forward "[\n\C-m]" nil t 1)
1234 (setq done (+ 1 done)))
1235 (goto-char (point-max))
1236 (if (and (/= start end)
1240 (- (buffer-size) (forward-line (buffer-size)))))))
1242 (defun line-number-at-pos (&optional pos)
1243 "Return (narrowed) buffer line number at position POS.
1244 If POS is nil, use current buffer location.
1245 Counting starts at (point-min), so the value refers
1246 to the contents of the accessible portion of the buffer."
1247 (let ((opoint (or pos (point))) start)
1249 (goto-char (point-min))
1250 (setq start (point))
1253 (1+ (count-lines start (point))))))
1255 (defun what-cursor-position (&optional detail)
1256 "Print info on cursor position (on screen and within buffer).
1257 Also describe the character after point, and give its character code
1258 in octal, decimal and hex.
1260 For a non-ASCII multibyte character, also give its encoding in the
1261 buffer's selected coding system if the coding system encodes the
1262 character safely. If the character is encoded into one byte, that
1263 code is shown in hex. If the character is encoded into more than one
1264 byte, just \"...\" is shown.
1266 In addition, with prefix argument, show details about that character
1267 in *Help* buffer. See also the command `describe-char'."
1269 (let* ((char (following-char))
1271 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1272 ;; start a directional embedding, which could completely
1273 ;; disrupt the rest of the line (e.g., RLO will display the
1274 ;; rest of the line right-to-left). So we put an invisible
1275 ;; PDF character after these characters, to end the
1276 ;; embedding, which eliminates any effects on the rest of
1277 ;; the line. For RLE and RLO we also append an invisible
1278 ;; LRM, to avoid reordering the following numerical
1279 ;; characters. For LRI/RLI/FSI we append a PDI.
1280 (cond ((memq char '(?\x202a ?\x202d))
1281 (propertize (string ?\x202c) 'invisible t))
1282 ((memq char '(?\x202b ?\x202e))
1283 (propertize (string ?\x202c ?\x200e) 'invisible t))
1284 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1285 (propertize (string ?\x2069) 'invisible t))
1286 ;; Strong right-to-left characters cause reordering of
1287 ;; the following numerical characters which show the
1288 ;; codepoint, so append LRM to countermand that.
1289 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1290 (propertize (string ?\x200e) 'invisible t))
1296 (total (buffer-size))
1297 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1298 (hscroll (if (= (window-hscroll) 0)
1300 (format " Hscroll=%d" (window-hscroll))))
1301 (col (current-column)))
1303 (if (or (/= beg 1) (/= end (1+ total)))
1304 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1305 pos total percent beg end col hscroll)
1306 (message "point=%d of %d (EOB) column=%d%s"
1307 pos total col hscroll))
1308 (let ((coding buffer-file-coding-system)
1309 encoded encoding-msg display-prop under-display)
1310 (if (or (not coding)
1311 (eq (coding-system-type coding) t))
1312 (setq coding (default-value 'buffer-file-coding-system)))
1313 (if (eq (char-charset char) 'eight-bit)
1315 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1316 ;; Check if the character is displayed with some `display'
1317 ;; text property. In that case, set under-display to the
1318 ;; buffer substring covered by that property.
1319 (setq display-prop (get-char-property pos 'display))
1321 (let ((to (or (next-single-char-property-change pos 'display)
1323 (if (< to (+ pos 4))
1324 (setq under-display "")
1325 (setq under-display "..."
1328 (concat (buffer-substring-no-properties pos to)
1330 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1333 (if (not (stringp display-prop))
1334 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1335 char char char under-display)
1336 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1337 char char char under-display display-prop))
1339 (format "(%d, #o%o, #x%x, file %s)"
1341 (if (> (length encoded) 1)
1343 (encoded-string-description encoded coding)))
1344 (format "(%d, #o%o, #x%x)" char char char)))))
1346 ;; We show the detailed information about CHAR.
1347 (describe-char (point)))
1348 (if (or (/= beg 1) (/= end (1+ total)))
1349 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1351 (single-key-description char)
1352 (buffer-substring-no-properties (point) (1+ (point))))
1354 encoding-msg pos total percent beg end col hscroll)
1355 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1356 (if enable-multibyte-characters
1358 (single-key-description char)
1359 (buffer-substring-no-properties (point) (1+ (point))))
1360 (single-key-description char))
1361 bidi-fixer encoding-msg pos total percent col hscroll))))))
1363 ;; Initialize read-expression-map. It is defined at C level.
1364 (defvar read-expression-map
1365 (let ((m (make-sparse-keymap)))
1366 (define-key m "\M-\t" 'completion-at-point)
1367 ;; Might as well bind TAB to completion, since inserting a TAB char is
1368 ;; much too rarely useful.
1369 (define-key m "\t" 'completion-at-point)
1370 (set-keymap-parent m minibuffer-local-map)
1373 (defun read-minibuffer (prompt &optional initial-contents)
1374 "Return a Lisp object read using the minibuffer, unevaluated.
1375 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1376 is a string to insert in the minibuffer before reading.
1377 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1378 Such arguments are used as in `read-from-minibuffer'.)"
1379 ;; Used for interactive spec `x'.
1380 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1381 t 'minibuffer-history))
1383 (defun eval-minibuffer (prompt &optional initial-contents)
1384 "Return value of Lisp expression read using the minibuffer.
1385 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1386 is a string to insert in the minibuffer before reading.
1387 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1388 Such arguments are used as in `read-from-minibuffer'.)"
1389 ;; Used for interactive spec `X'.
1390 (eval (read--expression prompt initial-contents)))
1392 (defvar minibuffer-completing-symbol nil
1393 "Non-nil means completing a Lisp symbol in the minibuffer.")
1394 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1396 (defvar minibuffer-default nil
1397 "The current default value or list of default values in the minibuffer.
1398 The functions `read-from-minibuffer' and `completing-read' bind
1399 this variable locally.")
1401 (defcustom eval-expression-print-level 4
1402 "Value for `print-level' while printing value in `eval-expression'.
1403 A value of nil means no limit."
1405 :type '(choice (const :tag "No Limit" nil) integer)
1408 (defcustom eval-expression-print-length 12
1409 "Value for `print-length' while printing value in `eval-expression'.
1410 A value of nil means no limit."
1412 :type '(choice (const :tag "No Limit" nil) integer)
1415 (defcustom eval-expression-debug-on-error t
1416 "If non-nil set `debug-on-error' to t in `eval-expression'.
1417 If nil, don't change the value of `debug-on-error'."
1422 (defun eval-expression-print-format (value)
1423 "Format VALUE as a result of evaluated expression.
1424 Return a formatted string which is displayed in the echo area
1425 in addition to the value printed by prin1 in functions which
1426 display the result of expression evaluation."
1427 (if (and (integerp value)
1428 (or (eq standard-output t)
1429 (zerop (prefix-numeric-value current-prefix-arg))))
1431 (if (and (characterp value)
1432 (char-displayable-p value))
1433 (prin1-char value))))
1435 (format " (#o%o, #x%x, %s)" value value char-string)
1436 (format " (#o%o, #x%x)" value value)))))
1438 (defvar eval-expression-minibuffer-setup-hook nil
1439 "Hook run by `eval-expression' when entering the minibuffer.")
1441 (defun read--expression (prompt &optional initial-contents)
1442 (let ((minibuffer-completing-symbol t))
1443 (minibuffer-with-setup-hook
1445 ;; FIXME: call emacs-lisp-mode?
1446 (add-function :before-until (local 'eldoc-documentation-function)
1447 #'elisp-eldoc-documentation-function)
1448 (add-hook 'completion-at-point-functions
1449 #'elisp-completion-at-point nil t)
1450 (run-hooks 'eval-expression-minibuffer-setup-hook))
1451 (read-from-minibuffer prompt initial-contents
1452 read-expression-map t
1453 'read-expression-history))))
1455 ;; We define this, rather than making `eval' interactive,
1456 ;; for the sake of completion of names like eval-region, eval-buffer.
1457 (defun eval-expression (exp &optional insert-value)
1458 "Evaluate EXP and print value in the echo area.
1459 When called interactively, read an Emacs Lisp expression and evaluate it.
1460 Value is also consed on to front of the variable `values'.
1461 Optional argument INSERT-VALUE non-nil (interactively, with prefix
1462 argument) means insert the result into the current buffer instead of
1463 printing it in the echo area.
1465 Normally, this function truncates long output according to the value
1466 of the variables `eval-expression-print-length' and
1467 `eval-expression-print-level'. With a prefix argument of zero,
1468 however, there is no such truncation. Such a prefix argument
1469 also causes integers to be printed in several additional formats
1470 \(octal, hexadecimal, and character).
1472 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1475 If `eval-expression-debug-on-error' is non-nil, which is the default,
1476 this command arranges for all errors to enter the debugger."
1478 (list (read--expression "Eval: ")
1479 current-prefix-arg))
1481 (if (null eval-expression-debug-on-error)
1482 (push (eval exp lexical-binding) values)
1483 (let ((old-value (make-symbol "t")) new-value)
1484 ;; Bind debug-on-error to something unique so that we can
1485 ;; detect when evalled code changes it.
1486 (let ((debug-on-error old-value))
1487 (push (eval (macroexpand-all exp) lexical-binding) values)
1488 (setq new-value debug-on-error))
1489 ;; If evalled code has changed the value of debug-on-error,
1490 ;; propagate that change to the global binding.
1491 (unless (eq old-value new-value)
1492 (setq debug-on-error new-value))))
1494 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1495 eval-expression-print-length))
1496 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1497 eval-expression-print-level))
1501 (let ((standard-output (current-buffer)))
1503 (prin1 (car values))
1504 (when (zerop (prefix-numeric-value insert-value))
1505 (let ((str (eval-expression-print-format (car values))))
1506 (if str (princ str)))))))
1508 (prin1 (car values) t)
1509 (let ((str (eval-expression-print-format (car values))))
1510 (if str (princ str t)))))))
1512 (defun edit-and-eval-command (prompt command)
1513 "Prompting with PROMPT, let user edit COMMAND and eval result.
1514 COMMAND is a Lisp expression. Let user edit that expression in
1515 the minibuffer, then read and evaluate the result."
1517 (let ((print-level nil)
1518 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1520 (read-from-minibuffer prompt
1521 (prin1-to-string command)
1522 read-expression-map t
1524 ;; If command was added to command-history as a string,
1525 ;; get rid of that. We want only evaluable expressions there.
1526 (if (stringp (car command-history))
1527 (setq command-history (cdr command-history)))))))
1529 ;; If command to be redone does not match front of history,
1530 ;; add it to the history.
1531 (or (equal command (car command-history))
1532 (setq command-history (cons command command-history)))
1535 (defun repeat-complex-command (arg)
1536 "Edit and re-evaluate last complex command, or ARGth from last.
1537 A complex command is one which used the minibuffer.
1538 The command is placed in the minibuffer as a Lisp form for editing.
1539 The result is executed, repeating the command as changed.
1540 If the command has been changed or is not the most recent previous
1541 command it is added to the front of the command history.
1542 You can use the minibuffer history commands \
1543 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1544 to get different commands to edit and resubmit."
1546 (let ((elt (nth (1- arg) command-history))
1551 (let ((print-level nil)
1552 (minibuffer-history-position arg)
1553 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1555 (read-from-minibuffer
1556 "Redo: " (prin1-to-string elt) read-expression-map t
1557 (cons 'command-history arg))
1559 ;; If command was added to command-history as a
1560 ;; string, get rid of that. We want only
1561 ;; evaluable expressions there.
1562 (if (stringp (car command-history))
1563 (setq command-history (cdr command-history))))))
1565 ;; If command to be redone does not match front of history,
1566 ;; add it to the history.
1567 (or (equal newcmd (car command-history))
1568 (setq command-history (cons newcmd command-history)))
1569 (apply #'funcall-interactively
1571 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1573 (error "Argument %d is beyond length of command history" arg)
1574 (error "There are no previous complex commands to repeat")))))
1577 (defvar extended-command-history nil)
1578 (defvar execute-extended-command--last-typed nil)
1580 (defun read-extended-command ()
1581 "Read command name to invoke in `execute-extended-command'."
1582 (minibuffer-with-setup-hook
1584 (add-hook 'post-self-insert-hook
1586 (setq execute-extended-command--last-typed
1587 (minibuffer-contents)))
1589 (set (make-local-variable 'minibuffer-default-add-function)
1591 ;; Get a command name at point in the original buffer
1592 ;; to propose it after M-n.
1593 (with-current-buffer (window-buffer (minibuffer-selected-window))
1594 (and (commandp (function-called-at-point))
1595 (format "%S" (function-called-at-point)))))))
1596 ;; Read a string, completing from and restricting to the set of
1597 ;; all defined commands. Don't provide any initial input.
1598 ;; Save the command read on the extended-command history list.
1601 ((eq current-prefix-arg '-) "- ")
1602 ((and (consp current-prefix-arg)
1603 (eq (car current-prefix-arg) 4)) "C-u ")
1604 ((and (consp current-prefix-arg)
1605 (integerp (car current-prefix-arg)))
1606 (format "%d " (car current-prefix-arg)))
1607 ((integerp current-prefix-arg)
1608 (format "%d " current-prefix-arg)))
1609 ;; This isn't strictly correct if `execute-extended-command'
1610 ;; is bound to anything else (e.g. [menu]).
1611 ;; It could use (key-description (this-single-command-keys)),
1612 ;; but actually a prompt other than "M-x" would be confusing,
1613 ;; because "M-x" is a well-known prompt to read a command
1614 ;; and it serves as a shorthand for "Extended command: ".
1616 (lambda (string pred action)
1618 (if (memq action '(nil t))
1619 ;; Exclude obsolete commands from completions.
1621 (and (funcall pred sym)
1622 (or (equal string (symbol-name sym))
1623 (not (get sym 'byte-obsolete-info)))))
1625 (complete-with-action action obarray string pred)))
1626 #'commandp t nil 'extended-command-history)))
1628 (defcustom suggest-key-bindings t
1629 "Non-nil means show the equivalent key-binding when M-x command has one.
1630 The value can be a length of time to show the message for.
1631 If the value is non-nil and not a number, we wait 2 seconds."
1633 :type '(choice (const :tag "off" nil)
1634 (integer :tag "time" 2)
1637 (defun execute-extended-command--shorter-1 (name length)
1639 ((zerop length) (list ""))
1640 ((equal name "") nil)
1642 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1643 (execute-extended-command--shorter-1
1644 (substring name 1) (1- length)))
1645 (when (string-match "\\`\\(-\\)?[^-]*" name)
1646 (execute-extended-command--shorter-1
1647 (substring name (match-end 0)) length))))))
1649 (defun execute-extended-command--shorter (name typed)
1650 (let ((candidates '())
1651 (max (length typed))
1654 (while (and (not binding)
1658 (setq candidates (execute-extended-command--shorter-1
1660 ;; Don't show the help message if the binding isn't
1661 ;; significantly shorter than the M-x command the user typed.
1663 (let ((candidate (pop candidates)))
1665 (car-safe (completion-try-completion
1666 candidate obarray 'commandp len)))
1667 (setq binding candidate))))
1670 (defun execute-extended-command (prefixarg &optional command-name typed)
1671 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1672 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1673 "Read a command name, then read the arguments and call the command.
1674 To pass a prefix argument to the command you are
1675 invoking, give a prefix argument to `execute-extended-command'."
1676 (declare (interactive-only command-execute))
1677 ;; FIXME: Remember the actual text typed by the user before completion,
1678 ;; so that we don't later on suggest the same shortening.
1680 (let ((execute-extended-command--last-typed nil))
1681 (list current-prefix-arg
1682 (read-extended-command)
1683 execute-extended-command--last-typed)))
1684 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1685 (unless command-name
1686 (let ((current-prefix-arg prefixarg) ; for prompt
1687 (execute-extended-command--last-typed nil))
1688 (setq command-name (read-extended-command))
1689 (setq typed execute-extended-command--last-typed)))
1690 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1691 (binding (and suggest-key-bindings
1692 (not executing-kbd-macro)
1693 (where-is-internal function overriding-local-map t))))
1694 (unless (commandp function)
1695 (error "`%s' is not a valid command name" command-name))
1696 (setq this-command function)
1697 ;; Normally `real-this-command' should never be changed, but here we really
1698 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1699 ;; binding" for <cmd>, so the command the user really wanted to run is
1700 ;; `function' and not `execute-extended-command'. The difference is
1701 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1702 (setq real-this-command function)
1703 (let ((prefix-arg prefixarg))
1704 (command-execute function 'record))
1705 ;; If enabled, show which key runs this command.
1706 ;; But first wait, and skip the message if there is input.
1708 ;; If this command displayed something in the echo area;
1709 ;; wait a few seconds, then display our suggestion message.
1710 ;; FIXME: Wait *after* running post-command-hook!
1711 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1712 ;; find a better answer anyway!
1713 (when suggest-key-bindings
1715 ((zerop (length (current-message))) 0)
1716 ((numberp suggest-key-bindings) suggest-key-bindings)
1718 (when (and waited (not (consp unread-command-events)))
1719 (unless (or binding executing-kbd-macro (not (symbolp function))
1720 (<= (length (symbol-name function)) 2))
1721 ;; There's no binding for CMD. Let's try and find the shortest
1722 ;; string to use in M-x.
1723 ;; FIXME: Can be slow. Cache it maybe?
1725 (setq binding (execute-extended-command--shorter
1726 (symbol-name function) typed))))
1729 (format-message "You can run the command `%s' with %s"
1731 (if (stringp binding)
1732 (concat "M-x " binding " RET")
1733 (key-description binding)))
1734 (sit-for (if (numberp suggest-key-bindings)
1735 suggest-key-bindings
1738 (defun command-execute (cmd &optional record-flag keys special)
1739 ;; BEWARE: Called directly from the C code.
1740 "Execute CMD as an editor command.
1741 CMD must be a symbol that satisfies the `commandp' predicate.
1742 Optional second arg RECORD-FLAG non-nil
1743 means unconditionally put this command in the variable `command-history'.
1744 Otherwise, that is done only if an arg is read using the minibuffer.
1745 The argument KEYS specifies the value to use instead of (this-command-keys)
1746 when reading the arguments; if it is nil, (this-command-keys) is used.
1747 The argument SPECIAL, if non-nil, means that this command is executing
1748 a special event, so ignore the prefix argument and don't clear it."
1749 (setq debug-on-next-call nil)
1750 (let ((prefixarg (unless special
1751 ;; FIXME: This should probably be done around
1752 ;; pre-command-hook rather than here!
1754 (setq current-prefix-arg prefix-arg)
1755 (setq prefix-arg nil)
1756 (when current-prefix-arg
1757 (prefix-command-update))))))
1758 (if (and (symbolp cmd)
1760 disabled-command-function)
1761 ;; FIXME: Weird calling convention!
1762 (run-hooks 'disabled-command-function)
1766 (setq final (indirect-function final))
1767 (if (autoloadp final)
1768 (setq final (autoload-do-load final cmd)))))
1771 ;; If requested, place the macro in the command history. For
1772 ;; other sorts of commands, call-interactively takes care of this.
1774 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1775 ;; Don't keep command history around forever.
1776 (when (and (numberp history-length) (> history-length 0))
1777 (let ((cell (nthcdr history-length command-history)))
1778 (if (consp cell) (setcdr cell nil)))))
1779 (execute-kbd-macro final prefixarg))
1781 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1782 (prog1 (call-interactively cmd record-flag keys)
1783 (when (and (symbolp cmd)
1784 (get cmd 'byte-obsolete-info)
1785 (not (get cmd 'command-execute-obsolete-warned)))
1786 (put cmd 'command-execute-obsolete-warned t)
1787 (message "%s" (macroexp--obsolete-warning
1788 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1790 (defvar minibuffer-history nil
1791 "Default minibuffer history list.
1792 This is used for all minibuffer input
1793 except when an alternate history list is specified.
1795 Maximum length of the history list is determined by the value
1796 of `history-length', which see.")
1797 (defvar minibuffer-history-sexp-flag nil
1798 "Control whether history list elements are expressions or strings.
1799 If the value of this variable equals current minibuffer depth,
1800 they are expressions; otherwise they are strings.
1801 \(That convention is designed to do the right thing for
1802 recursive uses of the minibuffer.)")
1803 (setq minibuffer-history-variable 'minibuffer-history)
1804 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1805 (defvar minibuffer-history-search-history nil)
1807 (defvar minibuffer-text-before-history nil
1808 "Text that was in this minibuffer before any history commands.
1809 This is nil if there have not yet been any history commands
1810 in this use of the minibuffer.")
1812 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1814 (defun minibuffer-history-initialize ()
1815 (setq minibuffer-text-before-history nil))
1817 (defun minibuffer-avoid-prompt (_new _old)
1818 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1819 (declare (obsolete cursor-intangible-mode "25.1"))
1820 (constrain-to-field nil (point-max)))
1822 (defcustom minibuffer-history-case-insensitive-variables nil
1823 "Minibuffer history variables for which matching should ignore case.
1824 If a history variable is a member of this list, then the
1825 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1826 commands ignore case when searching it, regardless of `case-fold-search'."
1827 :type '(repeat variable)
1830 (defun previous-matching-history-element (regexp n)
1831 "Find the previous history element that matches REGEXP.
1832 \(Previous history elements refer to earlier actions.)
1833 With prefix argument N, search for Nth previous match.
1834 If N is negative, find the next or Nth next match.
1835 Normally, history elements are matched case-insensitively if
1836 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1837 makes the search case-sensitive.
1838 See also `minibuffer-history-case-insensitive-variables'."
1840 (let* ((enable-recursive-minibuffers t)
1841 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1843 minibuffer-local-map
1845 'minibuffer-history-search-history
1846 (car minibuffer-history-search-history))))
1847 ;; Use the last regexp specified, by default, if input is empty.
1848 (list (if (string= regexp "")
1849 (if minibuffer-history-search-history
1850 (car minibuffer-history-search-history)
1851 (user-error "No previous history search regexp"))
1853 (prefix-numeric-value current-prefix-arg))))
1855 (if (and (zerop minibuffer-history-position)
1856 (null minibuffer-text-before-history))
1857 (setq minibuffer-text-before-history
1858 (minibuffer-contents-no-properties)))
1859 (let ((history (symbol-value minibuffer-history-variable))
1861 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1862 ;; On some systems, ignore case for file names.
1863 (if (memq minibuffer-history-variable
1864 minibuffer-history-case-insensitive-variables)
1866 ;; Respect the user's setting for case-fold-search:
1872 (pos minibuffer-history-position))
1875 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1876 (when (= pos prevpos)
1877 (user-error (if (= pos 1)
1878 "No later matching history item"
1879 "No earlier matching history item")))
1881 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1882 (let ((print-level nil))
1883 (prin1-to-string (nth (1- pos) history)))
1884 (nth (1- pos) history)))
1887 (and (string-match regexp match-string)
1889 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1890 (match-beginning 1))))
1892 (setq n (+ n (if (< n 0) 1 -1)))))
1893 (setq minibuffer-history-position pos)
1894 (goto-char (point-max))
1895 (delete-minibuffer-contents)
1896 (insert match-string)
1897 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1898 (if (memq (car (car command-history)) '(previous-matching-history-element
1899 next-matching-history-element))
1900 (setq command-history (cdr command-history))))
1902 (defun next-matching-history-element (regexp n)
1903 "Find the next history element that matches REGEXP.
1904 \(The next history element refers to a more recent action.)
1905 With prefix argument N, search for Nth next match.
1906 If N is negative, find the previous or Nth previous match.
1907 Normally, history elements are matched case-insensitively if
1908 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1909 makes the search case-sensitive."
1911 (let* ((enable-recursive-minibuffers t)
1912 (regexp (read-from-minibuffer "Next element matching (regexp): "
1914 minibuffer-local-map
1916 'minibuffer-history-search-history
1917 (car minibuffer-history-search-history))))
1918 ;; Use the last regexp specified, by default, if input is empty.
1919 (list (if (string= regexp "")
1920 (if minibuffer-history-search-history
1921 (car minibuffer-history-search-history)
1922 (user-error "No previous history search regexp"))
1924 (prefix-numeric-value current-prefix-arg))))
1925 (previous-matching-history-element regexp (- n)))
1927 (defvar minibuffer-temporary-goal-position nil)
1929 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1930 "Function run by `goto-history-element' before consuming default values.
1931 This is useful to dynamically add more elements to the list of default values
1932 when `goto-history-element' reaches the end of this list.
1933 Before calling this function `goto-history-element' sets the variable
1934 `minibuffer-default-add-done' to t, so it will call this function only
1935 once. In special cases, when this function needs to be called more
1936 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1937 overriding the setting of this variable to t in `goto-history-element'.")
1939 (defvar minibuffer-default-add-done nil
1940 "When nil, add more elements to the end of the list of default values.
1941 The value nil causes `goto-history-element' to add more elements to
1942 the list of defaults when it reaches the end of this list. It does
1943 this by calling a function defined by `minibuffer-default-add-function'.")
1945 (make-variable-buffer-local 'minibuffer-default-add-done)
1947 (defun minibuffer-default-add-completions ()
1948 "Return a list of all completions without the default value.
1949 This function is used to add all elements of the completion table to
1950 the end of the list of defaults just after the default value."
1951 (let ((def minibuffer-default)
1952 (all (all-completions ""
1953 minibuffer-completion-table
1954 minibuffer-completion-predicate)))
1957 (cons def (delete def all)))))
1959 (defun goto-history-element (nabs)
1960 "Puts element of the minibuffer history in the minibuffer.
1961 The argument NABS specifies the absolute history position."
1963 (when (and (not minibuffer-default-add-done)
1964 (functionp minibuffer-default-add-function)
1965 (< nabs (- (if (listp minibuffer-default)
1966 (length minibuffer-default)
1968 (setq minibuffer-default-add-done t
1969 minibuffer-default (funcall minibuffer-default-add-function)))
1970 (let ((minimum (if minibuffer-default
1971 (- (if (listp minibuffer-default)
1972 (length minibuffer-default)
1975 elt minibuffer-returned-to-present)
1976 (if (and (zerop minibuffer-history-position)
1977 (null minibuffer-text-before-history))
1978 (setq minibuffer-text-before-history
1979 (minibuffer-contents-no-properties)))
1980 (if (< nabs minimum)
1981 (user-error (if minibuffer-default
1982 "End of defaults; no next item"
1983 "End of history; no default available")))
1984 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
1985 (length (symbol-value minibuffer-history-variable))
1987 (user-error "Beginning of history; no preceding item"))
1988 (unless (memq last-command '(next-history-element
1989 previous-history-element))
1990 (let ((prompt-end (minibuffer-prompt-end)))
1991 (set (make-local-variable 'minibuffer-temporary-goal-position)
1992 (cond ((<= (point) prompt-end) prompt-end)
1995 (goto-char (point-max))
1996 (delete-minibuffer-contents)
1997 (setq minibuffer-history-position nabs)
1999 (setq elt (if (listp minibuffer-default)
2000 (nth (1- (abs nabs)) minibuffer-default)
2001 minibuffer-default)))
2003 (setq elt (or minibuffer-text-before-history ""))
2004 (setq minibuffer-returned-to-present t)
2005 (setq minibuffer-text-before-history nil))
2006 (t (setq elt (nth (1- minibuffer-history-position)
2007 (symbol-value minibuffer-history-variable)))))
2009 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2010 (not minibuffer-returned-to-present))
2011 (let ((print-level nil))
2012 (prin1-to-string elt))
2014 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2016 (defun next-history-element (n)
2017 "Puts next element of the minibuffer history in the minibuffer.
2018 With argument N, it uses the Nth following element."
2021 (goto-history-element (- minibuffer-history-position n))))
2023 (defun previous-history-element (n)
2024 "Puts previous element of the minibuffer history in the minibuffer.
2025 With argument N, it uses the Nth previous element."
2028 (goto-history-element (+ minibuffer-history-position n))))
2030 (defun next-line-or-history-element (&optional arg)
2031 "Move cursor vertically down ARG lines, or to the next history element.
2032 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2033 next element of the minibuffer history in the minibuffer."
2035 (or arg (setq arg 1))
2036 (let* ((old-point (point))
2037 ;; Remember the original goal column of possibly multi-line input
2038 ;; excluding the length of the prompt on the first line.
2039 (prompt-end (minibuffer-prompt-end))
2040 (old-column (unless (and (eolp) (> (point) prompt-end))
2041 (if (= (line-number-at-pos) 1)
2042 (max (- (current-column) (1- prompt-end)) 0)
2043 (current-column)))))
2048 ;; Restore old position since `line-move-visual' moves point to
2049 ;; the end of the line when it fails to go to the next line.
2050 (goto-char old-point)
2051 (next-history-element arg)
2052 ;; Reset `temporary-goal-column' because a correct value is not
2053 ;; calculated when `next-line' above fails by bumping against
2054 ;; the bottom of the minibuffer (bug#22544).
2055 (setq temporary-goal-column 0)
2056 ;; Restore the original goal column on the last line
2057 ;; of possibly multi-line input.
2058 (goto-char (point-max))
2060 (if (= (line-number-at-pos) 1)
2061 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2062 (move-to-column old-column)))))))
2064 (defun previous-line-or-history-element (&optional arg)
2065 "Move cursor vertically up ARG lines, or to the previous history element.
2066 When point moves over the top line of multi-line minibuffer, puts ARGth
2067 previous element of the minibuffer history in the minibuffer."
2069 (or arg (setq arg 1))
2070 (let* ((old-point (point))
2071 ;; Remember the original goal column of possibly multi-line input
2072 ;; excluding the length of the prompt on the first line.
2073 (prompt-end (minibuffer-prompt-end))
2074 (old-column (unless (and (eolp) (> (point) prompt-end))
2075 (if (= (line-number-at-pos) 1)
2076 (max (- (current-column) (1- prompt-end)) 0)
2077 (current-column)))))
2080 (previous-line arg))
2081 (beginning-of-buffer
2082 ;; Restore old position since `line-move-visual' moves point to
2083 ;; the beginning of the line when it fails to go to the previous line.
2084 (goto-char old-point)
2085 (previous-history-element arg)
2086 ;; Reset `temporary-goal-column' because a correct value is not
2087 ;; calculated when `previous-line' above fails by bumping against
2088 ;; the top of the minibuffer (bug#22544).
2089 (setq temporary-goal-column 0)
2090 ;; Restore the original goal column on the first line
2091 ;; of possibly multi-line input.
2092 (goto-char (minibuffer-prompt-end))
2094 (if (= (line-number-at-pos) 1)
2095 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2096 (move-to-column old-column))
2097 ;; Put the cursor at the end of the visual line instead of the
2098 ;; logical line, so the next `previous-line-or-history-element'
2099 ;; would move to the previous history element, not to a possible upper
2100 ;; visual line from the end of logical line in `line-move-visual' mode.
2101 (end-of-visual-line)
2102 ;; Since `end-of-visual-line' puts the cursor at the beginning
2103 ;; of the next visual line, move it one char back to the end
2104 ;; of the first visual line (bug#22544).
2105 (unless (eolp) (backward-char 1)))))))
2107 (defun next-complete-history-element (n)
2108 "Get next history element which completes the minibuffer before the point.
2109 The contents of the minibuffer after the point are deleted, and replaced
2110 by the new completion."
2112 (let ((point-at-start (point)))
2113 (next-matching-history-element
2115 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2117 ;; next-matching-history-element always puts us at (point-min).
2118 ;; Move to the position we were at before changing the buffer contents.
2119 ;; This is still sensible, because the text before point has not changed.
2120 (goto-char point-at-start)))
2122 (defun previous-complete-history-element (n)
2124 Get previous history element which completes the minibuffer before the point.
2125 The contents of the minibuffer after the point are deleted, and replaced
2126 by the new completion."
2128 (next-complete-history-element (- n)))
2130 ;; For compatibility with the old subr of the same name.
2131 (defun minibuffer-prompt-width ()
2132 "Return the display width of the minibuffer prompt.
2133 Return 0 if current buffer is not a minibuffer."
2134 ;; Return the width of everything before the field at the end of
2135 ;; the buffer; this should be 0 for normal buffers.
2136 (1- (minibuffer-prompt-end)))
2138 ;; isearch minibuffer history
2139 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2141 (defvar minibuffer-history-isearch-message-overlay)
2142 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2144 (defun minibuffer-history-isearch-setup ()
2145 "Set up a minibuffer for using isearch to search the minibuffer history.
2146 Intended to be added to `minibuffer-setup-hook'."
2147 (set (make-local-variable 'isearch-search-fun-function)
2148 'minibuffer-history-isearch-search)
2149 (set (make-local-variable 'isearch-message-function)
2150 'minibuffer-history-isearch-message)
2151 (set (make-local-variable 'isearch-wrap-function)
2152 'minibuffer-history-isearch-wrap)
2153 (set (make-local-variable 'isearch-push-state-function)
2154 'minibuffer-history-isearch-push-state)
2155 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2157 (defun minibuffer-history-isearch-end ()
2158 "Clean up the minibuffer after terminating isearch in the minibuffer."
2159 (if minibuffer-history-isearch-message-overlay
2160 (delete-overlay minibuffer-history-isearch-message-overlay)))
2162 (defun minibuffer-history-isearch-search ()
2163 "Return the proper search function, for isearch in minibuffer history."
2164 (lambda (string bound noerror)
2166 ;; Use standard functions to search within minibuffer text
2167 (isearch-search-fun-default))
2169 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2170 ;; searching forward. Lazy-highlight calls this lambda with the
2171 ;; bound arg, so skip the minibuffer prompt.
2172 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2173 (goto-char (minibuffer-prompt-end)))
2175 ;; 1. First try searching in the initial minibuffer text
2176 (funcall search-fun string
2177 (if isearch-forward bound (minibuffer-prompt-end))
2179 ;; 2. If the above search fails, start putting next/prev history
2180 ;; elements in the minibuffer successively, and search the string
2181 ;; in them. Do this only when bound is nil (i.e. not while
2182 ;; lazy-highlighting search strings in the current minibuffer text).
2187 (cond (isearch-forward
2188 (next-history-element 1)
2189 (goto-char (minibuffer-prompt-end)))
2191 (previous-history-element 1)
2192 (goto-char (point-max))))
2193 (setq isearch-barrier (point) isearch-opoint (point))
2194 ;; After putting the next/prev history element, search
2195 ;; the string in them again, until next-history-element
2196 ;; or previous-history-element raises an error at the
2197 ;; beginning/end of history.
2198 (setq found (funcall search-fun string
2199 (unless isearch-forward
2200 ;; For backward search, don't search
2201 ;; in the minibuffer prompt
2202 (minibuffer-prompt-end))
2204 ;; Return point of the new search result
2206 ;; Return nil when next(prev)-history-element fails
2209 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2210 "Display the minibuffer history search prompt.
2211 If there are no search errors, this function displays an overlay with
2212 the isearch prompt which replaces the original minibuffer prompt.
2213 Otherwise, it displays the standard isearch message returned from
2214 the function `isearch-message'."
2215 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2216 ;; Use standard function `isearch-message' when not in the minibuffer,
2217 ;; or search fails, or has an error (like incomplete regexp).
2218 ;; This function overwrites minibuffer text with isearch message,
2219 ;; so it's possible to see what is wrong in the search string.
2220 (isearch-message c-q-hack ellipsis)
2221 ;; Otherwise, put the overlay with the standard isearch prompt over
2222 ;; the initial minibuffer prompt.
2223 (if (overlayp minibuffer-history-isearch-message-overlay)
2224 (move-overlay minibuffer-history-isearch-message-overlay
2225 (point-min) (minibuffer-prompt-end))
2226 (setq minibuffer-history-isearch-message-overlay
2227 (make-overlay (point-min) (minibuffer-prompt-end)))
2228 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2229 (overlay-put minibuffer-history-isearch-message-overlay
2230 'display (isearch-message-prefix c-q-hack ellipsis))
2231 ;; And clear any previous isearch message.
2234 (defun minibuffer-history-isearch-wrap ()
2235 "Wrap the minibuffer history search when search fails.
2236 Move point to the first history element for a forward search,
2237 or to the last history element for a backward search."
2238 ;; When `minibuffer-history-isearch-search' fails on reaching the
2239 ;; beginning/end of the history, wrap the search to the first/last
2240 ;; minibuffer history element.
2242 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2243 (goto-history-element 0))
2244 (setq isearch-success t)
2245 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2247 (defun minibuffer-history-isearch-push-state ()
2248 "Save a function restoring the state of minibuffer history search.
2249 Save `minibuffer-history-position' to the additional state parameter
2250 in the search status stack."
2251 (let ((pos minibuffer-history-position))
2253 (minibuffer-history-isearch-pop-state cmd pos))))
2255 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2256 "Restore the minibuffer history search state.
2257 Go to the history element by the absolute history position HIST-POS."
2258 (goto-history-element hist-pos))
2261 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2262 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2264 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2265 "Table mapping redo records to the corresponding undo one.
2266 A redo record for undo-in-region maps to t.
2267 A redo record for ordinary undo maps to the following (earlier) undo.")
2269 (defvar undo-in-region nil
2270 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2272 (defvar undo-no-redo nil
2273 "If t, `undo' doesn't go through redo entries.")
2275 (defvar pending-undo-list nil
2276 "Within a run of consecutive undo commands, list remaining to be undone.
2277 If t, we undid all the way to the end of it.")
2279 (defun undo (&optional arg)
2280 "Undo some previous changes.
2281 Repeat this command to undo more changes.
2282 A numeric ARG serves as a repeat count.
2284 In Transient Mark mode when the mark is active, only undo changes within
2285 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2286 as an argument limits undo to changes within the current region."
2288 ;; Make last-command indicate for the next command that this was an undo.
2289 ;; That way, another undo will undo more.
2290 ;; If we get to the end of the undo history and get an error,
2291 ;; another undo command will find the undo history empty
2292 ;; and will get another error. To begin undoing the undos,
2293 ;; you must type some other command.
2294 (let* ((modified (buffer-modified-p))
2295 ;; For an indirect buffer, look in the base buffer for the
2297 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2298 (recent-save (with-current-buffer base-buffer
2299 (recent-auto-save-p)))
2301 ;; If we get an error in undo-start,
2302 ;; the next command should not be a "consecutive undo".
2303 ;; So set `this-command' to something other than `undo'.
2304 (setq this-command 'undo-start)
2306 (unless (and (eq last-command 'undo)
2307 (or (eq pending-undo-list t)
2308 ;; If something (a timer or filter?) changed the buffer
2309 ;; since the previous command, don't continue the undo seq.
2310 (let ((list buffer-undo-list))
2311 (while (eq (car list) nil)
2312 (setq list (cdr list)))
2313 ;; If the last undo record made was made by undo
2314 ;; it shows nothing else happened in between.
2315 (gethash list undo-equiv-table))))
2316 (setq undo-in-region
2317 (or (region-active-p) (and arg (not (numberp arg)))))
2319 (undo-start (region-beginning) (region-end))
2321 ;; get rid of initial undo boundary
2323 ;; If we got this far, the next command should be a consecutive undo.
2324 (setq this-command 'undo)
2325 ;; Check to see whether we're hitting a redo record, and if
2326 ;; so, ask the user whether she wants to skip the redo/undo pair.
2327 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2328 (or (eq (selected-window) (minibuffer-window))
2329 (setq message (format "%s%s!"
2330 (if (or undo-no-redo (not equiv))
2332 (if undo-in-region " in region" ""))))
2333 (when (and (consp equiv) undo-no-redo)
2334 ;; The equiv entry might point to another redo record if we have done
2335 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2336 (while (let ((next (gethash equiv undo-equiv-table)))
2337 (if next (setq equiv next))))
2338 (setq pending-undo-list equiv)))
2341 (prefix-numeric-value arg)
2343 ;; Record the fact that the just-generated undo records come from an
2344 ;; undo operation--that is, they are redo records.
2345 ;; In the ordinary case (not within a region), map the redo
2346 ;; record to the following undos.
2347 ;; I don't know how to do that in the undo-in-region case.
2348 (let ((list buffer-undo-list))
2349 ;; Strip any leading undo boundaries there might be, like we do
2350 ;; above when checking.
2351 (while (eq (car list) nil)
2352 (setq list (cdr list)))
2354 ;; Prevent identity mapping. This can happen if
2355 ;; consecutive nils are erroneously in undo list.
2356 (if (or undo-in-region (eq list pending-undo-list))
2360 ;; Don't specify a position in the undo record for the undo command.
2361 ;; Instead, undoing this should move point to where the change is.
2362 (let ((tail buffer-undo-list)
2365 (when (integerp (car tail))
2366 (let ((pos (car tail)))
2368 (setcdr prev (cdr tail))
2369 (setq buffer-undo-list (cdr tail)))
2370 (setq tail (cdr tail))
2372 (if (eq pos (car tail))
2374 (setcdr prev (cdr tail))
2375 (setq buffer-undo-list (cdr tail)))
2377 (setq tail (cdr tail)))
2379 (setq prev tail tail (cdr tail))))
2380 ;; Record what the current undo list says,
2381 ;; so the next command can tell if the buffer was modified in between.
2382 (and modified (not (buffer-modified-p))
2383 (with-current-buffer base-buffer
2384 (delete-auto-save-file-if-necessary recent-save)))
2385 ;; Display a message announcing success.
2387 (message "%s" message))))
2389 (defun buffer-disable-undo (&optional buffer)
2390 "Make BUFFER stop keeping undo information.
2391 No argument or nil as argument means do this for the current buffer."
2393 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2394 (setq buffer-undo-list t)))
2396 (defun undo-only (&optional arg)
2397 "Undo some previous changes.
2398 Repeat this command to undo more changes.
2399 A numeric ARG serves as a repeat count.
2400 Contrary to `undo', this will not redo a previous undo."
2402 (let ((undo-no-redo t)) (undo arg)))
2404 (defvar undo-in-progress nil
2405 "Non-nil while performing an undo.
2406 Some change-hooks test this variable to do something different.")
2408 (defun undo-more (n)
2409 "Undo back N undo-boundaries beyond what was already undone recently.
2410 Call `undo-start' to get ready to undo recent changes,
2411 then call `undo-more' one or more times to undo them."
2412 (or (listp pending-undo-list)
2413 (user-error (concat "No further undo information"
2414 (and undo-in-region " for region"))))
2415 (let ((undo-in-progress t))
2416 ;; Note: The following, while pulling elements off
2417 ;; `pending-undo-list' will call primitive change functions which
2418 ;; will push more elements onto `buffer-undo-list'.
2419 (setq pending-undo-list (primitive-undo n pending-undo-list))
2420 (if (null pending-undo-list)
2421 (setq pending-undo-list t))))
2423 (defun primitive-undo (n list)
2424 "Undo N records from the front of the list LIST.
2425 Return what remains of the list."
2427 ;; This is a good feature, but would make undo-start
2428 ;; unable to do what is expected.
2429 ;;(when (null (car (list)))
2430 ;; ;; If the head of the list is a boundary, it is the boundary
2431 ;; ;; preceding this command. Get rid of it and don't count it.
2432 ;; (setq list (cdr list))))
2435 ;; In a writable buffer, enable undoing read-only text that is
2436 ;; so because of text properties.
2437 (inhibit-read-only t)
2438 ;; Don't let `intangible' properties interfere with undo.
2439 (inhibit-point-motion-hooks t)
2440 ;; We use oldlist only to check for EQ. ++kfs
2441 (oldlist buffer-undo-list)
2445 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2446 ;; Handle an integer by setting point to that value.
2448 ((pred integerp) (goto-char next))
2449 ;; Element (t . TIME) records previous modtime.
2450 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2451 ;; UNKNOWN_MODTIME_NSECS.
2453 ;; If this records an obsolete save
2454 ;; (not matching the actual disk file)
2455 ;; then don't mark unmodified.
2456 (when (or (equal time (visited-file-modtime))
2458 (equal (list (car time) (cdr time))
2459 (visited-file-modtime))))
2460 (when (fboundp 'unlock-buffer)
2462 (set-buffer-modified-p nil)))
2463 ;; Element (nil PROP VAL BEG . END) is property change.
2464 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2465 (when (or (> (point-min) beg) (< (point-max) end))
2466 (error "Changes to be undone are outside visible portion of buffer"))
2467 (put-text-property beg end prop val))
2468 ;; Element (BEG . END) means range was inserted.
2469 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2470 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2471 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2472 (when (or (> (point-min) beg) (< (point-max) end))
2473 (error "Changes to be undone are outside visible portion of buffer"))
2474 ;; Set point first thing, so that undoing this undo
2475 ;; does not send point back to where it is now.
2477 (delete-region beg end))
2478 ;; Element (apply FUN . ARGS) means call FUN to undo.
2479 (`(apply . ,fun-args)
2480 (let ((currbuff (current-buffer)))
2481 (if (integerp (car fun-args))
2482 ;; Long format: (apply DELTA START END FUN . ARGS).
2483 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2484 (start-mark (copy-marker start nil))
2485 (end-mark (copy-marker end t)))
2486 (when (or (> (point-min) start) (< (point-max) end))
2487 (error "Changes to be undone are outside visible portion of buffer"))
2488 (apply fun args) ;; Use `save-current-buffer'?
2489 ;; Check that the function did what the entry
2490 ;; said it would do.
2491 (unless (and (= start start-mark)
2492 (= (+ delta end) end-mark))
2493 (error "Changes to be undone by function different than announced"))
2494 (set-marker start-mark nil)
2495 (set-marker end-mark nil))
2497 (unless (eq currbuff (current-buffer))
2498 (error "Undo function switched buffer"))
2499 (setq did-apply t)))
2500 ;; Element (STRING . POS) means STRING was deleted.
2501 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2502 (when (let ((apos (abs pos)))
2503 (or (< apos (point-min)) (> apos (point-max))))
2504 (error "Changes to be undone are outside visible portion of buffer"))
2505 (let (valid-marker-adjustments)
2506 ;; Check that marker adjustments which were recorded
2507 ;; with the (STRING . POS) record are still valid, ie
2508 ;; the markers haven't moved. We check their validity
2509 ;; before reinserting the string so as we don't need to
2510 ;; mind marker insertion-type.
2511 (while (and (markerp (car-safe (car list)))
2512 (integerp (cdr-safe (car list))))
2513 (let* ((marker-adj (pop list))
2514 (m (car marker-adj)))
2515 (and (eq (marker-buffer m) (current-buffer))
2517 (push marker-adj valid-marker-adjustments))))
2518 ;; Insert string and adjust point
2526 ;; Adjust the valid marker adjustments
2527 (dolist (adj valid-marker-adjustments)
2528 (set-marker (car adj)
2529 (- (car adj) (cdr adj))))))
2530 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2531 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2532 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2534 ;; Even though these elements are not expected in the undo
2535 ;; list, adjust them to be conservative for the 24.4
2536 ;; release. (Bug#16818)
2537 (when (marker-buffer marker)
2540 (marker-buffer marker))))
2541 (_ (error "Unrecognized entry in undo list %S" next))))
2542 (setq arg (1- arg)))
2543 ;; Make sure an apply entry produces at least one undo entry,
2544 ;; so the test in `undo' for continuing an undo series
2547 (eq oldlist buffer-undo-list))
2548 (setq buffer-undo-list
2549 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2552 ;; Deep copy of a list
2553 (defun undo-copy-list (list)
2554 "Make a copy of undo list LIST."
2555 (mapcar 'undo-copy-list-1 list))
2557 (defun undo-copy-list-1 (elt)
2559 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2562 (defun undo-start (&optional beg end)
2563 "Set `pending-undo-list' to the front of the undo list.
2564 The next call to `undo-more' will undo the most recently made change.
2565 If BEG and END are specified, then only undo elements
2566 that apply to text between BEG and END are used; other undo elements
2567 are ignored. If BEG and END are nil, all undo elements are used."
2568 (if (eq buffer-undo-list t)
2569 (user-error "No undo information in this buffer"))
2570 (setq pending-undo-list
2571 (if (and beg end (not (= beg end)))
2572 (undo-make-selective-list (min beg end) (max beg end))
2575 ;; The positions given in elements of the undo list are the positions
2576 ;; as of the time that element was recorded to undo history. In
2577 ;; general, subsequent buffer edits render those positions invalid in
2578 ;; the current buffer, unless adjusted according to the intervening
2581 ;; Undo in region is a use case that requires adjustments to undo
2582 ;; elements. It must adjust positions of elements in the region based
2583 ;; on newer elements not in the region so as they may be correctly
2584 ;; applied in the current buffer. undo-make-selective-list
2585 ;; accomplishes this with its undo-deltas list of adjustments. An
2586 ;; example undo history from oldest to newest:
2589 ;; 123456789 buffer-undo-list undo-deltas
2590 ;; --------- ---------------- -----------
2591 ;; aaa (1 . 4) (1 . -3)
2592 ;; aaba (3 . 4) N/A (in region)
2593 ;; ccaaba (1 . 3) (1 . -2)
2594 ;; ccaabaddd (7 . 10) (7 . -3)
2595 ;; ccaabdd ("ad" . 6) (6 . 2)
2596 ;; ccaabaddd (6 . 8) (6 . -2)
2597 ;; | |<-- region: "caab", from 2 to 6
2599 ;; When the user starts a run of undos in region,
2600 ;; undo-make-selective-list is called to create the full list of in
2601 ;; region elements. Each element is adjusted forward chronologically
2602 ;; through undo-deltas to determine if it is in the region.
2604 ;; In the above example, the insertion of "b" is (3 . 4) in the
2605 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2606 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2607 ;; . 6) is assessed as in the region and placed in the selective list.
2608 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2609 ;; due to the selected element. The "b" insertion is the only element
2610 ;; fully in the region, so in this example undo-make-selective-list
2611 ;; returns (nil (5 . 6)).
2613 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2614 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2615 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2616 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2617 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2619 ;; More interesting is how to adjust the "ddd" insertion due to the
2620 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2621 ;; If the reinsertion was a manual retyping of "ad", then the total
2622 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2623 ;; the reinsertion was due to undo, one might expect the first "d"
2624 ;; character would again be a part of the "ddd" text, meaning its
2625 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2627 ;; undo-make-selective-list assumes in this situation that "ad" was a
2628 ;; new edit, even if it was inserted because of an undo.
2629 ;; Consequently, if the user undos in region "8 to 10" of the
2630 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2631 ;; "ccaabad", as though the first "d" became detached from the
2632 ;; original "ddd" insertion. This quirk is a FIXME.
2634 (defun undo-make-selective-list (start end)
2635 "Return a list of undo elements for the region START to END.
2636 The elements come from `buffer-undo-list', but we keep only the
2637 elements inside this region, and discard those outside this
2638 region. The elements' positions are adjusted so as the returned
2639 list can be applied to the current buffer."
2640 (let ((ulist buffer-undo-list)
2641 ;; A list of position adjusted undo elements in the region.
2642 (selective-list (list nil))
2643 ;; A list of undo-deltas for out of region undo elements.
2648 (while (gethash ulist undo-equiv-table)
2649 (setq ulist (gethash ulist undo-equiv-table))))
2650 (setq undo-elt (car ulist))
2653 ;; Don't put two nils together in the list
2654 (when (car selective-list)
2655 (push nil selective-list)))
2656 ((and (consp undo-elt) (eq (car undo-elt) t))
2657 ;; This is a "was unmodified" element. Keep it
2658 ;; if we have kept everything thus far.
2659 (when (not undo-deltas)
2660 (push undo-elt selective-list)))
2661 ;; Skip over marker adjustments, instead relying
2662 ;; on finding them after (TEXT . POS) elements
2663 ((markerp (car-safe undo-elt))
2666 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2668 (if (undo-elt-in-region adjusted-undo-elt start end)
2670 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2671 (push adjusted-undo-elt selective-list)
2672 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2673 ;; kept. primitive-undo may discard them later.
2674 (when (and (stringp (car-safe adjusted-undo-elt))
2675 (integerp (cdr-safe adjusted-undo-elt)))
2676 (let ((list-i (cdr ulist)))
2677 (while (markerp (car-safe (car list-i)))
2678 (push (pop list-i) selective-list)))))
2679 (let ((delta (undo-delta undo-elt)))
2680 (when (/= 0 (cdr delta))
2681 (push delta undo-deltas)))))))
2683 (nreverse selective-list)))
2685 (defun undo-elt-in-region (undo-elt start end)
2686 "Determine whether UNDO-ELT falls inside the region START ... END.
2687 If it crosses the edge, we return nil.
2689 Generally this function is not useful for determining
2690 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2691 because markers can be arbitrarily relocated. Instead, pass the
2692 marker adjustment's corresponding (TEXT . POS) element."
2693 (cond ((integerp undo-elt)
2694 (and (>= undo-elt start)
2700 ((stringp (car undo-elt))
2701 ;; (TEXT . POSITION)
2702 (and (>= (abs (cdr undo-elt)) start)
2703 (<= (abs (cdr undo-elt)) end)))
2704 ((and (consp undo-elt) (markerp (car undo-elt)))
2705 ;; (MARKER . ADJUSTMENT)
2706 (<= start (car undo-elt) end))
2707 ((null (car undo-elt))
2708 ;; (nil PROPERTY VALUE BEG . END)
2709 (let ((tail (nthcdr 3 undo-elt)))
2710 (and (>= (car tail) start)
2711 (<= (cdr tail) end))))
2712 ((integerp (car undo-elt))
2714 (and (>= (car undo-elt) start)
2715 (<= (cdr undo-elt) end)))))
2717 (defun undo-elt-crosses-region (undo-elt start end)
2718 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2719 This assumes we have already decided that UNDO-ELT
2720 is not *inside* the region START...END."
2721 (declare (obsolete nil "25.1"))
2722 (cond ((atom undo-elt) nil)
2723 ((null (car undo-elt))
2724 ;; (nil PROPERTY VALUE BEG . END)
2725 (let ((tail (nthcdr 3 undo-elt)))
2726 (and (< (car tail) end)
2727 (> (cdr tail) start))))
2728 ((integerp (car undo-elt))
2730 (and (< (car undo-elt) end)
2731 (> (cdr undo-elt) start)))))
2733 (defun undo-adjust-elt (elt deltas)
2734 "Return adjustment of undo element ELT by the undo DELTAS
2739 (undo-adjust-pos elt deltas))
2741 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2742 (undo-adjust-beg-end beg end deltas))
2743 ;; (TEXT . POSITION)
2744 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2745 (cons text (* (if (< pos 0) -1 1)
2746 (undo-adjust-pos (abs pos) deltas))))
2747 ;; (nil PROPERTY VALUE BEG . END)
2748 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2749 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2750 ;; (apply DELTA START END FUN . ARGS)
2752 ;; All others return same elt
2755 ;; (BEG . END) can adjust to the same positions, commonly when an
2756 ;; insertion was undone and they are out of region, for example:
2759 ;; 123456789 buffer-undo-list undo-deltas
2760 ;; --------- ---------------- -----------
2762 ;; abbaa (2 . 4) (2 . -2)
2763 ;; aaa ("bb" . 2) (2 . 2)
2766 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2767 ;; undo. Further adjustments to such an element should be the same as
2768 ;; for (TEXT . POSITION) elements. The options are:
2770 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2771 ;; analogous to marker insertion-type t.
2773 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2774 ;; marker insertion-type nil.
2776 ;; There was no strong reason to prefer one or the other, except that
2777 ;; the first is more consistent with prior undo in region behavior.
2778 (defun undo-adjust-beg-end (beg end deltas)
2779 "Return cons of adjustments to BEG and END by the undo DELTAS
2781 (let ((adj-beg (undo-adjust-pos beg deltas)))
2782 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2784 (max adj-beg (undo-adjust-pos end deltas t)))))
2786 (defun undo-adjust-pos (pos deltas &optional use-<)
2787 "Return adjustment of POS by the undo DELTAS list, comparing
2788 with < or <= based on USE-<."
2789 (dolist (d deltas pos)
2794 ;; Don't allow pos to become less than the undo-delta
2795 ;; position. This edge case is described in the overview
2797 (max (car d) (- pos (cdr d)))))))
2799 ;; Return the first affected buffer position and the delta for an undo element
2800 ;; delta is defined as the change in subsequent buffer positions if we *did*
2802 (defun undo-delta (undo-elt)
2803 (if (consp undo-elt)
2804 (cond ((stringp (car undo-elt))
2805 ;; (TEXT . POSITION)
2806 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2807 ((integerp (car undo-elt))
2809 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2814 ;;; Default undo-boundary addition
2816 ;; This section adds a new undo-boundary at either after a command is
2817 ;; called or in some cases on a timer called after a change is made in
2819 (defvar-local undo-auto--last-boundary-cause nil
2820 "Describe the cause of the last undo-boundary.
2822 If `explicit', the last boundary was caused by an explicit call to
2823 `undo-boundary', that is one not called by the code in this
2826 If it is equal to `timer', then the last boundary was inserted
2827 by `undo-auto--boundary-timer'.
2829 If it is equal to `command', then the last boundary was inserted
2830 automatically after a command, that is by the code defined in
2833 If it is equal to a list, then the last boundary was inserted by
2834 an amalgamating command. The car of the list is the number of
2835 times an amalgamating command has been called, and the cdr are the
2836 buffers that were changed during the last command.")
2838 (defvar undo-auto-current-boundary-timer nil
2839 "Current timer which will run `undo-auto--boundary-timer' or nil.
2841 If set to non-nil, this will effectively disable the timer.")
2843 (defvar undo-auto--this-command-amalgamating nil
2844 "Non-nil if `this-command' should be amalgamated.
2845 This variable is set to nil by `undo-auto--boundaries' and is set
2846 by `undo-auto-amalgamate'." )
2848 (defun undo-auto--needs-boundary-p ()
2849 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2850 (car-safe buffer-undo-list))
2852 (defun undo-auto--last-boundary-amalgamating-number ()
2853 "Return the number of amalgamating last commands or nil.
2854 Amalgamating commands are, by default, either
2855 `self-insert-command' and `delete-char', but can be any command
2856 that calls `undo-auto-amalgamate'."
2857 (car-safe undo-auto--last-boundary-cause))
2859 (defun undo-auto--ensure-boundary (cause)
2860 "Add an `undo-boundary' to the current buffer if needed.
2861 REASON describes the reason that the boundary is being added; see
2862 `undo-auto--last-boundary' for more information."
2864 (undo-auto--needs-boundary-p))
2865 (let ((last-amalgamating
2866 (undo-auto--last-boundary-amalgamating-number)))
2868 (setq undo-auto--last-boundary-cause
2869 (if (eq 'amalgamate cause)
2871 (if last-amalgamating (1+ last-amalgamating) 0)
2872 undo-auto--undoably-changed-buffers)
2875 (defun undo-auto--boundaries (cause)
2876 "Check recently changed buffers and add a boundary if necessary.
2877 REASON describes the reason that the boundary is being added; see
2878 `undo-last-boundary' for more information."
2879 (dolist (b undo-auto--undoably-changed-buffers)
2880 (when (buffer-live-p b)
2881 (with-current-buffer b
2882 (undo-auto--ensure-boundary cause))))
2883 (setq undo-auto--undoably-changed-buffers nil))
2885 (defun undo-auto--boundary-timer ()
2886 "Timer which will run `undo--auto-boundary-timer'."
2887 (setq undo-auto-current-boundary-timer nil)
2888 (undo-auto--boundaries 'timer))
2890 (defun undo-auto--boundary-ensure-timer ()
2891 "Ensure that the `undo-auto-boundary-timer' is set."
2892 (unless undo-auto-current-boundary-timer
2893 (setq undo-auto-current-boundary-timer
2894 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2896 (defvar undo-auto--undoably-changed-buffers nil
2897 "List of buffers that have changed recently.
2899 This list is maintained by `undo-auto--undoable-change' and
2900 `undo-auto--boundaries' and can be affected by changes to their
2903 See also `undo-auto--buffer-undoably-changed'.")
2905 (defun undo-auto--add-boundary ()
2906 "Add an `undo-boundary' in appropriate buffers."
2907 (undo-auto--boundaries
2908 (let ((amal undo-auto--this-command-amalgamating))
2909 (setq undo-auto--this-command-amalgamating nil)
2914 (defun undo-auto-amalgamate ()
2915 "Amalgamate undo if necessary.
2916 This function can be called before an amalgamating command. It
2917 removes the previous `undo-boundary' if a series of such calls
2918 have been made. By default `self-insert-command' and
2919 `delete-char' are the only amalgamating commands, although this
2920 function could be called by any command wishing to have this
2922 (let ((last-amalgamating-count
2923 (undo-auto--last-boundary-amalgamating-number)))
2924 (setq undo-auto--this-command-amalgamating t)
2926 last-amalgamating-count
2929 (< last-amalgamating-count 20)
2930 (eq this-command last-command))
2931 ;; Amalgamate all buffers that have changed.
2932 (dolist (b (cdr undo-auto--last-boundary-cause))
2933 (when (buffer-live-p b)
2934 (with-current-buffer
2937 ;; The head of `buffer-undo-list' is nil.
2938 ;; `car-safe' doesn't work because
2939 ;; `buffer-undo-list' need not be a list!
2940 (and (listp buffer-undo-list)
2941 (not (car buffer-undo-list)))
2942 (setq buffer-undo-list
2943 (cdr buffer-undo-list))))))
2944 (setq undo-auto--last-boundary-cause 0)))))
2946 (defun undo-auto--undoable-change ()
2947 "Called after every undoable buffer change."
2948 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
2949 (undo-auto--boundary-ensure-timer))
2950 ;; End auto-boundary section
2952 (defcustom undo-ask-before-discard nil
2953 "If non-nil ask about discarding undo info for the current command.
2954 Normally, Emacs discards the undo info for the current command if
2955 it exceeds `undo-outer-limit'. But if you set this option
2956 non-nil, it asks in the echo area whether to discard the info.
2957 If you answer no, there is a slight risk that Emacs might crash, so
2958 only do it if you really want to undo the command.
2960 This option is mainly intended for debugging. You have to be
2961 careful if you use it for other purposes. Garbage collection is
2962 inhibited while the question is asked, meaning that Emacs might
2963 leak memory. So you should make sure that you do not wait
2964 excessively long before answering the question."
2969 (defvar undo-extra-outer-limit nil
2970 "If non-nil, an extra level of size that's ok in an undo item.
2971 We don't ask the user about truncating the undo list until the
2972 current item gets bigger than this amount.
2974 This variable only matters if `undo-ask-before-discard' is non-nil.")
2975 (make-variable-buffer-local 'undo-extra-outer-limit)
2977 ;; When the first undo batch in an undo list is longer than
2978 ;; undo-outer-limit, this function gets called to warn the user that
2979 ;; the undo info for the current command was discarded. Garbage
2980 ;; collection is inhibited around the call, so it had better not do a
2982 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2983 (defun undo-outer-limit-truncate (size)
2984 (if undo-ask-before-discard
2985 (when (or (null undo-extra-outer-limit)
2986 (> size undo-extra-outer-limit))
2987 ;; Don't ask the question again unless it gets even bigger.
2988 ;; This applies, in particular, if the user quits from the question.
2989 ;; Such a quit quits out of GC, but something else will call GC
2990 ;; again momentarily. It will call this function again,
2991 ;; but we don't want to ask the question again.
2992 (setq undo-extra-outer-limit (+ size 50000))
2993 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2994 (yes-or-no-p (format-message
2995 "Buffer `%s' undo info is %d bytes long; discard it? "
2996 (buffer-name) size)))
2997 (progn (setq buffer-undo-list nil)
2998 (setq undo-extra-outer-limit nil)
3001 (display-warning '(undo discard-info)
3004 "Buffer `%s' undo info was %d bytes long.\n"
3006 "The undo info was discarded because it exceeded \
3009 This is normal if you executed a command that made a huge change
3010 to the buffer. In that case, to prevent similar problems in the
3011 future, set `undo-outer-limit' to a value that is large enough to
3012 cover the maximum size of normal changes you expect a single
3013 command to make, but not so large that it might exceed the
3014 maximum memory allotted to Emacs.
3016 If you did not execute any such command, the situation is
3017 probably due to a bug and you should report it.
3019 You can disable the popping up of this buffer by adding the entry
3020 \(undo discard-info) to the user option `warning-suppress-types',
3021 which is defined in the `warnings' library.\n")
3023 (setq buffer-undo-list nil)
3026 (defcustom password-word-equivalents
3027 '("password" "passcode" "passphrase" "pass phrase"
3028 ; These are sorted according to the GNU en_US locale.
3031 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3057 "пароль" ; kk, ru, uk
3072 "List of words equivalent to \"password\".
3073 This is used by Shell mode and other parts of Emacs to recognize
3074 password prompts, including prompts in languages other than
3075 English. Different case choices should not be assumed to be
3076 included; callers should bind `case-fold-search' to t."
3077 :type '(repeat string)
3081 (defvar shell-command-history nil
3082 "History list for some commands that read shell commands.
3084 Maximum length of the history list is determined by the value
3085 of `history-length', which see.")
3087 (defvar shell-command-switch (purecopy "-c")
3088 "Switch used to have the shell execute its command line argument.")
3090 (defvar shell-command-default-error-buffer nil
3091 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3092 This buffer is used when `shell-command' or `shell-command-on-region'
3093 is run interactively. A value of nil means that output to stderr and
3094 stdout will be intermixed in the output stream.")
3096 (declare-function mailcap-file-default-commands "mailcap" (files))
3097 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3099 (defun minibuffer-default-add-shell-commands ()
3100 "Return a list of all commands associated with the current file.
3101 This function is used to add all related commands retrieved by `mailcap'
3102 to the end of the list of defaults just after the default value."
3104 (let* ((filename (if (listp minibuffer-default)
3105 (car minibuffer-default)
3106 minibuffer-default))
3107 (commands (and filename (require 'mailcap nil t)
3108 (mailcap-file-default-commands (list filename)))))
3109 (setq commands (mapcar (lambda (command)
3110 (concat command " " filename))
3112 (if (listp minibuffer-default)
3113 (append minibuffer-default commands)
3114 (cons minibuffer-default commands))))
3116 (declare-function shell-completion-vars "shell" ())
3118 (defvar minibuffer-local-shell-command-map
3119 (let ((map (make-sparse-keymap)))
3120 (set-keymap-parent map minibuffer-local-map)
3121 (define-key map "\t" 'completion-at-point)
3123 "Keymap used for completing shell commands in minibuffer.")
3125 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3126 "Read a shell command from the minibuffer.
3127 The arguments are the same as the ones of `read-from-minibuffer',
3128 except READ and KEYMAP are missing and HIST defaults
3129 to `shell-command-history'."
3131 (minibuffer-with-setup-hook
3133 (shell-completion-vars)
3134 (set (make-local-variable 'minibuffer-default-add-function)
3135 'minibuffer-default-add-shell-commands))
3136 (apply 'read-from-minibuffer prompt initial-contents
3137 minibuffer-local-shell-command-map
3139 (or hist 'shell-command-history)
3142 (defcustom async-shell-command-buffer 'confirm-new-buffer
3143 "What to do when the output buffer is used by another shell command.
3144 This option specifies how to resolve the conflict where a new command
3145 wants to direct its output to the buffer `*Async Shell Command*',
3146 but this buffer is already taken by another running shell command.
3148 The value `confirm-kill-process' is used to ask for confirmation before
3149 killing the already running process and running a new process
3150 in the same buffer, `confirm-new-buffer' for confirmation before running
3151 the command in a new buffer with a name other than the default buffer name,
3152 `new-buffer' for doing the same without confirmation,
3153 `confirm-rename-buffer' for confirmation before renaming the existing
3154 output buffer and running a new command in the default buffer,
3155 `rename-buffer' for doing the same without confirmation."
3156 :type '(choice (const :tag "Confirm killing of running command"
3157 confirm-kill-process)
3158 (const :tag "Confirm creation of a new buffer"
3160 (const :tag "Create a new buffer"
3162 (const :tag "Confirm renaming of existing buffer"
3163 confirm-rename-buffer)
3164 (const :tag "Rename the existing buffer"
3169 (defun async-shell-command (command &optional output-buffer error-buffer)
3170 "Execute string COMMAND asynchronously in background.
3172 Like `shell-command', but adds `&' at the end of COMMAND
3173 to execute it asynchronously.
3175 The output appears in the buffer `*Async Shell Command*'.
3176 That buffer is in shell mode.
3178 You can configure `async-shell-command-buffer' to specify what to do in
3179 case when `*Async Shell Command*' buffer is already taken by another
3180 running shell command. To run COMMAND without displaying the output
3181 in a window you can configure `display-buffer-alist' to use the action
3182 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3184 In Elisp, you will often be better served by calling `start-process'
3185 directly, since it offers more control and does not impose the use of a
3186 shell (with its need to quote arguments)."
3189 (read-shell-command "Async shell command: " nil nil
3193 ((eq major-mode 'dired-mode)
3194 (dired-get-filename nil t)))))
3195 (and filename (file-relative-name filename))))
3197 shell-command-default-error-buffer))
3198 (unless (string-match "&[ \t]*\\'" command)
3199 (setq command (concat command " &")))
3200 (shell-command command output-buffer error-buffer))
3202 (defun shell-command (command &optional output-buffer error-buffer)
3203 "Execute string COMMAND in inferior shell; display output, if any.
3204 With prefix argument, insert the COMMAND's output at point.
3206 Interactively, prompt for COMMAND in the minibuffer.
3208 If COMMAND ends in `&', execute it asynchronously.
3209 The output appears in the buffer `*Async Shell Command*'.
3210 That buffer is in shell mode. You can also use
3211 `async-shell-command' that automatically adds `&'.
3213 Otherwise, COMMAND is executed synchronously. The output appears in
3214 the buffer `*Shell Command Output*'. If the output is short enough to
3215 display in the echo area (which is determined by the variables
3216 `resize-mini-windows' and `max-mini-window-height'), it is shown
3217 there, but it is nonetheless available in buffer `*Shell Command
3218 Output*' even though that buffer is not automatically displayed.
3220 To specify a coding system for converting non-ASCII characters
3221 in the shell command output, use \\[universal-coding-system-argument] \
3222 before this command.
3224 Noninteractive callers can specify coding systems by binding
3225 `coding-system-for-read' and `coding-system-for-write'.
3227 The optional second argument OUTPUT-BUFFER, if non-nil,
3228 says to put the output in some other buffer.
3229 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
3230 If OUTPUT-BUFFER is not a buffer and not nil,
3231 insert output in current buffer. (This cannot be done asynchronously.)
3232 In either case, the buffer is first erased, and the output is
3233 inserted after point (leaving mark after it).
3235 If the command terminates without error, but generates output,
3236 and you did not specify \"insert it in the current buffer\",
3237 the output can be displayed in the echo area or in its buffer.
3238 If the output is short enough to display in the echo area
3239 \(determined by the variable `max-mini-window-height' if
3240 `resize-mini-windows' is non-nil), it is shown there.
3241 Otherwise,the buffer containing the output is displayed.
3243 If there is output and an error, and you did not specify \"insert it
3244 in the current buffer\", a message about the error goes at the end
3247 If there is no output, or if output is inserted in the current buffer,
3248 then `*Shell Command Output*' is deleted.
3250 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3251 or buffer name to which to direct the command's standard error output.
3252 If it is nil, error output is mingled with regular output.
3253 In an interactive call, the variable `shell-command-default-error-buffer'
3254 specifies the value of ERROR-BUFFER.
3256 In Elisp, you will often be better served by calling `call-process' or
3257 `start-process' directly, since it offers more control and does not impose
3258 the use of a shell (with its need to quote arguments)."
3262 (read-shell-command "Shell command: " nil nil
3266 ((eq major-mode 'dired-mode)
3267 (dired-get-filename nil t)))))
3268 (and filename (file-relative-name filename))))
3270 shell-command-default-error-buffer))
3271 ;; Look for a handler in case default-directory is a remote file name.
3273 (find-file-name-handler (directory-file-name default-directory)
3276 (funcall handler 'shell-command command output-buffer error-buffer)
3277 (if (and output-buffer
3278 (not (or (bufferp output-buffer) (stringp output-buffer))))
3279 ;; Output goes in current buffer.
3283 (expand-file-name "scor"
3284 (or small-temporary-file-directory
3285 temporary-file-directory)))
3287 (barf-if-buffer-read-only)
3289 ;; We do not use -f for csh; we will not support broken use of
3290 ;; .cshrcs. Even the BSD csh manual says to use
3291 ;; "if ($?prompt) exit" before things which are not useful
3292 ;; non-interactively. Besides, if someone wants their other
3293 ;; aliases for shell commands then they can still have them.
3294 (call-process shell-file-name nil
3298 nil shell-command-switch command)
3299 (when (and error-file (file-exists-p error-file))
3300 (if (< 0 (nth 7 (file-attributes error-file)))
3301 (with-current-buffer (get-buffer-create error-buffer)
3302 (let ((pos-from-end (- (point-max) (point))))
3305 ;; Do no formatting while reading error file,
3306 ;; because that can run a shell command, and we
3307 ;; don't want that to cause an infinite recursion.
3308 (format-insert-file error-file nil)
3309 ;; Put point after the inserted errors.
3310 (goto-char (- (point-max) pos-from-end)))
3311 (display-buffer (current-buffer))))
3312 (delete-file error-file))
3313 ;; This is like exchange-point-and-mark, but doesn't
3314 ;; activate the mark. It is cleaner to avoid activation,
3315 ;; even though the command loop would deactivate the mark
3316 ;; because we inserted text.
3317 (goto-char (prog1 (mark t)
3318 (set-marker (mark-marker) (point)
3319 (current-buffer)))))
3320 ;; Output goes in a separate buffer.
3321 ;; Preserve the match data in case called from a program.
3323 (if (string-match "[ \t]*&[ \t]*\\'" command)
3324 ;; Command ending with ampersand means asynchronous.
3325 (let ((buffer (get-buffer-create
3326 (or output-buffer "*Async Shell Command*")))
3327 (directory default-directory)
3329 ;; Remove the ampersand.
3330 (setq command (substring command 0 (match-beginning 0)))
3331 ;; Ask the user what to do with already running process.
3332 (setq proc (get-buffer-process buffer))
3335 ((eq async-shell-command-buffer 'confirm-kill-process)
3336 ;; If will kill a process, query first.
3337 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3339 (error "Shell command in progress")))
3340 ((eq async-shell-command-buffer 'confirm-new-buffer)
3341 ;; If will create a new buffer, query first.
3342 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3343 (setq buffer (generate-new-buffer
3344 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3345 output-buffer "*Async Shell Command*")))
3346 (error "Shell command in progress")))
3347 ((eq async-shell-command-buffer 'new-buffer)
3348 ;; It will create a new buffer.
3349 (setq buffer (generate-new-buffer
3350 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3351 output-buffer "*Async Shell Command*"))))
3352 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3353 ;; If will rename the buffer, query first.
3354 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3356 (with-current-buffer buffer
3358 (setq buffer (get-buffer-create
3359 (or output-buffer "*Async Shell Command*"))))
3360 (error "Shell command in progress")))
3361 ((eq async-shell-command-buffer 'rename-buffer)
3362 ;; It will rename the buffer.
3363 (with-current-buffer buffer
3365 (setq buffer (get-buffer-create
3366 (or output-buffer "*Async Shell Command*"))))))
3367 (with-current-buffer buffer
3368 (setq buffer-read-only nil)
3369 ;; Setting buffer-read-only to nil doesn't suffice
3370 ;; if some text has a non-nil read-only property,
3371 ;; which comint sometimes adds for prompts.
3372 (let ((inhibit-read-only t))
3374 (display-buffer buffer '(nil (allow-no-window . t)))
3375 (setq default-directory directory)
3376 (setq proc (start-process "Shell" buffer shell-file-name
3377 shell-command-switch command))
3378 (setq mode-line-process '(":%s"))
3379 (require 'shell) (shell-mode)
3380 (set-process-sentinel proc 'shell-command-sentinel)
3381 ;; Use the comint filter for proper handling of carriage motion
3382 ;; (see `comint-inhibit-carriage-motion'),.
3383 (set-process-filter proc 'comint-output-filter)
3385 ;; Otherwise, command is executed synchronously.
3386 (shell-command-on-region (point) (point) command
3387 output-buffer nil error-buffer)))))))
3389 (defun display-message-or-buffer (message &optional buffer-name action frame)
3390 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3391 MESSAGE may be either a string or a buffer.
3393 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3394 for maximum height of the echo area, as defined by `max-mini-window-height'
3395 if `resize-mini-windows' is non-nil.
3397 Returns either the string shown in the echo area, or when a pop-up
3398 buffer is used, the window used to display it.
3400 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3401 name of the buffer used to display it in the case where a pop-up buffer
3402 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3403 string and it is displayed in the echo area, it is not specified whether
3404 the contents are inserted into the buffer anyway.
3406 Optional arguments ACTION and FRAME are as for `display-buffer',
3407 and are only used if a pop-up buffer is displayed."
3408 (cond ((and (stringp message) (not (string-match "\n" message)))
3409 ;; Trivial case where we can use the echo area
3410 (message "%s" message))
3411 ((and (stringp message)
3412 (= (string-match "\n" message) (1- (length message))))
3413 ;; Trivial case where we can just remove single trailing newline
3414 (message "%s" (substring message 0 (1- (length message)))))
3417 (with-current-buffer
3418 (if (bufferp message)
3420 (get-buffer-create (or buffer-name "*Message*")))
3422 (unless (bufferp message)
3427 (if (= (buffer-size) 0)
3429 (count-screen-lines nil nil nil (minibuffer-window)))))
3431 ((and (or (<= lines 1)
3433 (if resize-mini-windows
3434 (cond ((floatp max-mini-window-height)
3436 max-mini-window-height))
3437 ((integerp max-mini-window-height)
3438 max-mini-window-height)
3442 ;; Don't use the echo area if the output buffer is
3443 ;; already displayed in the selected frame.
3444 (not (get-buffer-window (current-buffer))))
3446 (goto-char (point-max))
3449 (message "%s" (buffer-substring (point-min) (point))))
3452 (goto-char (point-min))
3453 (display-buffer (current-buffer) action frame))))))))
3456 ;; We have a sentinel to prevent insertion of a termination message
3457 ;; in the buffer itself.
3458 (defun shell-command-sentinel (process signal)
3459 (if (memq (process-status process) '(exit signal))
3461 (car (cdr (cdr (process-command process))))
3462 (substring signal 0 -1))))
3464 (defun shell-command-on-region (start end command
3465 &optional output-buffer replace
3466 error-buffer display-error-buffer
3467 region-noncontiguous-p)
3468 "Execute string COMMAND in inferior shell with region as input.
3469 Normally display output (if any) in temp buffer `*Shell Command Output*';
3470 Prefix arg means replace the region with it. Return the exit code of
3473 To specify a coding system for converting non-ASCII characters
3474 in the input and output to the shell command, use \\[universal-coding-system-argument]
3475 before this command. By default, the input (from the current buffer)
3476 is encoded using coding-system specified by `process-coding-system-alist',
3477 falling back to `default-process-coding-system' if no match for COMMAND
3478 is found in `process-coding-system-alist'.
3480 Noninteractive callers can specify coding systems by binding
3481 `coding-system-for-read' and `coding-system-for-write'.
3483 If the command generates output, the output may be displayed
3484 in the echo area or in a buffer.
3485 If the output is short enough to display in the echo area
3486 \(determined by the variable `max-mini-window-height' if
3487 `resize-mini-windows' is non-nil), it is shown there.
3488 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3489 The output is available in that buffer in both cases.
3491 If there is output and an error, a message about the error
3492 appears at the end of the output. If there is no output, or if
3493 output is inserted in the current buffer, the buffer `*Shell
3494 Command Output*' is deleted.
3496 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3497 command's output. If the value is a buffer or buffer name,
3498 put the output there. If the value is nil, use the buffer
3499 `*Shell Command Output*'. Any other value, excluding nil,
3500 means to insert the output in the current buffer. In either case,
3501 the output is inserted after point (leaving mark after it).
3503 Optional fifth arg REPLACE, if non-nil, means to insert the
3504 output in place of text from START to END, putting point and mark
3507 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3508 or buffer name to which to direct the command's standard error
3509 output. If nil, error output is mingled with regular output.
3510 When called interactively, `shell-command-default-error-buffer'
3511 is used for ERROR-BUFFER.
3513 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3514 display the error buffer if there were any errors. When called
3515 interactively, this is t."
3516 (interactive (let (string)
3518 (user-error "The mark is not set now, so there is no region"))
3519 ;; Do this before calling region-beginning
3520 ;; and region-end, in case subprocess output
3521 ;; relocates them while we are in the minibuffer.
3522 (setq string (read-shell-command "Shell command on region: "))
3523 ;; call-interactively recognizes region-beginning and
3524 ;; region-end specially, leaving them in the history.
3525 (list (region-beginning) (region-end)
3529 shell-command-default-error-buffer
3531 (region-noncontiguous-p))))
3535 (expand-file-name "scor"
3536 (or small-temporary-file-directory
3537 temporary-file-directory)))
3540 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3541 (if region-noncontiguous-p
3542 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3546 (call-process-region (point-min) (point-max)
3548 nil shell-command-switch
3550 (setq output (split-string (buffer-string) "\n")))
3552 (funcall region-insert-function output))
3555 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3556 ;; Replace specified region with output from command.
3557 (let ((swap (and replace (< start end))))
3558 ;; Don't muck with mark unless REPLACE says we should.
3560 (and replace (push-mark (point) 'nomsg))
3562 (call-process-region start end shell-file-name replace
3566 nil shell-command-switch command))
3567 ;; It is rude to delete a buffer which the command is not using.
3568 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3569 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3570 ;; (kill-buffer shell-buffer)))
3571 ;; Don't muck with mark unless REPLACE says we should.
3572 (and replace swap (exchange-point-and-mark)))
3573 ;; No prefix argument: put the output in a temp buffer,
3574 ;; replacing its entire contents.
3575 (let ((buffer (get-buffer-create
3576 (or output-buffer "*Shell Command Output*"))))
3578 (if (eq buffer (current-buffer))
3579 ;; If the input is the same buffer as the output,
3580 ;; delete everything but the specified region,
3581 ;; then replace that region with the output.
3582 (progn (setq buffer-read-only nil)
3583 (delete-region (max start end) (point-max))
3584 (delete-region (point-min) (min start end))
3586 (call-process-region (point-min) (point-max)
3591 nil shell-command-switch
3593 ;; Clear the output buffer, then run the command with
3595 (let ((directory default-directory))
3596 (with-current-buffer buffer
3597 (setq buffer-read-only nil)
3598 (if (not output-buffer)
3599 (setq default-directory directory))
3602 (call-process-region start end shell-file-name nil
3604 (list buffer error-file)
3606 nil shell-command-switch command)))
3607 ;; Report the output.
3608 (with-current-buffer buffer
3609 (setq mode-line-process
3610 (cond ((null exit-status)
3612 ((stringp exit-status)
3613 (format " - Signal [%s]" exit-status))
3614 ((not (equal 0 exit-status))
3615 (format " - Exit [%d]" exit-status)))))
3616 (if (with-current-buffer buffer (> (point-max) (point-min)))
3617 ;; There's some output, display it
3618 (display-message-or-buffer buffer)
3619 ;; No output; error?
3622 (< 0 (nth 7 (file-attributes error-file))))
3623 (format "some error output%s"
3624 (if shell-command-default-error-buffer
3625 (format " to the \"%s\" buffer"
3626 shell-command-default-error-buffer)
3629 (cond ((null exit-status)
3630 (message "(Shell command failed with error)"))
3631 ((equal 0 exit-status)
3632 (message "(Shell command succeeded with %s)"
3634 ((stringp exit-status)
3635 (message "(Shell command killed by signal %s)"
3638 (message "(Shell command failed with code %d and %s)"
3639 exit-status output))))
3640 ;; Don't kill: there might be useful info in the undo-log.
3641 ;; (kill-buffer buffer)
3644 (when (and error-file (file-exists-p error-file))
3645 (if (< 0 (nth 7 (file-attributes error-file)))
3646 (with-current-buffer (get-buffer-create error-buffer)
3647 (let ((pos-from-end (- (point-max) (point))))
3650 ;; Do no formatting while reading error file,
3651 ;; because that can run a shell command, and we
3652 ;; don't want that to cause an infinite recursion.
3653 (format-insert-file error-file nil)
3654 ;; Put point after the inserted errors.
3655 (goto-char (- (point-max) pos-from-end)))
3656 (and display-error-buffer
3657 (display-buffer (current-buffer)))))
3658 (delete-file error-file))
3661 (defun shell-command-to-string (command)
3662 "Execute shell command COMMAND and return its output as a string."
3663 (with-output-to-string
3664 (with-current-buffer
3666 (process-file shell-file-name nil t nil shell-command-switch command))))
3668 (defun process-file (program &optional infile buffer display &rest args)
3669 "Process files synchronously in a separate process.
3670 Similar to `call-process', but may invoke a file handler based on
3671 `default-directory'. The current working directory of the
3672 subprocess is `default-directory'.
3674 File names in INFILE and BUFFER are handled normally, but file
3675 names in ARGS should be relative to `default-directory', as they
3676 are passed to the process verbatim. (This is a difference to
3677 `call-process' which does not support file handlers for INFILE
3680 Some file handlers might not support all variants, for example
3681 they might behave as if DISPLAY was nil, regardless of the actual
3683 (let ((fh (find-file-name-handler default-directory 'process-file))
3686 (if fh (apply fh 'process-file program infile buffer display args)
3687 (when infile (setq lc (file-local-copy infile)))
3688 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3689 (make-temp-file "emacs")))
3691 (apply 'call-process program
3693 (if stderr-file (list (car buffer) stderr-file) buffer)
3695 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3696 (when stderr-file (delete-file stderr-file))
3697 (when lc (delete-file lc)))))
3699 (defvar process-file-side-effects t
3700 "Whether a call of `process-file' changes remote files.
3702 By default, this variable is always set to t, meaning that a
3703 call of `process-file' could potentially change any file on a
3704 remote host. When set to nil, a file handler could optimize
3705 its behavior with respect to remote file attribute caching.
3707 You should only ever change this variable with a let-binding;
3708 never with `setq'.")
3710 (defun start-file-process (name buffer program &rest program-args)
3711 "Start a program in a subprocess. Return the process object for it.
3713 Similar to `start-process', but may invoke a file handler based on
3714 `default-directory'. See Info node `(elisp)Magic File Names'.
3716 This handler ought to run PROGRAM, perhaps on the local host,
3717 perhaps on a remote host that corresponds to `default-directory'.
3718 In the latter case, the local part of `default-directory' becomes
3719 the working directory of the process.
3721 PROGRAM and PROGRAM-ARGS might be file names. They are not
3722 objects of file handler invocation. File handlers might not
3723 support pty association, if PROGRAM is nil."
3724 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3725 (if fh (apply fh 'start-file-process name buffer program program-args)
3726 (apply 'start-process name buffer program program-args))))
3730 (defvar tabulated-list-format)
3731 (defvar tabulated-list-entries)
3732 (defvar tabulated-list-sort-key)
3733 (declare-function tabulated-list-init-header "tabulated-list" ())
3734 (declare-function tabulated-list-print "tabulated-list"
3735 (&optional remember-pos update))
3737 (defvar process-menu-query-only nil)
3739 (defvar process-menu-mode-map
3740 (let ((map (make-sparse-keymap)))
3741 (define-key map [?d] 'process-menu-delete-process)
3744 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3745 "Major mode for listing the processes called by Emacs."
3746 (setq tabulated-list-format [("Process" 15 t)
3751 (make-local-variable 'process-menu-query-only)
3752 (setq tabulated-list-sort-key (cons "Process" nil))
3753 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3754 (tabulated-list-init-header))
3756 (defun process-menu-delete-process ()
3757 "Kill process at point in a `list-processes' buffer."
3759 (let ((pos (point)))
3760 (delete-process (tabulated-list-get-id))
3762 (goto-char (min pos (point-max)))
3765 (beginning-of-line))))
3767 (defun list-processes--refresh ()
3768 "Recompute the list of processes for the Process List buffer.
3769 Also, delete any process that is exited or signaled."
3770 (setq tabulated-list-entries nil)
3771 (dolist (p (process-list))
3772 (cond ((memq (process-status p) '(exit signal closed))
3774 ((or (not process-menu-query-only)
3775 (process-query-on-exit-flag p))
3776 (let* ((buf (process-buffer p))
3777 (type (process-type p))
3778 (name (process-name p))
3779 (status (symbol-name (process-status p)))
3780 (buf-label (if (buffer-live-p buf)
3781 `(,(buffer-name buf)
3783 help-echo ,(format-message
3788 action process-menu-visit-buffer)
3790 (tty (or (process-tty-name p) "--"))
3792 (if (memq type '(network serial))
3793 (let ((contact (process-contact p t)))
3794 (if (eq type 'network)
3796 (if (plist-get contact :type)
3799 (if (plist-get contact :server)
3800 (format "server on %s"
3802 (plist-get contact :host)
3803 (plist-get contact :local)))
3804 (format "connection to %s"
3805 (plist-get contact :host))))
3806 (format "(serial port %s%s)"
3807 (or (plist-get contact :port) "?")
3808 (let ((speed (plist-get contact :speed)))
3810 (format " at %s b/s" speed)
3812 (mapconcat 'identity (process-command p) " "))))
3813 (push (list p (vector name status buf-label tty cmd))
3814 tabulated-list-entries))))))
3816 (defun process-menu-visit-buffer (button)
3817 (display-buffer (button-get button 'process-buffer)))
3819 (defun list-processes (&optional query-only buffer)
3820 "Display a list of all processes that are Emacs sub-processes.
3821 If optional argument QUERY-ONLY is non-nil, only processes with
3822 the query-on-exit flag set are listed.
3823 Any process listed as exited or signaled is actually eliminated
3824 after the listing is made.
3825 Optional argument BUFFER specifies a buffer to use, instead of
3827 The return value is always nil.
3829 This function lists only processes that were launched by Emacs. To
3830 see other processes running on the system, use `list-system-processes'."
3832 (or (fboundp 'process-list)
3833 (error "Asynchronous subprocesses are not supported on this system"))
3834 (unless (bufferp buffer)
3835 (setq buffer (get-buffer-create "*Process List*")))
3836 (with-current-buffer buffer
3838 (setq process-menu-query-only query-only)
3839 (list-processes--refresh)
3840 (tabulated-list-print))
3841 (display-buffer buffer)
3844 ;;;; Prefix commands
3846 (setq prefix-command--needs-update nil)
3847 (setq prefix-command--last-echo nil)
3849 (defun internal-echo-keystrokes-prefix ()
3850 ;; BEWARE: Called directly from C code.
3851 ;; If the return value is non-nil, it means we are in the middle of
3852 ;; a command with prefix, such as a command invoked with prefix-arg.
3853 (if (not prefix-command--needs-update)
3854 prefix-command--last-echo
3855 (setq prefix-command--last-echo
3857 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3858 (lambda (fun) (push (funcall fun) strs)))
3859 (setq strs (delq nil strs))
3860 (when strs (mapconcat #'identity strs " "))))))
3862 (defvar prefix-command-echo-keystrokes-functions nil
3863 "Abnormal hook which constructs the description of the current prefix state.
3864 Each function is called with no argument, should return a string or nil.")
3866 (defun prefix-command-update ()
3867 "Update state of prefix commands.
3868 Call it whenever you change the \"prefix command state\"."
3869 (setq prefix-command--needs-update t))
3871 (defvar prefix-command-preserve-state-hook nil
3872 "Normal hook run when a command needs to preserve the prefix.")
3874 (defun prefix-command-preserve-state ()
3875 "Pass the current prefix command state to the next command.
3876 Should be called by all prefix commands.
3877 Runs `prefix-command-preserve-state-hook'."
3878 (run-hooks 'prefix-command-preserve-state-hook)
3879 ;; If the current command is a prefix command, we don't want the next (real)
3880 ;; command to have `last-command' set to, say, `universal-argument'.
3881 (setq this-command last-command)
3882 (setq real-this-command real-last-command)
3883 (prefix-command-update))
3885 (defun reset-this-command-lengths ()
3886 (declare (obsolete prefix-command-preserve-state "25.1"))
3889 ;;;;; The main prefix command.
3891 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
3893 (add-hook 'prefix-command-echo-keystrokes-functions
3894 #'universal-argument--description)
3895 (defun universal-argument--description ()
3900 (`(,(and (pred integerp) n))
3902 (while (and (> n 4) (= (mod n 4) 0))
3903 (setq str (concat str " C-u"))
3905 (if (= n 4) str (format " %s" prefix-arg))))
3906 (_ (format " %s" prefix-arg))))))
3908 (add-hook 'prefix-command-preserve-state-hook
3909 #'universal-argument--preserve)
3910 (defun universal-argument--preserve ()
3911 (setq prefix-arg current-prefix-arg))
3913 (defvar universal-argument-map
3914 (let ((map (make-sparse-keymap))
3915 (universal-argument-minus
3916 ;; For backward compatibility, minus with no modifiers is an ordinary
3917 ;; command if digits have already been entered.
3918 `(menu-item "" negative-argument
3919 :filter ,(lambda (cmd)
3920 (if (integerp prefix-arg) nil cmd)))))
3921 (define-key map [switch-frame]
3922 (lambda (e) (interactive "e")
3923 (handle-switch-frame e) (universal-argument--mode)))
3924 (define-key map [?\C-u] 'universal-argument-more)
3925 (define-key map [?-] universal-argument-minus)
3926 (define-key map [?0] 'digit-argument)
3927 (define-key map [?1] 'digit-argument)
3928 (define-key map [?2] 'digit-argument)
3929 (define-key map [?3] 'digit-argument)
3930 (define-key map [?4] 'digit-argument)
3931 (define-key map [?5] 'digit-argument)
3932 (define-key map [?6] 'digit-argument)
3933 (define-key map [?7] 'digit-argument)
3934 (define-key map [?8] 'digit-argument)
3935 (define-key map [?9] 'digit-argument)
3936 (define-key map [kp-0] 'digit-argument)
3937 (define-key map [kp-1] 'digit-argument)
3938 (define-key map [kp-2] 'digit-argument)
3939 (define-key map [kp-3] 'digit-argument)
3940 (define-key map [kp-4] 'digit-argument)
3941 (define-key map [kp-5] 'digit-argument)
3942 (define-key map [kp-6] 'digit-argument)
3943 (define-key map [kp-7] 'digit-argument)
3944 (define-key map [kp-8] 'digit-argument)
3945 (define-key map [kp-9] 'digit-argument)
3946 (define-key map [kp-subtract] universal-argument-minus)
3948 "Keymap used while processing \\[universal-argument].")
3950 (defun universal-argument--mode ()
3951 (prefix-command-update)
3952 (set-transient-map universal-argument-map nil))
3954 (defun universal-argument ()
3955 "Begin a numeric argument for the following command.
3956 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3957 \\[universal-argument] following the digits or minus sign ends the argument.
3958 \\[universal-argument] without digits or minus sign provides 4 as argument.
3959 Repeating \\[universal-argument] without digits or minus sign
3960 multiplies the argument by 4 each time.
3961 For some commands, just \\[universal-argument] by itself serves as a flag
3962 which is different in effect from any particular numeric argument.
3963 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3965 (prefix-command-preserve-state)
3966 (setq prefix-arg (list 4))
3967 (universal-argument--mode))
3969 (defun universal-argument-more (arg)
3970 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3971 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3973 (prefix-command-preserve-state)
3974 (setq prefix-arg (if (consp arg)
3975 (list (* 4 (car arg)))
3979 (when (consp prefix-arg) (universal-argument--mode)))
3981 (defun negative-argument (arg)
3982 "Begin a negative numeric argument for the next command.
3983 \\[universal-argument] following digits or minus sign ends the argument."
3985 (prefix-command-preserve-state)
3986 (setq prefix-arg (cond ((integerp arg) (- arg))
3989 (universal-argument--mode))
3991 (defun digit-argument (arg)
3992 "Part of the numeric argument for the next command.
3993 \\[universal-argument] following digits or minus sign ends the argument."
3995 (prefix-command-preserve-state)
3996 (let* ((char (if (integerp last-command-event)
3998 (get last-command-event 'ascii-character)))
3999 (digit (- (logand char ?\177) ?0)))
4000 (setq prefix-arg (cond ((integerp arg)
4002 (if (< arg 0) (- digit) digit)))
4004 ;; Treat -0 as just -, so that -01 will work.
4005 (if (zerop digit) '- (- digit)))
4008 (universal-argument--mode))
4011 (defvar filter-buffer-substring-functions nil
4012 "This variable is a wrapper hook around `buffer-substring--filter'.")
4013 (make-obsolete-variable 'filter-buffer-substring-functions
4014 'filter-buffer-substring-function "24.4")
4016 (defvar filter-buffer-substring-function #'buffer-substring--filter
4017 "Function to perform the filtering in `filter-buffer-substring'.
4018 The function is called with the same 3 arguments (BEG END DELETE)
4019 that `filter-buffer-substring' received. It should return the
4020 buffer substring between BEG and END, after filtering. If DELETE is
4021 non-nil, it should delete the text between BEG and END from the buffer.")
4023 (defvar buffer-substring-filters nil
4024 "List of filter functions for `buffer-substring--filter'.
4025 Each function must accept a single argument, a string, and return a string.
4026 The buffer substring is passed to the first function in the list,
4027 and the return value of each function is passed to the next.
4028 As a special convention, point is set to the start of the buffer text
4029 being operated on (i.e., the first argument of `buffer-substring--filter')
4030 before these functions are called.")
4031 (make-obsolete-variable 'buffer-substring-filters
4032 'filter-buffer-substring-function "24.1")
4034 (defun filter-buffer-substring (beg end &optional delete)
4035 "Return the buffer substring between BEG and END, after filtering.
4036 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4038 This calls the function that `filter-buffer-substring-function' specifies
4039 \(passing the same three arguments that it received) to do the work,
4040 and returns whatever it does. The default function does no filtering,
4041 unless a hook has been set.
4043 Use `filter-buffer-substring' instead of `buffer-substring',
4044 `buffer-substring-no-properties', or `delete-and-extract-region' when
4045 you want to allow filtering to take place. For example, major or minor
4046 modes can use `filter-buffer-substring-function' to extract characters
4047 that are special to a buffer, and should not be copied into other buffers."
4048 (funcall filter-buffer-substring-function beg end delete))
4050 (defun buffer-substring--filter (beg end &optional delete)
4051 "Default function to use for `filter-buffer-substring-function'.
4052 Its arguments and return value are as specified for `filter-buffer-substring'.
4053 This respects the wrapper hook `filter-buffer-substring-functions',
4054 and the abnormal hook `buffer-substring-filters'.
4055 No filtering is done unless a hook says to."
4056 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
4058 ((or delete buffer-substring-filters)
4061 (let ((string (if delete (delete-and-extract-region beg end)
4062 (buffer-substring beg end))))
4063 (dolist (filter buffer-substring-filters)
4064 (setq string (funcall filter string)))
4067 (buffer-substring beg end)))))
4070 ;;;; Window system cut and paste hooks.
4072 (defvar interprogram-cut-function #'gui-select-text
4073 "Function to call to make a killed region available to other programs.
4074 Most window systems provide a facility for cutting and pasting
4075 text between different programs, such as the clipboard on X and
4076 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4078 This variable holds a function that Emacs calls whenever text is
4079 put in the kill ring, to make the new kill available to other
4080 programs. The function takes one argument, TEXT, which is a
4081 string containing the text which should be made available.")
4083 (defvar interprogram-paste-function #'gui-selection-value
4084 "Function to call to get text cut from other programs.
4085 Most window systems provide a facility for cutting and pasting
4086 text between different programs, such as the clipboard on X and
4087 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4089 This variable holds a function that Emacs calls to obtain text
4090 that other programs have provided for pasting. The function is
4091 called with no arguments. If no other program has provided text
4092 to paste, the function should return nil (in which case the
4093 caller, usually `current-kill', should use the top of the Emacs
4094 kill ring). If another program has provided text to paste, the
4095 function should return that text as a string (in which case the
4096 caller should put this string in the kill ring as the latest
4099 The function may also return a list of strings if the window
4100 system supports multiple selections. The first string will be
4101 used as the pasted text, but the other will be placed in the kill
4102 ring for easy access via `yank-pop'.
4104 Note that the function should return a string only if a program
4105 other than Emacs has provided a string for pasting; if Emacs
4106 provided the most recent string, the function should return nil.
4107 If it is difficult to tell whether Emacs or some other program
4108 provided the current string, it is probably good enough to return
4109 nil if the string is equal (according to `string=') to the last
4110 text Emacs provided.")
4114 ;;;; The kill ring data structure.
4116 (defvar kill-ring nil
4117 "List of killed text sequences.
4118 Since the kill ring is supposed to interact nicely with cut-and-paste
4119 facilities offered by window systems, use of this variable should
4120 interact nicely with `interprogram-cut-function' and
4121 `interprogram-paste-function'. The functions `kill-new',
4122 `kill-append', and `current-kill' are supposed to implement this
4123 interaction; you may want to use them instead of manipulating the kill
4126 (defcustom kill-ring-max 60
4127 "Maximum length of kill ring before oldest elements are thrown away."
4131 (defvar kill-ring-yank-pointer nil
4132 "The tail of the kill ring whose car is the last thing yanked.")
4134 (defcustom save-interprogram-paste-before-kill nil
4135 "Save clipboard strings into kill ring before replacing them.
4136 When one selects something in another program to paste it into Emacs,
4137 but kills something in Emacs before actually pasting it,
4138 this selection is gone unless this variable is non-nil,
4139 in which case the other program's selection is saved in the `kill-ring'
4140 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4145 (defcustom kill-do-not-save-duplicates nil
4146 "Do not add a new string to `kill-ring' if it duplicates the last one.
4147 The comparison is done using `equal-including-properties'."
4152 (defun kill-new (string &optional replace)
4153 "Make STRING the latest kill in the kill ring.
4154 Set `kill-ring-yank-pointer' to point to it.
4155 If `interprogram-cut-function' is non-nil, apply it to STRING.
4156 Optional second argument REPLACE non-nil means that STRING will replace
4157 the front of the kill ring, rather than being added to the list.
4159 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4160 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4163 When the yank handler has a non-nil PARAM element, the original STRING
4164 argument is not used by `insert-for-yank'. However, since Lisp code
4165 may access and use elements from the kill ring directly, the STRING
4166 argument should still be a \"useful\" string for such uses."
4167 (unless (and kill-do-not-save-duplicates
4168 ;; Due to text properties such as 'yank-handler that
4169 ;; can alter the contents to yank, comparison using
4170 ;; `equal' is unsafe.
4171 (equal-including-properties string (car kill-ring)))
4172 (if (fboundp 'menu-bar-update-yank-menu)
4173 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4174 (when save-interprogram-paste-before-kill
4175 (let ((interprogram-paste (and interprogram-paste-function
4176 (funcall interprogram-paste-function))))
4177 (when interprogram-paste
4178 (dolist (s (if (listp interprogram-paste)
4179 (nreverse interprogram-paste)
4180 (list interprogram-paste)))
4181 (unless (and kill-do-not-save-duplicates
4182 (equal-including-properties s (car kill-ring)))
4183 (push s kill-ring))))))
4184 (unless (and kill-do-not-save-duplicates
4185 (equal-including-properties string (car kill-ring)))
4186 (if (and replace kill-ring)
4187 (setcar kill-ring string)
4188 (push string kill-ring)
4189 (if (> (length kill-ring) kill-ring-max)
4190 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4191 (setq kill-ring-yank-pointer kill-ring)
4192 (if interprogram-cut-function
4193 (funcall interprogram-cut-function string)))
4195 ;; It has been argued that this should work similar to `self-insert-command'
4196 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4197 (defcustom kill-append-merge-undo nil
4198 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4203 (defun kill-append (string before-p)
4204 "Append STRING to the end of the latest kill in the kill ring.
4205 If BEFORE-P is non-nil, prepend STRING to the kill.
4206 Also removes the last undo boundary in the current buffer,
4207 depending on `kill-append-merge-undo'.
4208 If `interprogram-cut-function' is set, pass the resulting kill to it."
4209 (let* ((cur (car kill-ring)))
4210 (kill-new (if before-p (concat string cur) (concat cur string))
4211 (or (= (length cur) 0)
4212 (equal nil (get-text-property 0 'yank-handler cur))))
4213 (when (and kill-append-merge-undo (not buffer-read-only))
4214 (let ((prev buffer-undo-list)
4215 (next (cdr buffer-undo-list)))
4216 ;; find the next undo boundary
4220 ;; remove this undo boundary
4222 (setcdr prev (cdr next)))))))
4224 (defcustom yank-pop-change-selection nil
4225 "Whether rotating the kill ring changes the window system selection.
4226 If non-nil, whenever the kill ring is rotated (usually via the
4227 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4228 to copy the new kill to the window system selection."
4233 (defun current-kill (n &optional do-not-move)
4234 "Rotate the yanking point by N places, and then return that kill.
4235 If N is zero and `interprogram-paste-function' is set to a
4236 function that returns a string or a list of strings, and if that
4237 function doesn't return nil, then that string (or list) is added
4238 to the front of the kill ring and the string (or first string in
4239 the list) is returned as the latest kill.
4241 If N is not zero, and if `yank-pop-change-selection' is
4242 non-nil, use `interprogram-cut-function' to transfer the
4243 kill at the new yank point into the window system selection.
4245 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4246 move the yanking point; just return the Nth kill forward."
4248 (let ((interprogram-paste (and (= n 0)
4249 interprogram-paste-function
4250 (funcall interprogram-paste-function))))
4251 (if interprogram-paste
4253 ;; Disable the interprogram cut function when we add the new
4254 ;; text to the kill ring, so Emacs doesn't try to own the
4255 ;; selection, with identical text.
4256 (let ((interprogram-cut-function nil))
4257 (if (listp interprogram-paste)
4258 (mapc 'kill-new (nreverse interprogram-paste))
4259 (kill-new interprogram-paste)))
4261 (or kill-ring (error "Kill ring is empty"))
4262 (let ((ARGth-kill-element
4263 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4267 (setq kill-ring-yank-pointer ARGth-kill-element)
4268 (when (and yank-pop-change-selection
4270 interprogram-cut-function)
4271 (funcall interprogram-cut-function (car ARGth-kill-element))))
4272 (car ARGth-kill-element)))))
4276 ;;;; Commands for manipulating the kill ring.
4278 (defcustom kill-read-only-ok nil
4279 "Non-nil means don't signal an error for killing read-only text."
4283 (defun kill-region (beg end &optional region)
4284 "Kill (\"cut\") text between point and mark.
4285 This deletes the text from the buffer and saves it in the kill ring.
4286 The command \\[yank] can retrieve it from there.
4287 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4289 If you want to append the killed region to the last killed text,
4290 use \\[append-next-kill] before \\[kill-region].
4292 Any command that calls this function is a \"kill command\".
4293 If the previous command was also a kill command,
4294 the text killed this time appends to the text killed last time
4295 to make one entry in the kill ring.
4297 The killed text is filtered by `filter-buffer-substring' before it is
4298 saved in the kill ring, so the actual saved text might be different
4299 from what was killed.
4301 If the buffer is read-only, Emacs will beep and refrain from deleting
4302 the text, but put the text in the kill ring anyway. This means that
4303 you can use the killing commands to copy text from a read-only buffer.
4305 Lisp programs should use this function for killing text.
4306 (To delete text, use `delete-region'.)
4307 Supply two arguments, character positions BEG and END indicating the
4308 stretch of text to be killed. If the optional argument REGION is
4309 non-nil, the function ignores BEG and END, and kills the current
4311 ;; Pass mark first, then point, because the order matters when
4312 ;; calling `kill-append'.
4313 (interactive (list (mark) (point) 'region))
4314 (unless (and beg end)
4315 (user-error "The mark is not set now, so there is no region"))
4317 (let ((string (if region
4318 (funcall region-extract-function 'delete)
4319 (filter-buffer-substring beg end 'delete))))
4320 (when string ;STRING is nil if BEG = END
4321 ;; Add that string to the kill ring, one way or another.
4322 (if (eq last-command 'kill-region)
4323 (kill-append string (< end beg))
4325 (when (or string (eq last-command 'kill-region))
4326 (setq this-command 'kill-region))
4327 (setq deactivate-mark t)
4329 ((buffer-read-only text-read-only)
4330 ;; The code above failed because the buffer, or some of the characters
4331 ;; in the region, are read-only.
4332 ;; We should beep, in case the user just isn't aware of this.
4333 ;; However, there's no harm in putting
4334 ;; the region's text in the kill ring, anyway.
4335 (copy-region-as-kill beg end region)
4336 ;; Set this-command now, so it will be set even if we get an error.
4337 (setq this-command 'kill-region)
4338 ;; This should barf, if appropriate, and give us the correct error.
4339 (if kill-read-only-ok
4340 (progn (message "Read only text copied to kill ring") nil)
4341 ;; Signal an error if the buffer is read-only.
4342 (barf-if-buffer-read-only)
4343 ;; If the buffer isn't read-only, the text is.
4344 (signal 'text-read-only (list (current-buffer)))))))
4346 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4347 ;; to get two copies of the text when the user accidentally types M-w and
4348 ;; then corrects it with the intended C-w.
4349 (defun copy-region-as-kill (beg end &optional region)
4350 "Save the region as if killed, but don't kill it.
4351 In Transient Mark mode, deactivate the mark.
4352 If `interprogram-cut-function' is non-nil, also save the text for a window
4353 system cut and paste.
4355 The copied text is filtered by `filter-buffer-substring' before it is
4356 saved in the kill ring, so the actual saved text might be different
4357 from what was in the buffer.
4359 When called from Lisp, save in the kill ring the stretch of text
4360 between BEG and END, unless the optional argument REGION is
4361 non-nil, in which case ignore BEG and END, and save the current
4364 This command's old key binding has been given to `kill-ring-save'."
4365 ;; Pass mark first, then point, because the order matters when
4366 ;; calling `kill-append'.
4367 (interactive (list (mark) (point)
4368 (prefix-numeric-value current-prefix-arg)))
4369 (let ((str (if region
4370 (funcall region-extract-function nil)
4371 (filter-buffer-substring beg end))))
4372 (if (eq last-command 'kill-region)
4373 (kill-append str (< end beg))
4375 (setq deactivate-mark t)
4378 (defun kill-ring-save (beg end &optional region)
4379 "Save the region as if killed, but don't kill it.
4380 In Transient Mark mode, deactivate the mark.
4381 If `interprogram-cut-function' is non-nil, also save the text for a window
4382 system cut and paste.
4384 If you want to append the killed line to the last killed text,
4385 use \\[append-next-kill] before \\[kill-ring-save].
4387 The copied text is filtered by `filter-buffer-substring' before it is
4388 saved in the kill ring, so the actual saved text might be different
4389 from what was in the buffer.
4391 When called from Lisp, save in the kill ring the stretch of text
4392 between BEG and END, unless the optional argument REGION is
4393 non-nil, in which case ignore BEG and END, and save the current
4396 This command is similar to `copy-region-as-kill', except that it gives
4397 visual feedback indicating the extent of the region being copied."
4398 ;; Pass mark first, then point, because the order matters when
4399 ;; calling `kill-append'.
4400 (interactive (list (mark) (point)
4401 (prefix-numeric-value current-prefix-arg)))
4402 (copy-region-as-kill beg end region)
4403 ;; This use of called-interactively-p is correct because the code it
4404 ;; controls just gives the user visual feedback.
4405 (if (called-interactively-p 'interactive)
4406 (indicate-copied-region)))
4408 (defun indicate-copied-region (&optional message-len)
4409 "Indicate that the region text has been copied interactively.
4410 If the mark is visible in the selected window, blink the cursor
4411 between point and mark if there is currently no active region
4414 If the mark lies outside the selected window, display an
4415 informative message containing a sample of the copied text. The
4416 optional argument MESSAGE-LEN, if non-nil, specifies the length
4417 of this sample text; it defaults to 40."
4418 (let ((mark (mark t))
4420 ;; Inhibit quitting so we can make a quit here
4421 ;; look like a C-g typed as a command.
4423 (if (pos-visible-in-window-p mark (selected-window))
4424 ;; Swap point-and-mark quickly so as to show the region that
4425 ;; was selected. Don't do it if the region is highlighted.
4426 (unless (and (region-active-p)
4427 (face-background 'region))
4428 ;; Swap point and mark.
4429 (set-marker (mark-marker) (point) (current-buffer))
4431 (sit-for blink-matching-delay)
4433 (set-marker (mark-marker) mark (current-buffer))
4435 ;; If user quit, deactivate the mark
4436 ;; as C-g would as a command.
4437 (and quit-flag (region-active-p)
4439 (let ((len (min (abs (- mark point))
4440 (or message-len 40))))
4442 ;; Don't say "killed"; that is misleading.
4443 (message "Saved text until \"%s\""
4444 (buffer-substring-no-properties (- mark len) mark))
4445 (message "Saved text from \"%s\""
4446 (buffer-substring-no-properties mark (+ mark len))))))))
4448 (defun append-next-kill (&optional interactive)
4449 "Cause following command, if it kills, to add to previous kill.
4450 If the next command kills forward from point, the kill is
4451 appended to the previous killed text. If the command kills
4452 backward, the kill is prepended. Kill commands that act on the
4453 region, such as `kill-region', are regarded as killing forward if
4454 point is after mark, and killing backward if point is before
4457 If the next command is not a kill command, `append-next-kill' has
4460 The argument is used for internal purposes; do not supply one."
4462 ;; We don't use (interactive-p), since that breaks kbd macros.
4465 (setq this-command 'kill-region)
4466 (message "If the next command is a kill, it will append"))
4467 (setq last-command 'kill-region)))
4469 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4470 "Character set that matches bidirectional formatting control characters.")
4472 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4473 "Character set that matches any character except bidirectional controls.")
4475 (defun squeeze-bidi-context-1 (from to category replacement)
4476 "A subroutine of `squeeze-bidi-context'.
4477 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4478 (let ((pt (copy-marker from))
4479 (limit (copy-marker to))
4488 ;; L and R categories include embedding and
4489 ;; override controls, but we don't want to
4490 ;; replace them, because that might change
4491 ;; the visual order. Likewise with PDF and
4492 ;; isolate controls.
4493 (+ pt (skip-chars-forward
4494 bidi-directional-non-controls-chars
4496 ;; Replace any run of non-RTL characters by a single LRM.
4497 (if (null (re-search-forward category lim1 t))
4498 ;; No more characters of CATEGORY, we are done.
4500 (replace-match replacement nil t)
4501 (move-marker pt (point)))
4503 ;; Skip directional controls, if any.
4505 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4507 (defun squeeze-bidi-context (from to)
4508 "Replace characters between FROM and TO while keeping bidi context.
4510 This function replaces the region of text with as few characters
4511 as possible, while preserving the effect that region will have on
4512 bidirectional display before and after the region."
4513 (let ((start (set-marker (make-marker)
4514 (if (> from 0) from (+ (point-max) from))))
4515 (end (set-marker (make-marker) to))
4516 ;; This is for when they copy text with read-only text
4518 (inhibit-read-only t))
4519 (if (null (marker-position end))
4520 (setq end (point-max-marker)))
4521 ;; Replace each run of non-RTL characters with a single LRM.
4522 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4523 ;; Replace each run of non-LTR characters with a single RLM. Note
4524 ;; that the \cR category includes both the Arabic Letter (AL) and
4525 ;; R characters; here we ignore the distinction between them,
4526 ;; because that distinction only affects Arabic Number (AN)
4527 ;; characters, which are weak and don't affect the reordering.
4528 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4530 (defun line-substring-with-bidi-context (start end &optional no-properties)
4531 "Return buffer text between START and END with its bidi context.
4533 START and END are assumed to belong to the same physical line
4534 of buffer text. This function prepends and appends to the text
4535 between START and END bidi control characters that preserve the
4536 visual order of that text when it is inserted at some other place."
4537 (if (or (< start (point-min))
4538 (> end (point-max)))
4539 (signal 'args-out-of-range (list (current-buffer) start end)))
4540 (let ((buf (current-buffer))
4541 substr para-dir from to)
4544 (setq para-dir (current-bidi-paragraph-direction))
4545 (setq from (line-beginning-position)
4546 to (line-end-position))
4548 ;; If we don't have any mixed directional characters in the
4549 ;; entire line, we can just copy the substring without adding
4551 (if (or (looking-at-p "\\CR*$")
4552 (looking-at-p "\\CL*$"))
4553 (setq substr (if no-properties
4554 (buffer-substring-no-properties start end)
4555 (buffer-substring start end)))
4559 (insert-buffer-substring-no-properties buf from to)
4560 (insert-buffer-substring buf from to))
4561 (squeeze-bidi-context 1 (1+ (- start from)))
4562 (squeeze-bidi-context (- end to) nil)
4563 (buffer-substring 1 (point-max)))))
4565 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4566 ;; (1) force the string to have the same base embedding
4567 ;; direction as the paragraph direction at the source, no matter
4568 ;; what is the paragraph direction at destination; and (2) avoid
4569 ;; affecting the visual order of the surrounding text at
4570 ;; destination if there are characters of different
4571 ;; directionality there.
4572 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4575 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4576 "Return portion of current buffer between START and END with bidi context.
4578 This function works similar to `buffer-substring', but it prepends and
4579 appends to the text bidi directional control characters necessary to
4580 preserve the visual appearance of the text if it is inserted at another
4581 place. This is useful when the buffer substring includes bidirectional
4582 text and control characters that cause non-trivial reordering on display.
4583 If copied verbatim, such text can have a very different visual appearance,
4584 and can also change the visual appearance of the surrounding text at the
4585 destination of the copy.
4587 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4588 the text properties."
4589 (let (line-end substr)
4590 (if (or (< start (point-min))
4591 (> end (point-max)))
4592 (signal 'args-out-of-range (list (current-buffer) start end)))
4595 (setq line-end (min end (line-end-position)))
4596 (while (< start end)
4600 (line-substring-with-bidi-context start line-end
4603 (setq start (point))
4604 (setq line-end (min end (line-end-position))))
4609 (defcustom yank-handled-properties
4610 '((font-lock-face . yank-handle-font-lock-face-property)
4611 (category . yank-handle-category-property))
4612 "List of special text property handling conditions for yanking.
4613 Each element should have the form (PROP . FUN), where PROP is a
4614 property symbol and FUN is a function. When the `yank' command
4615 inserts text into the buffer, it scans the inserted text for
4616 stretches of text that have `eq' values of the text property
4617 PROP; for each such stretch of text, FUN is called with three
4618 arguments: the property's value in that text, and the start and
4619 end positions of the text.
4621 This is done prior to removing the properties specified by
4622 `yank-excluded-properties'."
4624 :type '(repeat (cons (symbol :tag "property symbol")
4628 ;; This is actually used in subr.el but defcustom does not work there.
4629 (defcustom yank-excluded-properties
4630 '(category field follow-link fontified font-lock-face help-echo
4631 intangible invisible keymap local-map mouse-face read-only
4633 "Text properties to discard when yanking.
4634 The value should be a list of text properties to discard or t,
4635 which means to discard all text properties.
4637 See also `yank-handled-properties'."
4638 :type '(choice (const :tag "All" t) (repeat symbol))
4642 (defvar yank-window-start nil)
4643 (defvar yank-undo-function nil
4644 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4645 Function is called with two parameters, START and END corresponding to
4646 the value of the mark and point; it is guaranteed that START <= END.
4647 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4649 (defun yank-pop (&optional arg)
4650 "Replace just-yanked stretch of killed text with a different stretch.
4651 This command is allowed only immediately after a `yank' or a `yank-pop'.
4652 At such a time, the region contains a stretch of reinserted
4653 previously-killed text. `yank-pop' deletes that text and inserts in its
4654 place a different stretch of killed text.
4656 With no argument, the previous kill is inserted.
4657 With argument N, insert the Nth previous kill.
4658 If N is negative, this is a more recent kill.
4660 The sequence of kills wraps around, so that after the oldest one
4661 comes the newest one.
4663 When this command inserts killed text into the buffer, it honors
4664 `yank-excluded-properties' and `yank-handler' as described in the
4665 doc string for `insert-for-yank-1', which see."
4667 (if (not (eq last-command 'yank))
4668 (user-error "Previous command was not a yank"))
4669 (setq this-command 'yank)
4670 (unless arg (setq arg 1))
4671 (let ((inhibit-read-only t)
4672 (before (< (point) (mark t))))
4674 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4675 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4676 (setq yank-undo-function nil)
4677 (set-marker (mark-marker) (point) (current-buffer))
4678 (insert-for-yank (current-kill arg))
4679 ;; Set the window start back where it was in the yank command,
4681 (set-window-start (selected-window) yank-window-start t)
4683 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4684 ;; It is cleaner to avoid activation, even though the command
4685 ;; loop would deactivate the mark because we inserted text.
4686 (goto-char (prog1 (mark t)
4687 (set-marker (mark-marker) (point) (current-buffer))))))
4690 (defun yank (&optional arg)
4691 "Reinsert (\"paste\") the last stretch of killed text.
4692 More precisely, reinsert the most recent kill, which is the
4693 stretch of killed text most recently killed OR yanked. Put point
4694 at the end, and set mark at the beginning without activating it.
4695 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4696 With argument N, reinsert the Nth most recent kill.
4698 When this command inserts text into the buffer, it honors the
4699 `yank-handled-properties' and `yank-excluded-properties'
4700 variables, and the `yank-handler' text property. See
4701 `insert-for-yank-1' for details.
4703 See also the command `yank-pop' (\\[yank-pop])."
4705 (setq yank-window-start (window-start))
4706 ;; If we don't get all the way thru, make last-command indicate that
4707 ;; for the following command.
4708 (setq this-command t)
4710 (insert-for-yank (current-kill (cond
4715 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4716 ;; It is cleaner to avoid activation, even though the command
4717 ;; loop would deactivate the mark because we inserted text.
4718 (goto-char (prog1 (mark t)
4719 (set-marker (mark-marker) (point) (current-buffer)))))
4720 ;; If we do get all the way thru, make this-command indicate that.
4721 (if (eq this-command t)
4722 (setq this-command 'yank))
4725 (defun rotate-yank-pointer (arg)
4726 "Rotate the yanking point in the kill ring.
4727 With ARG, rotate that many kills forward (or backward, if negative)."
4731 ;; Some kill commands.
4733 ;; Internal subroutine of delete-char
4734 (defun kill-forward-chars (arg)
4735 (if (listp arg) (setq arg (car arg)))
4736 (if (eq arg '-) (setq arg -1))
4737 (kill-region (point) (+ (point) arg)))
4739 ;; Internal subroutine of backward-delete-char
4740 (defun kill-backward-chars (arg)
4741 (if (listp arg) (setq arg (car arg)))
4742 (if (eq arg '-) (setq arg -1))
4743 (kill-region (point) (- (point) arg)))
4745 (defcustom backward-delete-char-untabify-method 'untabify
4746 "The method for untabifying when deleting backward.
4747 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4748 `hungry' -- delete all whitespace, both tabs and spaces;
4749 `all' -- delete all whitespace, including tabs, spaces and newlines;
4750 nil -- just delete one character."
4751 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4755 (defun backward-delete-char-untabify (arg &optional killp)
4756 "Delete characters backward, changing tabs into spaces.
4757 The exact behavior depends on `backward-delete-char-untabify-method'.
4758 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4759 Interactively, ARG is the prefix arg (default 1)
4760 and KILLP is t if a prefix arg was specified."
4761 (interactive "*p\nP")
4762 (when (eq backward-delete-char-untabify-method 'untabify)
4765 (while (and (> count 0) (not (bobp)))
4766 (if (= (preceding-char) ?\t)
4767 (let ((col (current-column)))
4769 (setq col (- col (current-column)))
4770 (insert-char ?\s col)
4773 (setq count (1- count))))))
4774 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4775 ((eq backward-delete-char-untabify-method 'all)
4778 (let* ((oldpt (point))
4779 (wh (- oldpt (save-excursion
4780 (skip-chars-backward skip)
4781 (constrain-to-field nil oldpt)))))
4782 (+ arg (if (zerop wh) 0 (1- wh))))
4784 ;; Avoid warning about delete-backward-char
4785 (with-no-warnings (delete-backward-char n killp))))
4787 (defun zap-to-char (arg char)
4788 "Kill up to and including ARGth occurrence of CHAR.
4789 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4790 Goes backward if ARG is negative; error if CHAR not found."
4791 (interactive (list (prefix-numeric-value current-prefix-arg)
4792 (read-char "Zap to char: " t)))
4793 ;; Avoid "obsolete" warnings for translation-table-for-input.
4795 (if (char-table-p translation-table-for-input)
4796 (setq char (or (aref translation-table-for-input char) char))))
4797 (kill-region (point) (progn
4798 (search-forward (char-to-string char) nil nil arg)
4801 ;; kill-line and its subroutines.
4803 (defcustom kill-whole-line nil
4804 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4808 (defun kill-line (&optional arg)
4809 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4810 With prefix argument ARG, kill that many lines from point.
4811 Negative arguments kill lines backward.
4812 With zero argument, kills the text before point on the current line.
4814 When calling from a program, nil means \"no arg\",
4815 a number counts as a prefix arg.
4817 To kill a whole line, when point is not at the beginning, type \
4818 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4820 If `show-trailing-whitespace' is non-nil, this command will just
4821 kill the rest of the current line, even if there are only
4824 If option `kill-whole-line' is non-nil, then this command kills the whole line
4825 including its terminating newline, when used at the beginning of a line
4826 with no argument. As a consequence, you can always kill a whole line
4827 by typing \\[move-beginning-of-line] \\[kill-line].
4829 If you want to append the killed line to the last killed text,
4830 use \\[append-next-kill] before \\[kill-line].
4832 If the buffer is read-only, Emacs will beep and refrain from deleting
4833 the line, but put the line in the kill ring anyway. This means that
4834 you can use this command to copy text from a read-only buffer.
4835 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4838 (kill-region (point)
4839 ;; It is better to move point to the other end of the kill
4840 ;; before killing. That way, in a read-only buffer, point
4841 ;; moves across the text that is copied to the kill ring.
4842 ;; The choice has no effect on undo now that undo records
4843 ;; the value of point from before the command was run.
4846 (forward-visible-line (prefix-numeric-value arg))
4848 (signal 'end-of-buffer nil))
4851 (end-of-visible-line) (point))))
4852 (if (or (save-excursion
4853 ;; If trailing whitespace is visible,
4854 ;; don't treat it as nothing.
4855 (unless show-trailing-whitespace
4856 (skip-chars-forward " \t" end))
4858 (and kill-whole-line (bolp)))
4859 (forward-visible-line 1)
4863 (defun kill-whole-line (&optional arg)
4865 With prefix ARG, kill that many lines starting from the current line.
4866 If ARG is negative, kill backward. Also kill the preceding newline.
4867 \(This is meant to make \\[repeat] work well with negative arguments.)
4868 If ARG is zero, kill current line but exclude the trailing newline."
4870 (or arg (setq arg 1))
4871 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4872 (signal 'end-of-buffer nil))
4873 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4874 (signal 'beginning-of-buffer nil))
4875 (unless (eq last-command 'kill-region)
4877 (setq last-command 'kill-region))
4879 ;; We need to kill in two steps, because the previous command
4880 ;; could have been a kill command, in which case the text
4881 ;; before point needs to be prepended to the current kill
4882 ;; ring entry and the text after point appended. Also, we
4883 ;; need to use save-excursion to avoid copying the same text
4884 ;; twice to the kill ring in read-only buffers.
4886 (kill-region (point) (progn (forward-visible-line 0) (point))))
4887 (kill-region (point) (progn (end-of-visible-line) (point))))
4890 (kill-region (point) (progn (end-of-visible-line) (point))))
4891 (kill-region (point)
4892 (progn (forward-visible-line (1+ arg))
4893 (unless (bobp) (backward-char))
4897 (kill-region (point) (progn (forward-visible-line 0) (point))))
4898 (kill-region (point)
4899 (progn (forward-visible-line arg) (point))))))
4901 (defun forward-visible-line (arg)
4902 "Move forward by ARG lines, ignoring currently invisible newlines only.
4903 If ARG is negative, move backward -ARG lines.
4904 If ARG is zero, move to the beginning of the current line."
4909 (or (zerop (forward-line 1))
4910 (signal 'end-of-buffer nil))
4911 ;; If the newline we just skipped is invisible,
4914 (get-char-property (1- (point)) 'invisible)))
4915 (if (if (eq buffer-invisibility-spec t)
4917 (or (memq prop buffer-invisibility-spec)
4918 (assq prop buffer-invisibility-spec)))
4919 (setq arg (1+ arg))))
4920 (setq arg (1- arg)))
4921 ;; If invisible text follows, and it is a number of complete lines,
4923 (let ((opoint (point)))
4924 (while (and (not (eobp))
4926 (get-char-property (point) 'invisible)))
4927 (if (eq buffer-invisibility-spec t)
4929 (or (memq prop buffer-invisibility-spec)
4930 (assq prop buffer-invisibility-spec)))))
4932 (if (get-text-property (point) 'invisible)
4933 (or (next-single-property-change (point) 'invisible)
4935 (next-overlay-change (point)))))
4937 (goto-char opoint))))
4939 (while (or first (<= arg 0))
4942 (or (zerop (forward-line -1))
4943 (signal 'beginning-of-buffer nil)))
4944 ;; If the newline we just moved to is invisible,
4948 (get-char-property (1- (point)) 'invisible)))
4949 (unless (if (eq buffer-invisibility-spec t)
4951 (or (memq prop buffer-invisibility-spec)
4952 (assq prop buffer-invisibility-spec)))
4953 (setq arg (1+ arg)))))
4955 ;; If invisible text follows, and it is a number of complete lines,
4957 (let ((opoint (point)))
4958 (while (and (not (bobp))
4960 (get-char-property (1- (point)) 'invisible)))
4961 (if (eq buffer-invisibility-spec t)
4963 (or (memq prop buffer-invisibility-spec)
4964 (assq prop buffer-invisibility-spec)))))
4966 (if (get-text-property (1- (point)) 'invisible)
4967 (or (previous-single-property-change (point) 'invisible)
4969 (previous-overlay-change (point)))))
4971 (goto-char opoint)))))
4972 ((beginning-of-buffer end-of-buffer)
4975 (defun end-of-visible-line ()
4976 "Move to end of current visible line."
4978 ;; If the following character is currently invisible,
4979 ;; skip all characters with that same `invisible' property value,
4980 ;; then find the next newline.
4981 (while (and (not (eobp))
4983 (skip-chars-forward "^\n")
4985 (get-char-property (point) 'invisible)))
4986 (if (eq buffer-invisibility-spec t)
4988 (or (memq prop buffer-invisibility-spec)
4989 (assq prop buffer-invisibility-spec))))))
4990 (skip-chars-forward "^\n")
4991 (if (get-text-property (point) 'invisible)
4992 (goto-char (or (next-single-property-change (point) 'invisible)
4994 (goto-char (next-overlay-change (point))))
4997 (defun insert-buffer (buffer)
4998 "Insert after point the contents of BUFFER.
4999 Puts mark after the inserted text.
5000 BUFFER may be a buffer or a buffer name."
5001 (declare (interactive-only insert-buffer-substring))
5005 (barf-if-buffer-read-only)
5006 (read-buffer "Insert buffer: "
5007 (if (eq (selected-window) (next-window))
5008 (other-buffer (current-buffer))
5009 (window-buffer (next-window)))
5013 (insert-buffer-substring (get-buffer buffer))
5017 (defun append-to-buffer (buffer start end)
5018 "Append to specified buffer the text of the region.
5019 It is inserted into that buffer before its point.
5021 When calling from a program, give three arguments:
5022 BUFFER (or buffer name), START and END.
5023 START and END specify the portion of the current buffer to be copied."
5025 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5026 (region-beginning) (region-end)))
5027 (let* ((oldbuf (current-buffer))
5028 (append-to (get-buffer-create buffer))
5029 (windows (get-buffer-window-list append-to t t))
5032 (with-current-buffer append-to
5033 (setq point (point))
5034 (barf-if-buffer-read-only)
5035 (insert-buffer-substring oldbuf start end)
5036 (dolist (window windows)
5037 (when (= (window-point window) point)
5038 (set-window-point window (point))))))))
5040 (defun prepend-to-buffer (buffer start end)
5041 "Prepend to specified buffer the text of the region.
5042 It is inserted into that buffer after its point.
5044 When calling from a program, give three arguments:
5045 BUFFER (or buffer name), START and END.
5046 START and END specify the portion of the current buffer to be copied."
5047 (interactive "BPrepend to buffer: \nr")
5048 (let ((oldbuf (current-buffer)))
5049 (with-current-buffer (get-buffer-create buffer)
5050 (barf-if-buffer-read-only)
5052 (insert-buffer-substring oldbuf start end)))))
5054 (defun copy-to-buffer (buffer start end)
5055 "Copy to specified buffer the text of the region.
5056 It is inserted into that buffer, replacing existing text there.
5058 When calling from a program, give three arguments:
5059 BUFFER (or buffer name), START and END.
5060 START and END specify the portion of the current buffer to be copied."
5061 (interactive "BCopy to buffer: \nr")
5062 (let ((oldbuf (current-buffer)))
5063 (with-current-buffer (get-buffer-create buffer)
5064 (barf-if-buffer-read-only)
5067 (insert-buffer-substring oldbuf start end)))))
5069 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5071 (defvar activate-mark-hook nil
5072 "Hook run when the mark becomes active.
5073 It is also run at the end of a command, if the mark is active and
5074 it is possible that the region may have changed.")
5076 (defvar deactivate-mark-hook nil
5077 "Hook run when the mark becomes inactive.")
5079 (defun mark (&optional force)
5080 "Return this buffer's mark value as integer, or nil if never set.
5082 In Transient Mark mode, this function signals an error if
5083 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5084 or the argument FORCE is non-nil, it disregards whether the mark
5085 is active, and returns an integer or nil in the usual way.
5087 If you are using this in an editing command, you are most likely making
5088 a mistake; see the documentation of `set-mark'."
5089 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5090 (marker-position (mark-marker))
5091 (signal 'mark-inactive nil)))
5093 ;; Behind display-selections-p.
5095 (defun deactivate-mark (&optional force)
5096 "Deactivate the mark.
5097 If Transient Mark mode is disabled, this function normally does
5098 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5100 Deactivating the mark sets `mark-active' to nil, updates the
5101 primary selection according to `select-active-regions', and runs
5102 `deactivate-mark-hook'.
5104 If Transient Mark mode was temporarily enabled, reset the value
5105 of the variable `transient-mark-mode'; if this causes Transient
5106 Mark mode to be disabled, don't change `mark-active' to nil or
5107 run `deactivate-mark-hook'."
5108 (when (or (region-active-p) force)
5109 (when (and (if (eq select-active-regions 'only)
5110 (eq (car-safe transient-mark-mode) 'only)
5111 select-active-regions)
5113 (display-selections-p))
5114 ;; The var `saved-region-selection', if non-nil, is the text in
5115 ;; the region prior to the last command modifying the buffer.
5116 ;; Set the selection to that, or to the current region.
5117 (cond (saved-region-selection
5118 (if (gui-backend-selection-owner-p 'PRIMARY)
5119 (gui-set-selection 'PRIMARY saved-region-selection))
5120 (setq saved-region-selection nil))
5121 ;; If another program has acquired the selection, region
5122 ;; deactivation should not clobber it (Bug#11772).
5123 ((and (/= (region-beginning) (region-end))
5124 (or (gui-backend-selection-owner-p 'PRIMARY)
5125 (null (gui-backend-selection-exists-p 'PRIMARY))))
5126 (gui-set-selection 'PRIMARY
5127 (funcall region-extract-function nil)))))
5128 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5130 ((eq (car-safe transient-mark-mode) 'only)
5131 (setq transient-mark-mode (cdr transient-mark-mode))
5132 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5133 (kill-local-variable 'transient-mark-mode)))
5134 ((eq transient-mark-mode 'lambda)
5135 (kill-local-variable 'transient-mark-mode)))
5136 (setq mark-active nil)
5137 (run-hooks 'deactivate-mark-hook)
5138 (redisplay--update-region-highlight (selected-window))))
5140 (defun activate-mark (&optional no-tmm)
5142 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5144 (unless (region-active-p)
5145 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5146 (setq mark-active t)
5147 (unless (or transient-mark-mode no-tmm)
5148 (setq-local transient-mark-mode 'lambda))
5149 (run-hooks 'activate-mark-hook))))
5151 (defun set-mark (pos)
5152 "Set this buffer's mark to POS. Don't use this function!
5153 That is to say, don't use this function unless you want
5154 the user to see that the mark has moved, and you want the previous
5155 mark position to be lost.
5157 Normally, when a new mark is set, the old one should go on the stack.
5158 This is why most applications should use `push-mark', not `set-mark'.
5160 Novice Emacs Lisp programmers often try to use the mark for the wrong
5161 purposes. The mark saves a location for the user's convenience.
5162 Most editing commands should not alter the mark.
5163 To remember a location for internal use in the Lisp program,
5164 store it in a Lisp variable. Example:
5166 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5169 (set-marker (mark-marker) pos (current-buffer))
5170 (activate-mark 'no-tmm))
5171 ;; Normally we never clear mark-active except in Transient Mark mode.
5172 ;; But when we actually clear out the mark value too, we must
5173 ;; clear mark-active in any mode.
5175 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5176 ;; it should never be nil if the mark is nil.
5177 (setq mark-active nil)
5178 (set-marker (mark-marker) nil)))
5180 (defun save-mark-and-excursion--save ()
5182 (let ((mark (mark-marker)))
5183 (and (marker-position mark) (copy-marker mark)))
5186 (defun save-mark-and-excursion--restore (saved-mark-info)
5187 (let ((saved-mark (car saved-mark-info))
5188 (omark (marker-position (mark-marker)))
5190 (saved-mark-active (cdr saved-mark-info)))
5192 (if (null saved-mark)
5193 (set-marker (mark-marker) nil)
5194 (setf nmark (marker-position saved-mark))
5195 (set-marker (mark-marker) nmark)
5196 (set-marker saved-mark nil))
5198 (let ((cur-mark-active mark-active))
5199 (setq mark-active saved-mark-active)
5200 ;; If mark is active now, and either was not active or was at a
5201 ;; different place, run the activate hook.
5202 (if saved-mark-active
5203 (when (or (not cur-mark-active)
5204 (not (eq omark nmark)))
5205 (run-hooks 'activate-mark-hook))
5206 ;; If mark has ceased to be active, run deactivate hook.
5207 (when cur-mark-active
5208 (run-hooks 'deactivate-mark-hook))))))
5210 (defmacro save-mark-and-excursion (&rest body)
5211 "Like `save-excursion', but also save and restore the mark state.
5212 This macro does what `save-excursion' did before Emacs 25.1."
5213 (let ((saved-marker-sym (make-symbol "saved-marker")))
5214 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5216 (save-excursion ,@body)
5217 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5219 (defcustom use-empty-active-region nil
5220 "Whether \"region-aware\" commands should act on empty regions.
5221 If nil, region-aware commands treat the empty region as inactive.
5222 If non-nil, region-aware commands treat the region as active as
5223 long as the mark is active, even if the region is empty.
5225 Region-aware commands are those that act on the region if it is
5226 active and Transient Mark mode is enabled, and on the text near
5230 :group 'editing-basics)
5232 (defun use-region-p ()
5233 "Return t if the region is active and it is appropriate to act on it.
5234 This is used by commands that act specially on the region under
5235 Transient Mark mode.
5237 The return value is t if Transient Mark mode is enabled and the
5238 mark is active; furthermore, if `use-empty-active-region' is nil,
5239 the region must not be empty. Otherwise, the return value is nil.
5241 For some commands, it may be appropriate to ignore the value of
5242 `use-empty-active-region'; in that case, use `region-active-p'."
5243 (and (region-active-p)
5244 (or use-empty-active-region (> (region-end) (region-beginning)))))
5246 (defun region-active-p ()
5247 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5249 Some commands act specially on the region when Transient Mark
5250 mode is enabled. Usually, such commands should use
5251 `use-region-p' instead of this function, because `use-region-p'
5252 also checks the value of `use-empty-active-region'."
5253 (and transient-mark-mode mark-active
5254 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5255 ;; without the mark being set (e.g. bug#17324). We really should fix
5256 ;; that problem, but in the mean time, let's make sure we don't say the
5257 ;; region is active when there's no mark.
5258 (progn (cl-assert (mark)) t)))
5260 (defun region-noncontiguous-p ()
5261 "Return non-nil if the region contains several pieces.
5262 An example is a rectangular region handled as a list of
5263 separate contiguous regions for each line."
5264 (> (length (funcall region-extract-function 'bounds)) 1))
5266 (defvar redisplay-unhighlight-region-function
5267 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5269 (defvar redisplay-highlight-region-function
5270 (lambda (start end window rol)
5271 (if (not (overlayp rol))
5272 (let ((nrol (make-overlay start end)))
5273 (funcall redisplay-unhighlight-region-function rol)
5274 (overlay-put nrol 'window window)
5275 (overlay-put nrol 'face 'region)
5276 ;; Normal priority so that a large region doesn't hide all the
5277 ;; overlays within it, but high secondary priority so that if it
5278 ;; ends/starts in the middle of a small overlay, that small overlay
5279 ;; won't hide the region's boundaries.
5280 (overlay-put nrol 'priority '(nil . 100))
5282 (unless (and (eq (overlay-buffer rol) (current-buffer))
5283 (eq (overlay-start rol) start)
5284 (eq (overlay-end rol) end))
5285 (move-overlay rol start end (current-buffer)))
5288 (defun redisplay--update-region-highlight (window)
5289 (let ((rol (window-parameter window 'internal-region-overlay)))
5290 (if (not (and (region-active-p)
5291 (or highlight-nonselected-windows
5292 (eq window (selected-window))
5293 (and (window-minibuffer-p)
5294 (eq window (minibuffer-selected-window))))))
5295 (funcall redisplay-unhighlight-region-function rol)
5296 (let* ((pt (window-point window))
5298 (start (min pt mark))
5301 (funcall redisplay-highlight-region-function
5302 start end window rol)))
5303 (unless (equal new rol)
5304 (set-window-parameter window 'internal-region-overlay
5307 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5308 "Hook run just before redisplay.
5309 It is called in each window that is to be redisplayed. It takes one argument,
5310 which is the window that will be redisplayed. When run, the `current-buffer'
5311 is set to the buffer displayed in that window.")
5313 (defun redisplay--pre-redisplay-functions (windows)
5314 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5316 (with-current-buffer (window-buffer (selected-window))
5317 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5318 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5319 (with-current-buffer (window-buffer win)
5320 (run-hook-with-args 'pre-redisplay-functions win))))))
5322 (add-function :before pre-redisplay-function
5323 #'redisplay--pre-redisplay-functions)
5326 (defvar-local mark-ring nil
5327 "The list of former marks of the current buffer, most recent first.")
5328 (put 'mark-ring 'permanent-local t)
5330 (defcustom mark-ring-max 16
5331 "Maximum size of mark ring. Start discarding off end if gets this big."
5333 :group 'editing-basics)
5335 (defvar global-mark-ring nil
5336 "The list of saved global marks, most recent first.")
5338 (defcustom global-mark-ring-max 16
5339 "Maximum size of global mark ring. \
5340 Start discarding off end if gets this big."
5342 :group 'editing-basics)
5344 (defun pop-to-mark-command ()
5345 "Jump to mark, and pop a new position for mark off the ring.
5346 \(Does not affect global mark ring)."
5349 (user-error "No mark set in this buffer")
5350 (if (= (point) (mark t))
5351 (message "Mark popped"))
5352 (goto-char (mark t))
5355 (defun push-mark-command (arg &optional nomsg)
5356 "Set mark at where point is.
5357 If no prefix ARG and mark is already set there, just activate it.
5358 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5360 (let ((mark (mark t)))
5361 (if (or arg (null mark) (/= mark (point)))
5362 (push-mark nil nomsg t)
5363 (activate-mark 'no-tmm)
5365 (message "Mark activated")))))
5367 (defcustom set-mark-command-repeat-pop nil
5368 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5369 That means that C-u \\[set-mark-command] \\[set-mark-command]
5370 will pop the mark twice, and
5371 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5372 will pop the mark three times.
5374 A value of nil means \\[set-mark-command]'s behavior does not change
5375 after C-u \\[set-mark-command]."
5377 :group 'editing-basics)
5379 (defun set-mark-command (arg)
5380 "Set the mark where point is, or jump to the mark.
5381 Setting the mark also alters the region, which is the text
5382 between point and mark; this is the closest equivalent in
5383 Emacs to what some editors call the \"selection\".
5385 With no prefix argument, set the mark at point, and push the
5386 old mark position on local mark ring. Also push the old mark on
5387 global mark ring, if the previous mark was set in another buffer.
5389 When Transient Mark Mode is off, immediately repeating this
5390 command activates `transient-mark-mode' temporarily.
5392 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5393 jump to the mark, and set the mark from
5394 position popped off the local mark ring (this does not affect the global
5395 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5396 mark ring (see `pop-global-mark').
5398 If `set-mark-command-repeat-pop' is non-nil, repeating
5399 the \\[set-mark-command] command with no prefix argument pops the next position
5400 off the local (or global) mark ring and jumps there.
5402 With \\[universal-argument] \\[universal-argument] as prefix
5403 argument, unconditionally set mark where point is, even if
5404 `set-mark-command-repeat-pop' is non-nil.
5406 Novice Emacs Lisp programmers often try to use the mark for the wrong
5407 purposes. See the documentation of `set-mark' for more information."
5409 (cond ((eq transient-mark-mode 'lambda)
5410 (kill-local-variable 'transient-mark-mode))
5411 ((eq (car-safe transient-mark-mode) 'only)
5414 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5415 (push-mark-command nil))
5416 ((not (eq this-command 'set-mark-command))
5418 (pop-to-mark-command)
5419 (push-mark-command t)))
5420 ((and set-mark-command-repeat-pop
5421 (eq last-command 'pop-global-mark)
5423 (setq this-command 'pop-global-mark)
5425 ((or (and set-mark-command-repeat-pop
5426 (eq last-command 'pop-to-mark-command))
5428 (setq this-command 'pop-to-mark-command)
5429 (pop-to-mark-command))
5430 ((eq last-command 'set-mark-command)
5431 (if (region-active-p)
5434 (message "Mark deactivated"))
5436 (message "Mark activated")))
5438 (push-mark-command nil))))
5440 (defun push-mark (&optional location nomsg activate)
5441 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5442 If the last global mark pushed was not in the current buffer,
5443 also push LOCATION on the global mark ring.
5444 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5446 Novice Emacs Lisp programmers often try to use the mark for the wrong
5447 purposes. See the documentation of `set-mark' for more information.
5449 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5450 (unless (null (mark t))
5451 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5452 (when (> (length mark-ring) mark-ring-max)
5453 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5454 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5455 (set-marker (mark-marker) (or location (point)) (current-buffer))
5456 ;; Now push the mark on the global mark ring.
5457 (if (and global-mark-ring
5458 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5459 ;; The last global mark pushed was in this same buffer.
5460 ;; Don't push another one.
5462 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5463 (when (> (length global-mark-ring) global-mark-ring-max)
5464 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5465 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5466 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5467 (message "Mark set"))
5468 (if (or activate (not transient-mark-mode))
5469 (set-mark (mark t)))
5473 "Pop off mark ring into the buffer's actual mark.
5474 Does not set point. Does nothing if mark ring is empty."
5476 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5477 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5478 (move-marker (car mark-ring) nil)
5479 (if (null (mark t)) (ding))
5480 (setq mark-ring (cdr mark-ring)))
5483 (define-obsolete-function-alias
5484 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5485 (defun exchange-point-and-mark (&optional arg)
5486 "Put the mark where point is now, and point where the mark is now.
5487 This command works even when the mark is not active,
5488 and it reactivates the mark.
5490 If Transient Mark mode is on, a prefix ARG deactivates the mark
5491 if it is active, and otherwise avoids reactivating it. If
5492 Transient Mark mode is off, a prefix ARG enables Transient Mark
5495 (let ((omark (mark t))
5496 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5498 (user-error "No mark set in this buffer"))
5501 (cond (temp-highlight
5502 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5503 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5504 (not (or arg (region-active-p))))
5506 (t (activate-mark)))
5509 (defcustom shift-select-mode t
5510 "When non-nil, shifted motion keys activate the mark momentarily.
5512 While the mark is activated in this way, any shift-translated point
5513 motion key extends the region, and if Transient Mark mode was off, it
5514 is temporarily turned on. Furthermore, the mark will be deactivated
5515 by any subsequent point motion key that was not shift-translated, or
5516 by any action that normally deactivates the mark in Transient Mark mode.
5518 See `this-command-keys-shift-translated' for the meaning of
5521 :group 'editing-basics)
5523 (defun handle-shift-selection ()
5524 "Activate/deactivate mark depending on invocation thru shift translation.
5525 This function is called by `call-interactively' when a command
5526 with a `^' character in its `interactive' spec is invoked, before
5527 running the command itself.
5529 If `shift-select-mode' is enabled and the command was invoked
5530 through shift translation, set the mark and activate the region
5531 temporarily, unless it was already set in this way. See
5532 `this-command-keys-shift-translated' for the meaning of shift
5535 Otherwise, if the region has been activated temporarily,
5536 deactivate it, and restore the variable `transient-mark-mode' to
5538 (cond ((and shift-select-mode this-command-keys-shift-translated)
5539 (unless (and mark-active
5540 (eq (car-safe transient-mark-mode) 'only))
5541 (setq-local transient-mark-mode
5543 (unless (eq transient-mark-mode 'lambda)
5544 transient-mark-mode)))
5545 (push-mark nil nil t)))
5546 ((eq (car-safe transient-mark-mode) 'only)
5547 (setq transient-mark-mode (cdr transient-mark-mode))
5548 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5549 (kill-local-variable 'transient-mark-mode))
5550 (deactivate-mark))))
5552 (define-minor-mode transient-mark-mode
5553 "Toggle Transient Mark mode.
5554 With a prefix argument ARG, enable Transient Mark mode if ARG is
5555 positive, and disable it otherwise. If called from Lisp, enable
5556 Transient Mark mode if ARG is omitted or nil.
5558 Transient Mark mode is a global minor mode. When enabled, the
5559 region is highlighted with the `region' face whenever the mark
5560 is active. The mark is \"deactivated\" by changing the buffer,
5561 and after certain other operations that set the mark but whose
5562 main purpose is something else--for example, incremental search,
5563 \\[beginning-of-buffer], and \\[end-of-buffer].
5565 You can also deactivate the mark by typing \\[keyboard-quit] or
5566 \\[keyboard-escape-quit].
5568 Many commands change their behavior when Transient Mark mode is
5569 in effect and the mark is active, by acting on the region instead
5570 of their usual default part of the buffer's text. Examples of
5571 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5572 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5573 To see the documentation of commands which are sensitive to the
5574 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5575 or \"mark.*active\" at the prompt."
5577 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5578 :variable (default-value 'transient-mark-mode))
5580 (defvar widen-automatically t
5581 "Non-nil means it is ok for commands to call `widen' when they want to.
5582 Some commands will do this in order to go to positions outside
5583 the current accessible part of the buffer.
5585 If `widen-automatically' is nil, these commands will do something else
5586 as a fallback, and won't change the buffer bounds.")
5588 (defvar non-essential nil
5589 "Whether the currently executing code is performing an essential task.
5590 This variable should be non-nil only when running code which should not
5591 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5592 user for a password when we are simply scanning a set of files in the
5593 background or displaying possible completions before the user even asked
5596 (defun pop-global-mark ()
5597 "Pop off global mark ring and jump to the top location."
5599 ;; Pop entries which refer to non-existent buffers.
5600 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5601 (setq global-mark-ring (cdr global-mark-ring)))
5602 (or global-mark-ring
5603 (error "No global mark set"))
5604 (let* ((marker (car global-mark-ring))
5605 (buffer (marker-buffer marker))
5606 (position (marker-position marker)))
5607 (setq global-mark-ring (nconc (cdr global-mark-ring)
5608 (list (car global-mark-ring))))
5610 (or (and (>= position (point-min))
5611 (<= position (point-max)))
5612 (if widen-automatically
5614 (error "Global mark position is outside accessible part of buffer")))
5615 (goto-char position)
5616 (switch-to-buffer buffer)))
5618 (defcustom next-line-add-newlines nil
5619 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5622 :group 'editing-basics)
5624 (defun next-line (&optional arg try-vscroll)
5625 "Move cursor vertically down ARG lines.
5626 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5627 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5628 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5629 function will not vscroll.
5633 If there is no character in the target line exactly under the current column,
5634 the cursor is positioned after the character in that line which spans this
5635 column, or at the end of the line if it is not long enough.
5636 If there is no line in the buffer after this one, behavior depends on the
5637 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5638 to create a line, and moves the cursor to that line. Otherwise it moves the
5639 cursor to the end of the buffer.
5641 If the variable `line-move-visual' is non-nil, this command moves
5642 by display lines. Otherwise, it moves by buffer lines, without
5643 taking variable-width characters or continued lines into account.
5645 The command \\[set-goal-column] can be used to create
5646 a semipermanent goal column for this command.
5647 Then instead of trying to move exactly vertically (or as close as possible),
5648 this command moves to the specified goal column (or as close as possible).
5649 The goal column is stored in the variable `goal-column', which is nil
5650 when there is no goal column. Note that setting `goal-column'
5651 overrides `line-move-visual' and causes this command to move by buffer
5652 lines rather than by display lines."
5653 (declare (interactive-only forward-line))
5654 (interactive "^p\np")
5655 (or arg (setq arg 1))
5656 (if (and next-line-add-newlines (= arg 1))
5657 (if (save-excursion (end-of-line) (eobp))
5658 ;; When adding a newline, don't expand an abbrev.
5659 (let ((abbrev-mode nil))
5661 (insert (if use-hard-newlines hard-newline "\n")))
5662 (line-move arg nil nil try-vscroll))
5663 (if (called-interactively-p 'interactive)
5665 (line-move arg nil nil try-vscroll)
5666 ((beginning-of-buffer end-of-buffer)
5667 (signal (car err) (cdr err))))
5668 (line-move arg nil nil try-vscroll)))
5671 (defun previous-line (&optional arg try-vscroll)
5672 "Move cursor vertically up ARG lines.
5673 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5674 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5675 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5676 function will not vscroll.
5680 If there is no character in the target line exactly over the current column,
5681 the cursor is positioned after the character in that line which spans this
5682 column, or at the end of the line if it is not long enough.
5684 If the variable `line-move-visual' is non-nil, this command moves
5685 by display lines. Otherwise, it moves by buffer lines, without
5686 taking variable-width characters or continued lines into account.
5688 The command \\[set-goal-column] can be used to create
5689 a semipermanent goal column for this command.
5690 Then instead of trying to move exactly vertically (or as close as possible),
5691 this command moves to the specified goal column (or as close as possible).
5692 The goal column is stored in the variable `goal-column', which is nil
5693 when there is no goal column. Note that setting `goal-column'
5694 overrides `line-move-visual' and causes this command to move by buffer
5695 lines rather than by display lines."
5696 (declare (interactive-only
5697 "use `forward-line' with negative argument instead."))
5698 (interactive "^p\np")
5699 (or arg (setq arg 1))
5700 (if (called-interactively-p 'interactive)
5702 (line-move (- arg) nil nil try-vscroll)
5703 ((beginning-of-buffer end-of-buffer)
5704 (signal (car err) (cdr err))))
5705 (line-move (- arg) nil nil try-vscroll))
5708 (defcustom track-eol nil
5709 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5710 This means moving to the end of each line moved onto.
5711 The beginning of a blank line does not count as the end of a line.
5712 This has no effect when the variable `line-move-visual' is non-nil."
5714 :group 'editing-basics)
5716 (defcustom goal-column nil
5717 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5718 A non-nil setting overrides the variable `line-move-visual', which see."
5719 :type '(choice integer
5720 (const :tag "None" nil))
5721 :group 'editing-basics)
5722 (make-variable-buffer-local 'goal-column)
5724 (defvar temporary-goal-column 0
5725 "Current goal column for vertical motion.
5726 It is the column where point was at the start of the current run
5727 of vertical motion commands.
5729 When moving by visual lines via the function `line-move-visual', it is a cons
5730 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5731 divided by the default column width, and HSCROLL is the number of
5732 columns by which window is scrolled from left margin.
5734 When the `track-eol' feature is doing its job, the value is
5735 `most-positive-fixnum'.")
5737 (defcustom line-move-ignore-invisible t
5738 "Non-nil means commands that move by lines ignore invisible newlines.
5739 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5740 as if newlines that are invisible didn't exist, and count
5741 only visible newlines. Thus, moving across across 2 newlines
5742 one of which is invisible will be counted as a one-line move.
5743 Also, a non-nil value causes invisible text to be ignored when
5744 counting columns for the purposes of keeping point in the same
5745 column by \\[next-line] and \\[previous-line].
5747 Outline mode sets this."
5749 :group 'editing-basics)
5751 (defcustom line-move-visual t
5752 "When non-nil, `line-move' moves point by visual lines.
5753 This movement is based on where the cursor is displayed on the
5754 screen, instead of relying on buffer contents alone. It takes
5755 into account variable-width characters and line continuation.
5756 If nil, `line-move' moves point by logical lines.
5757 A non-nil setting of `goal-column' overrides the value of this variable
5758 and forces movement by logical lines.
5759 A window that is horizontally scrolled also forces movement by logical
5762 :group 'editing-basics
5765 ;; Only used if display-graphic-p.
5766 (declare-function font-info "font.c" (name &optional frame))
5768 (defun default-font-height ()
5769 "Return the height in pixels of the current buffer's default face font.
5771 If the default font is remapped (see `face-remapping-alist'), the
5772 function returns the height of the remapped face."
5773 (let ((default-font (face-font 'default)))
5775 ((and (display-multi-font-p)
5776 ;; Avoid calling font-info if the frame's default font was
5777 ;; not changed since the frame was created. That's because
5778 ;; font-info is expensive for some fonts, see bug #14838.
5779 (not (string= (frame-parameter nil 'font) default-font)))
5780 (aref (font-info default-font) 3))
5781 (t (frame-char-height)))))
5783 (defun default-font-width ()
5784 "Return the width in pixels of the current buffer's default face font.
5786 If the default font is remapped (see `face-remapping-alist'), the
5787 function returns the width of the remapped face."
5788 (let ((default-font (face-font 'default)))
5790 ((and (display-multi-font-p)
5791 ;; Avoid calling font-info if the frame's default font was
5792 ;; not changed since the frame was created. That's because
5793 ;; font-info is expensive for some fonts, see bug #14838.
5794 (not (string= (frame-parameter nil 'font) default-font)))
5795 (let* ((info (font-info (face-font 'default)))
5796 (width (aref info 11)))
5800 (t (frame-char-width)))))
5802 (defun default-line-height ()
5803 "Return the pixel height of current buffer's default-face text line.
5805 The value includes `line-spacing', if any, defined for the buffer
5807 (let ((dfh (default-font-height))
5808 (lsp (if (display-graphic-p)
5810 (default-value 'line-spacing)
5811 (frame-parameter nil 'line-spacing)
5815 (setq lsp (truncate (* (frame-char-height) lsp))))
5818 (defun window-screen-lines ()
5819 "Return the number of screen lines in the text area of the selected window.
5821 This is different from `window-text-height' in that this function counts
5822 lines in units of the height of the font used by the default face displayed
5823 in the window, not in units of the frame's default font, and also accounts
5824 for `line-spacing', if any, defined for the window's buffer or frame.
5826 The value is a floating-point number."
5827 (let ((edges (window-inside-pixel-edges))
5828 (dlh (default-line-height)))
5829 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5831 ;; Returns non-nil if partial move was done.
5832 (defun line-move-partial (arg noerror &optional _to-end)
5834 ;; Move backward (up).
5835 ;; If already vscrolled, reduce vscroll
5836 (let ((vs (window-vscroll nil t))
5837 (dlh (default-line-height)))
5839 (set-window-vscroll nil (- vs dlh) t)))
5841 ;; Move forward (down).
5842 (let* ((lh (window-line-height -1))
5847 (this-lh (window-line-height))
5848 (this-height (car this-lh))
5849 (this-ypos (nth 2 this-lh))
5850 (dlh (default-line-height))
5851 (wslines (window-screen-lines))
5852 (edges (window-inside-pixel-edges))
5853 (winh (- (nth 3 edges) (nth 1 edges) 1))
5855 (if (> (mod wslines 1.0) 0.0)
5856 (setq wslines (round (+ wslines 0.5))))
5861 (<= this-ypos (- dlh)))
5863 (let ((wend (pos-visible-in-window-p t nil t)))
5864 (setq rbot (nth 3 wend)
5866 vpos (nth 5 wend))))
5868 (let ((wstart (pos-visible-in-window-p nil nil t)))
5869 (setq this-ypos (nth 2 wstart)
5870 this-height (nth 4 wstart))))
5873 (let ((ppos (posn-at-point))
5875 (setq col-row (posn-actual-col-row ppos))
5877 (- (cdr col-row) (window-vscroll))
5878 (cdr (posn-col-row ppos))))))
5879 ;; VPOS > 0 means the last line is only partially visible.
5880 ;; But if the part that is visible is at least as tall as the
5881 ;; default font, that means the line is actually fully
5882 ;; readable, and something like line-spacing is hidden. So in
5883 ;; that case we accept the last line in the window as still
5884 ;; visible, and consider the margin as starting one line
5886 (if (and vpos (> vpos 0))
5888 (>= rowh (default-font-height))
5890 (setq last-line (min (- wslines scroll-margin) vpos))
5891 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5893 ;; If last line of window is fully visible, and vscrolling
5894 ;; more would make this line invisible, move forward.
5895 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5897 (<= this-height dlh))
5898 (or (null rbot) (= rbot 0)))
5900 ;; If cursor is not in the bottom scroll margin, and the
5901 ;; current line is is not too tall, move forward.
5902 ((and (or (null this-height) (<= this-height winh))
5907 ;; When already vscrolled, we vscroll some more if we can,
5908 ;; or clear vscroll and move forward at end of tall image.
5910 (when (or (and rbot (> rbot 0))
5911 (and this-height (> this-height dlh)))
5912 (set-window-vscroll nil (+ vs dlh) t)))
5913 ;; If cursor just entered the bottom scroll margin, move forward,
5914 ;; but also optionally vscroll one line so redisplay won't recenter.
5918 ;; Don't vscroll if the partially-visible line at window
5919 ;; bottom is not too tall (a.k.a. "just one more text
5920 ;; line"): in that case, we do want redisplay to behave
5921 ;; normally, i.e. recenter or whatever.
5923 ;; Note: ROWH + RBOT from the value returned by
5924 ;; pos-visible-in-window-p give the total height of the
5925 ;; partially-visible glyph row at the end of the window. As
5926 ;; we are dealing with floats, we disregard sub-pixel
5927 ;; discrepancies between that and DLH.
5928 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5929 (set-window-vscroll nil dlh t))
5930 (line-move-1 arg noerror)
5932 ;; If there are lines above the last line, scroll-up one line.
5933 ((and vpos (> vpos 0))
5936 ;; Finally, start vscroll.
5938 (set-window-vscroll nil dlh t)))))))
5941 ;; This is like line-move-1 except that it also performs
5942 ;; vertical scrolling of tall images if appropriate.
5943 ;; That is not really a clean thing to do, since it mixes
5944 ;; scrolling with cursor motion. But so far we don't have
5945 ;; a cleaner solution to the problem of making C-n do something
5946 ;; useful given a tall image.
5947 (defun line-move (arg &optional noerror _to-end try-vscroll)
5948 "Move forward ARG lines.
5949 If NOERROR, don't signal an error if we can't move ARG lines.
5951 TRY-VSCROLL controls whether to vscroll tall lines: if either
5952 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5955 (line-move-1 arg noerror)
5956 (unless (and auto-window-vscroll try-vscroll
5957 ;; Only vscroll for single line moves
5959 ;; Under scroll-conservatively, the display engine
5960 ;; does this better.
5961 (zerop scroll-conservatively)
5962 ;; But don't vscroll in a keyboard macro.
5963 (not defining-kbd-macro)
5964 (not executing-kbd-macro)
5965 (line-move-partial arg noerror))
5966 (set-window-vscroll nil 0 t)
5967 (if (and line-move-visual
5968 ;; Display-based column are incompatible with goal-column.
5970 ;; When the text in the window is scrolled to the left,
5971 ;; display-based motion doesn't make sense (because each
5972 ;; logical line occupies exactly one screen line).
5973 (not (> (window-hscroll) 0))
5974 ;; Likewise when the text _was_ scrolled to the left
5975 ;; when the current run of vertical motion commands
5977 (not (and (memq last-command
5978 `(next-line previous-line ,this-command))
5980 (numberp temporary-goal-column)
5981 (>= temporary-goal-column
5982 (- (window-width) hscroll-margin)))))
5983 (prog1 (line-move-visual arg noerror)
5984 ;; If we moved into a tall line, set vscroll to make
5985 ;; scrolling through tall images more smooth.
5986 (let ((lh (line-pixel-height))
5987 (edges (window-inside-pixel-edges))
5988 (dlh (default-line-height))
5990 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5992 (< (point) (window-start))
5997 (line-move-1 arg noerror)))))
5999 ;; Display-based alternative to line-move-1.
6000 ;; Arg says how many lines to move. The value is t if we can move the
6001 ;; specified number of lines.
6002 (defun line-move-visual (arg &optional noerror)
6003 "Move ARG lines forward.
6004 If NOERROR, don't signal an error if we can't move that many lines."
6005 (let ((opoint (point))
6006 (hscroll (window-hscroll))
6008 ;; Check if the previous command was a line-motion command, or if
6009 ;; we were called from some other command.
6010 (if (and (consp temporary-goal-column)
6011 (memq last-command `(next-line previous-line ,this-command)))
6012 ;; If so, there's no need to reset `temporary-goal-column',
6013 ;; but we may need to hscroll.
6014 (if (or (/= (cdr temporary-goal-column) hscroll)
6015 (> (cdr temporary-goal-column) 0))
6016 (setq target-hscroll (cdr temporary-goal-column)))
6017 ;; Otherwise, we should reset `temporary-goal-column'.
6018 (let ((posn (posn-at-point))
6021 ;; Handle the `overflow-newline-into-fringe' case:
6022 ((eq (nth 1 posn) 'right-fringe)
6023 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6024 ((car (posn-x-y posn))
6025 (setq x-pos (car (posn-x-y posn)))
6026 ;; In R2L lines, the X pixel coordinate is measured from the
6027 ;; left edge of the window, but columns are still counted
6028 ;; from the logical-order beginning of the line, i.e. from
6029 ;; the right edge in this case. We need to adjust for that.
6030 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6031 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6032 (setq temporary-goal-column
6033 (cons (/ (float x-pos)
6037 (set-window-hscroll (selected-window) target-hscroll))
6038 ;; vertical-motion can move more than it was asked to if it moves
6039 ;; across display strings with newlines. We don't want to ring
6040 ;; the bell and announce beginning/end of buffer in that case.
6041 (or (and (or (and (>= arg 0)
6042 (>= (vertical-motion
6043 (cons (or goal-column
6044 (if (consp temporary-goal-column)
6045 (car temporary-goal-column)
6046 temporary-goal-column))
6050 (<= (vertical-motion
6051 (cons (or goal-column
6052 (if (consp temporary-goal-column)
6053 (car temporary-goal-column)
6054 temporary-goal-column))
6059 ;; If the goal column lies on a display string,
6060 ;; `vertical-motion' advances the cursor to the end
6061 ;; of the string. For arg < 0, this can cause the
6062 ;; cursor to get stuck. (Bug#3020).
6063 (= (vertical-motion arg) arg)))
6065 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6068 ;; This is the guts of next-line and previous-line.
6069 ;; Arg says how many lines to move.
6070 ;; The value is t if we can move the specified number of lines.
6071 (defun line-move-1 (arg &optional noerror _to-end)
6072 ;; Don't run any point-motion hooks, and disregard intangibility,
6073 ;; for intermediate positions.
6074 (let ((inhibit-point-motion-hooks t)
6077 (if (consp temporary-goal-column)
6078 (setq temporary-goal-column (+ (car temporary-goal-column)
6079 (cdr temporary-goal-column))))
6082 (if (not (memq last-command '(next-line previous-line)))
6083 (setq temporary-goal-column
6084 (if (and track-eol (eolp)
6085 ;; Don't count beg of empty line as end of line
6086 ;; unless we just did explicit end-of-line.
6087 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6088 most-positive-fixnum
6091 (if (not (or (integerp selective-display)
6092 line-move-ignore-invisible))
6093 ;; Use just newline characters.
6094 ;; Set ARG to 0 if we move as many lines as requested.
6096 (progn (if (> arg 1) (forward-line (1- arg)))
6097 ;; This way of moving forward ARG lines
6098 ;; verifies that we have a newline after the last one.
6099 ;; It doesn't get confused by intangible text.
6101 (if (zerop (forward-line 1))
6103 (and (zerop (forward-line arg))
6107 (signal (if (< arg 0)
6108 'beginning-of-buffer
6111 ;; Move by arg lines, but ignore invisible ones.
6113 (while (and (> arg 0) (not done))
6114 ;; If the following character is currently invisible,
6115 ;; skip all characters with that same `invisible' property value.
6116 (while (and (not (eobp)) (invisible-p (point)))
6117 (goto-char (next-char-property-change (point))))
6119 ;; We don't use `end-of-line', since we want to escape
6120 ;; from field boundaries occurring exactly at point.
6121 (goto-char (constrain-to-field
6122 (let ((inhibit-field-text-motion t))
6123 (line-end-position))
6125 'inhibit-line-move-field-capture))
6126 ;; If there's no invisibility here, move over the newline.
6130 (signal 'end-of-buffer nil)
6132 ((and (> arg 1) ;; Use vertical-motion for last move
6133 (not (integerp selective-display))
6134 (not (invisible-p (point))))
6135 ;; We avoid vertical-motion when possible
6136 ;; because that has to fontify.
6138 ;; Otherwise move a more sophisticated way.
6139 ((zerop (vertical-motion 1))
6141 (signal 'end-of-buffer nil)
6144 (setq arg (1- arg))))
6145 ;; The logic of this is the same as the loop above,
6146 ;; it just goes in the other direction.
6147 (while (and (< arg 0) (not done))
6148 ;; For completely consistency with the forward-motion
6149 ;; case, we should call beginning-of-line here.
6150 ;; However, if point is inside a field and on a
6151 ;; continued line, the call to (vertical-motion -1)
6152 ;; below won't move us back far enough; then we return
6153 ;; to the same column in line-move-finish, and point
6154 ;; gets stuck -- cyd
6159 (signal 'beginning-of-buffer nil)
6161 ((and (< arg -1) ;; Use vertical-motion for last move
6162 (not (integerp selective-display))
6163 (not (invisible-p (1- (point)))))
6165 ((zerop (vertical-motion -1))
6167 (signal 'beginning-of-buffer nil)
6171 (while (and ;; Don't move over previous invis lines
6172 ;; if our target is the middle of this line.
6173 (or (zerop (or goal-column temporary-goal-column))
6175 (not (bobp)) (invisible-p (1- (point))))
6176 (goto-char (previous-char-property-change (point))))))))
6177 ;; This is the value the function returns.
6181 ;; If we did not move down as far as desired, at least go
6182 ;; to end of line. Be sure to call point-entered and
6183 ;; point-left-hooks.
6184 (let* ((npoint (prog1 (line-end-position)
6185 (goto-char opoint)))
6186 (inhibit-point-motion-hooks nil))
6187 (goto-char npoint)))
6189 ;; If we did not move up as far as desired,
6190 ;; at least go to beginning of line.
6191 (let* ((npoint (prog1 (line-beginning-position)
6192 (goto-char opoint)))
6193 (inhibit-point-motion-hooks nil))
6194 (goto-char npoint)))
6196 (line-move-finish (or goal-column temporary-goal-column)
6197 opoint (> orig-arg 0)))))))
6199 (defun line-move-finish (column opoint forward)
6202 ;; Set REPEAT to t to repeat the whole thing.
6207 (line-beg (line-beginning-position))
6209 ;; Compute the end of the line
6210 ;; ignoring effectively invisible newlines.
6212 ;; Like end-of-line but ignores fields.
6213 (skip-chars-forward "^\n")
6214 (while (and (not (eobp)) (invisible-p (point)))
6215 (goto-char (next-char-property-change (point)))
6216 (skip-chars-forward "^\n"))
6219 ;; Move to the desired column.
6220 (line-move-to-column (truncate column))
6222 ;; Corner case: suppose we start out in a field boundary in
6223 ;; the middle of a continued line. When we get to
6224 ;; line-move-finish, point is at the start of a new *screen*
6225 ;; line but the same text line; then line-move-to-column would
6226 ;; move us backwards. Test using C-n with point on the "x" in
6227 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6234 ;; Process intangibility within a line.
6235 ;; With inhibit-point-motion-hooks bound to nil, a call to
6236 ;; goto-char moves point past intangible text.
6238 ;; However, inhibit-point-motion-hooks controls both the
6239 ;; intangibility and the point-entered/point-left hooks. The
6240 ;; following hack avoids calling the point-* hooks
6241 ;; unnecessarily. Note that we move *forward* past intangible
6242 ;; text when the initial and final points are the same.
6244 (let ((inhibit-point-motion-hooks nil))
6247 ;; If intangibility moves us to a different (later) place
6248 ;; in the same line, use that as the destination.
6249 (if (<= (point) line-end)
6251 ;; If that position is "too late",
6252 ;; try the previous allowable position.
6256 ;; If going forward, don't accept the previous
6257 ;; allowable position if it is before the target line.
6258 (< line-beg (point))
6259 ;; If going backward, don't accept the previous
6260 ;; allowable position if it is still after the target line.
6261 (<= (point) line-end))
6263 ;; As a last resort, use the end of the line.
6264 (setq new line-end))))
6266 ;; Now move to the updated destination, processing fields
6267 ;; as well as intangibility.
6269 (let ((inhibit-point-motion-hooks nil))
6271 ;; Ignore field boundaries if the initial and final
6272 ;; positions have the same `field' property, even if the
6273 ;; fields are non-contiguous. This seems to be "nicer"
6274 ;; behavior in many situations.
6275 (if (eq (get-char-property new 'field)
6276 (get-char-property opoint 'field))
6278 (constrain-to-field new opoint t t
6279 'inhibit-line-move-field-capture))))
6281 ;; If all this moved us to a different line,
6282 ;; retry everything within that new line.
6283 (when (or (< (point) line-beg) (> (point) line-end))
6284 ;; Repeat the intangibility and field processing.
6285 (setq repeat t))))))
6287 (defun line-move-to-column (col)
6288 "Try to find column COL, considering invisibility.
6289 This function works only in certain cases,
6290 because what we really need is for `move-to-column'
6291 and `current-column' to be able to ignore invisible text."
6294 (move-to-column col))
6296 (when (and line-move-ignore-invisible
6297 (not (bolp)) (invisible-p (1- (point))))
6298 (let ((normal-location (point))
6299 (normal-column (current-column)))
6300 ;; If the following character is currently invisible,
6301 ;; skip all characters with that same `invisible' property value.
6302 (while (and (not (eobp))
6303 (invisible-p (point)))
6304 (goto-char (next-char-property-change (point))))
6305 ;; Have we advanced to a larger column position?
6306 (if (> (current-column) normal-column)
6307 ;; We have made some progress towards the desired column.
6308 ;; See if we can make any further progress.
6309 (line-move-to-column (+ (current-column) (- col normal-column)))
6310 ;; Otherwise, go to the place we originally found
6311 ;; and move back over invisible text.
6312 ;; that will get us to the same place on the screen
6313 ;; but with a more reasonable buffer position.
6314 (goto-char normal-location)
6316 ;; We want the real line beginning, so it's consistent
6317 ;; with bolp below, otherwise we might infloop.
6318 (let ((inhibit-field-text-motion t))
6319 (line-beginning-position))))
6320 (while (and (not (bolp)) (invisible-p (1- (point))))
6321 (goto-char (previous-char-property-change (point) line-beg))))))))
6323 (defun move-end-of-line (arg)
6324 "Move point to end of current line as displayed.
6325 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6326 If point reaches the beginning or end of buffer, it stops there.
6328 To ignore the effects of the `intangible' text or overlay
6329 property, bind `inhibit-point-motion-hooks' to t.
6330 If there is an image in the current line, this function
6331 disregards newlines that are part of the text on which the image
6334 (or arg (setq arg 1))
6339 (let ((goal-column 0)
6340 (line-move-visual nil))
6341 (and (line-move arg t)
6342 ;; With bidi reordering, we may not be at bol,
6343 ;; so make sure we are.
6344 (skip-chars-backward "^\n")
6347 (while (and (not (bobp)) (invisible-p (1- (point))))
6348 (goto-char (previous-single-char-property-change
6349 (point) 'invisible)))
6353 (if (and (> (point) newpos)
6354 (eq (preceding-char) ?\n))
6356 (if (and (> (point) newpos) (not (eobp))
6357 (not (eq (following-char) ?\n)))
6358 ;; If we skipped something intangible and now we're not
6359 ;; really at eol, keep going.
6363 (defun move-beginning-of-line (arg)
6364 "Move point to beginning of current line as displayed.
6365 \(If there's an image in the line, this disregards newlines
6366 which are part of the text that the image rests on.)
6368 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6369 If point reaches the beginning or end of buffer, it stops there.
6370 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6372 (or arg (setq arg 1))
6374 (let ((orig (point))
6375 first-vis first-vis-field-value)
6377 ;; Move by lines, if ARG is not 1 (the default).
6379 (let ((line-move-visual nil))
6380 (line-move (1- arg) t)))
6382 ;; Move to beginning-of-line, ignoring fields and invisible text.
6383 (skip-chars-backward "^\n")
6384 (while (and (not (bobp)) (invisible-p (1- (point))))
6385 (goto-char (previous-char-property-change (point)))
6386 (skip-chars-backward "^\n"))
6388 ;; Now find first visible char in the line.
6389 (while (and (< (point) orig) (invisible-p (point)))
6390 (goto-char (next-char-property-change (point) orig)))
6391 (setq first-vis (point))
6393 ;; See if fields would stop us from reaching FIRST-VIS.
6394 (setq first-vis-field-value
6395 (constrain-to-field first-vis orig (/= arg 1) t nil))
6397 (goto-char (if (/= first-vis-field-value first-vis)
6398 ;; If yes, obey them.
6399 first-vis-field-value
6400 ;; Otherwise, move to START with attention to fields.
6401 ;; (It is possible that fields never matter in this case.)
6402 (constrain-to-field (point) orig
6403 (/= arg 1) t nil)))))
6406 ;; Many people have said they rarely use this feature, and often type
6407 ;; it by accident. Maybe it shouldn't even be on a key.
6408 (put 'set-goal-column 'disabled t)
6410 (defun set-goal-column (arg)
6411 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6412 Those commands will move to this position in the line moved to
6413 rather than trying to keep the same horizontal position.
6414 With a non-nil argument ARG, clears out the goal column
6415 so that \\[next-line] and \\[previous-line] resume vertical motion.
6416 The goal column is stored in the variable `goal-column'."
6420 (setq goal-column nil)
6421 (message "No goal column"))
6422 (setq goal-column (current-column))
6423 ;; The older method below can be erroneous if `set-goal-column' is bound
6424 ;; to a sequence containing %
6425 ;;(message (substitute-command-keys
6426 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6430 (format "Goal column %d " goal-column)
6431 (substitute-command-keys
6432 "(use \\[set-goal-column] with an arg to unset it)")))
6437 ;;; Editing based on visual lines, as opposed to logical lines.
6439 (defun end-of-visual-line (&optional n)
6440 "Move point to end of current visual line.
6441 With argument N not nil or 1, move forward N - 1 visual lines first.
6442 If point reaches the beginning or end of buffer, it stops there.
6443 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6447 (let ((line-move-visual t))
6448 (line-move (1- n) t)))
6449 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6450 ;; constrain to field boundaries, so we don't either.
6451 (vertical-motion (cons (window-width) 0)))
6453 (defun beginning-of-visual-line (&optional n)
6454 "Move point to beginning of current visual line.
6455 With argument N not nil or 1, move forward N - 1 visual lines first.
6456 If point reaches the beginning or end of buffer, it stops there.
6457 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6460 (let ((opoint (point)))
6462 (let ((line-move-visual t))
6463 (line-move (1- n) t)))
6465 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6466 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6468 (defun kill-visual-line (&optional arg)
6469 "Kill the rest of the visual line.
6470 With prefix argument ARG, kill that many visual lines from point.
6471 If ARG is negative, kill visual lines backward.
6472 If ARG is zero, kill the text before point on the current visual
6475 If you want to append the killed line to the last killed text,
6476 use \\[append-next-kill] before \\[kill-line].
6478 If the buffer is read-only, Emacs will beep and refrain from deleting
6479 the line, but put the line in the kill ring anyway. This means that
6480 you can use this command to copy text from a read-only buffer.
6481 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6484 ;; Like in `kill-line', it's better to move point to the other end
6485 ;; of the kill before killing.
6486 (let ((opoint (point))
6487 (kill-whole-line (and kill-whole-line (bolp))))
6489 (vertical-motion (prefix-numeric-value arg))
6490 (end-of-visual-line 1)
6491 (if (= (point) opoint)
6493 ;; Skip any trailing whitespace at the end of the visual line.
6494 ;; We used to do this only if `show-trailing-whitespace' is
6495 ;; nil, but that's wrong; the correct thing would be to check
6496 ;; whether the trailing whitespace is highlighted. But, it's
6497 ;; OK to just do this unconditionally.
6498 (skip-chars-forward " \t")))
6499 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6503 (defun next-logical-line (&optional arg try-vscroll)
6504 "Move cursor vertically down ARG lines.
6505 This is identical to `next-line', except that it always moves
6506 by logical lines instead of visual lines, ignoring the value of
6507 the variable `line-move-visual'."
6508 (interactive "^p\np")
6509 (let ((line-move-visual nil))
6511 (next-line arg try-vscroll))))
6513 (defun previous-logical-line (&optional arg try-vscroll)
6514 "Move cursor vertically up ARG lines.
6515 This is identical to `previous-line', except that it always moves
6516 by logical lines instead of visual lines, ignoring the value of
6517 the variable `line-move-visual'."
6518 (interactive "^p\np")
6519 (let ((line-move-visual nil))
6521 (previous-line arg try-vscroll))))
6523 (defgroup visual-line nil
6524 "Editing based on visual lines."
6528 (defvar visual-line-mode-map
6529 (let ((map (make-sparse-keymap)))
6530 (define-key map [remap kill-line] 'kill-visual-line)
6531 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6532 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6533 ;; These keybindings interfere with xterm function keys. Are
6534 ;; there any other suitable bindings?
6535 ;; (define-key map "\M-[" 'previous-logical-line)
6536 ;; (define-key map "\M-]" 'next-logical-line)
6539 (defcustom visual-line-fringe-indicators '(nil nil)
6540 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6541 The value should be a list of the form (LEFT RIGHT), where LEFT
6542 and RIGHT are symbols representing the bitmaps to display, to
6543 indicate wrapped lines, in the left and right fringes respectively.
6544 See also `fringe-indicator-alist'.
6545 The default is not to display fringe indicators for wrapped lines.
6546 This variable does not affect fringe indicators displayed for
6548 :type '(list (choice (const :tag "Hide left indicator" nil)
6549 (const :tag "Left curly arrow" left-curly-arrow)
6550 (symbol :tag "Other bitmap"))
6551 (choice (const :tag "Hide right indicator" nil)
6552 (const :tag "Right curly arrow" right-curly-arrow)
6553 (symbol :tag "Other bitmap")))
6554 :set (lambda (symbol value)
6555 (dolist (buf (buffer-list))
6556 (with-current-buffer buf
6557 (when (and (boundp 'visual-line-mode)
6558 (symbol-value 'visual-line-mode))
6559 (setq fringe-indicator-alist
6560 (cons (cons 'continuation value)
6563 (copy-tree fringe-indicator-alist)))))))
6564 (set-default symbol value)))
6566 (defvar visual-line--saved-state nil)
6568 (define-minor-mode visual-line-mode
6569 "Toggle visual line based editing (Visual Line mode).
6570 With a prefix argument ARG, enable Visual Line mode if ARG is
6571 positive, and disable it otherwise. If called from Lisp, enable
6572 the mode if ARG is omitted or nil.
6574 When Visual Line mode is enabled, `word-wrap' is turned on in
6575 this buffer, and simple editing commands are redefined to act on
6576 visual lines, not logical lines. See Info node `Visual Line
6578 :keymap visual-line-mode-map
6581 (if visual-line-mode
6583 (set (make-local-variable 'visual-line--saved-state) nil)
6584 ;; Save the local values of some variables, to be restored if
6585 ;; visual-line-mode is turned off.
6586 (dolist (var '(line-move-visual truncate-lines
6587 truncate-partial-width-windows
6588 word-wrap fringe-indicator-alist))
6589 (if (local-variable-p var)
6590 (push (cons var (symbol-value var))
6591 visual-line--saved-state)))
6592 (set (make-local-variable 'line-move-visual) t)
6593 (set (make-local-variable 'truncate-partial-width-windows) nil)
6594 (setq truncate-lines nil
6596 fringe-indicator-alist
6597 (cons (cons 'continuation visual-line-fringe-indicators)
6598 fringe-indicator-alist)))
6599 (kill-local-variable 'line-move-visual)
6600 (kill-local-variable 'word-wrap)
6601 (kill-local-variable 'truncate-lines)
6602 (kill-local-variable 'truncate-partial-width-windows)
6603 (kill-local-variable 'fringe-indicator-alist)
6604 (dolist (saved visual-line--saved-state)
6605 (set (make-local-variable (car saved)) (cdr saved)))
6606 (kill-local-variable 'visual-line--saved-state)))
6608 (defun turn-on-visual-line-mode ()
6609 (visual-line-mode 1))
6611 (define-globalized-minor-mode global-visual-line-mode
6612 visual-line-mode turn-on-visual-line-mode)
6615 (defun transpose-chars (arg)
6616 "Interchange characters around point, moving forward one character.
6617 With prefix arg ARG, effect is to take character before point
6618 and drag it forward past ARG other characters (backward if ARG negative).
6619 If no argument and at end of line, the previous two chars are exchanged."
6621 (when (and (null arg) (eolp) (not (bobp))
6622 (not (get-text-property (1- (point)) 'read-only)))
6624 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6626 (defun transpose-words (arg)
6627 "Interchange words around point, leaving point at end of them.
6628 With prefix arg ARG, effect is to take word before or around point
6629 and drag it forward past ARG other words (backward if ARG negative).
6630 If ARG is zero, the words around or after point and around or after mark
6632 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6634 (transpose-subr 'forward-word arg))
6636 (defun transpose-sexps (arg)
6637 "Like \\[transpose-words] but applies to sexps.
6638 Does not work on a sexp that point is in the middle of
6639 if it is a list or string."
6643 ;; Here we should try to simulate the behavior of
6644 ;; (cons (progn (forward-sexp x) (point))
6645 ;; (progn (forward-sexp (- x)) (point)))
6646 ;; Except that we don't want to rely on the second forward-sexp
6647 ;; putting us back to where we want to be, since forward-sexp-function
6648 ;; might do funny things like infix-precedence.
6650 (looking-at "\\sw\\|\\s_")
6652 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6653 ;; Jumping over a symbol. We might be inside it, mind you.
6654 (progn (funcall (if (> arg 0)
6655 'skip-syntax-backward 'skip-syntax-forward)
6657 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6658 ;; Otherwise, we're between sexps. Take a step back before jumping
6659 ;; to make sure we'll obey the same precedence no matter which direction
6661 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6662 (cons (save-excursion (forward-sexp arg) (point))
6663 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6664 (not (zerop (funcall (if (> arg 0)
6665 'skip-syntax-forward
6666 'skip-syntax-backward)
6671 (defun transpose-lines (arg)
6672 "Exchange current line and previous line, leaving point after both.
6673 With argument ARG, takes previous line and moves it past ARG lines.
6674 With argument 0, interchanges line point is in with line mark is in."
6676 (transpose-subr (function
6680 ;; Move forward over ARG lines,
6681 ;; but create newlines if necessary.
6682 (setq arg (forward-line arg))
6683 (if (/= (preceding-char) ?\n)
6684 (setq arg (1+ arg)))
6687 (forward-line arg))))
6690 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6691 ;; which seems inconsistent with the ARG /= 0 case.
6692 ;; FIXME document SPECIAL.
6693 (defun transpose-subr (mover arg &optional special)
6694 "Subroutine to do the work of transposing objects.
6695 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6696 moves forward by units of the given object (e.g. forward-sentence,
6697 forward-paragraph). If ARG is zero, exchanges the current object
6698 with the one containing mark. If ARG is an integer, moves the
6699 current object past ARG following (if ARG is positive) or
6700 preceding (if ARG is negative) objects, leaving point after the
6702 (let ((aux (if special mover
6704 (cons (progn (funcall mover x) (point))
6705 (progn (funcall mover (- x)) (point))))))
6710 (setq pos1 (funcall aux 1))
6711 (goto-char (or (mark) (error "No mark set in this buffer")))
6712 (setq pos2 (funcall aux 1))
6713 (transpose-subr-1 pos1 pos2))
6714 (exchange-point-and-mark))
6716 (setq pos1 (funcall aux -1))
6717 (setq pos2 (funcall aux arg))
6718 (transpose-subr-1 pos1 pos2)
6719 (goto-char (car pos2)))
6721 (setq pos1 (funcall aux -1))
6722 (goto-char (car pos1))
6723 (setq pos2 (funcall aux arg))
6724 (transpose-subr-1 pos1 pos2)
6725 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6727 (defun transpose-subr-1 (pos1 pos2)
6728 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6729 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6730 (when (> (car pos1) (car pos2))
6732 (setq pos1 pos2 pos2 swap)))
6733 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6734 (atomic-change-group
6735 ;; This sequence of insertions attempts to preserve marker
6736 ;; positions at the start and end of the transposed objects.
6737 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6738 (len1 (- (cdr pos1) (car pos1)))
6739 (len2 (length word))
6740 (boundary (make-marker)))
6741 (set-marker boundary (car pos2))
6742 (goto-char (cdr pos1))
6743 (insert-before-markers word)
6744 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6745 (goto-char boundary)
6747 (goto-char (+ boundary len1))
6748 (delete-region (point) (+ (point) len2))
6749 (set-marker boundary nil))))
6751 (defun backward-word (&optional arg)
6752 "Move backward until encountering the beginning of a word.
6753 With argument ARG, do this that many times.
6754 If ARG is omitted or nil, move point backward one word.
6756 The word boundaries are normally determined by the buffer's syntax
6757 table, but `find-word-boundary-function-table', such as set up
6758 by `subword-mode', can change that. If a Lisp program needs to
6759 move by words determined strictly by the syntax table, it should
6760 use `backward-word-strictly' instead."
6762 (forward-word (- (or arg 1))))
6764 (defun mark-word (&optional arg allow-extend)
6765 "Set mark ARG words away from point.
6766 The place mark goes is the same place \\[forward-word] would
6767 move to with the same argument.
6768 Interactively, if this command is repeated
6769 or (in Transient Mark mode) if the mark is active,
6770 it marks the next ARG words after the ones already marked."
6771 (interactive "P\np")
6772 (cond ((and allow-extend
6773 (or (and (eq last-command this-command) (mark t))
6775 (setq arg (if arg (prefix-numeric-value arg)
6776 (if (< (mark) (point)) -1 1)))
6785 (forward-word (prefix-numeric-value arg))
6789 (defun kill-word (arg)
6790 "Kill characters forward until encountering the end of a word.
6791 With argument ARG, do this that many times."
6793 (kill-region (point) (progn (forward-word arg) (point))))
6795 (defun backward-kill-word (arg)
6796 "Kill characters backward until encountering the beginning of a word.
6797 With argument ARG, do this that many times."
6799 (kill-word (- arg)))
6801 (defun current-word (&optional strict really-word)
6802 "Return the symbol or word that point is on (or a nearby one) as a string.
6803 The return value includes no text properties.
6804 If optional arg STRICT is non-nil, return nil unless point is within
6805 or adjacent to a symbol or word. In all cases the value can be nil
6806 if there is no word nearby.
6807 The function, belying its name, normally finds a symbol.
6808 If optional arg REALLY-WORD is non-nil, it finds just a word."
6810 (let* ((oldpoint (point)) (start (point)) (end (point))
6811 (syntaxes (if really-word "w" "w_"))
6812 (not-syntaxes (concat "^" syntaxes)))
6813 (skip-syntax-backward syntaxes) (setq start (point))
6814 (goto-char oldpoint)
6815 (skip-syntax-forward syntaxes) (setq end (point))
6816 (when (and (eq start oldpoint) (eq end oldpoint)
6817 ;; Point is neither within nor adjacent to a word.
6819 ;; Look for preceding word in same line.
6820 (skip-syntax-backward not-syntaxes (line-beginning-position))
6822 ;; No preceding word in same line.
6823 ;; Look for following word in same line.
6825 (skip-syntax-forward not-syntaxes (line-end-position))
6826 (setq start (point))
6827 (skip-syntax-forward syntaxes)
6830 (skip-syntax-backward syntaxes)
6831 (setq start (point))))
6832 ;; If we found something nonempty, return it as a string.
6833 (unless (= start end)
6834 (buffer-substring-no-properties start end)))))
6836 (defcustom fill-prefix nil
6837 "String for filling to insert at front of new line, or nil for none."
6838 :type '(choice (const :tag "None" nil)
6841 (make-variable-buffer-local 'fill-prefix)
6842 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6844 (defcustom auto-fill-inhibit-regexp nil
6845 "Regexp to match lines which should not be auto-filled."
6846 :type '(choice (const :tag "None" nil)
6850 (defun do-auto-fill ()
6851 "The default value for `normal-auto-fill-function'.
6852 This is the default auto-fill function, some major modes use a different one.
6853 Returns t if it really did any work."
6854 (let (fc justify give-up
6855 (fill-prefix fill-prefix))
6856 (if (or (not (setq justify (current-justification)))
6857 (null (setq fc (current-fill-column)))
6858 (and (eq justify 'left)
6859 (<= (current-column) fc))
6860 (and auto-fill-inhibit-regexp
6861 (save-excursion (beginning-of-line)
6862 (looking-at auto-fill-inhibit-regexp))))
6863 nil ;; Auto-filling not required
6864 (if (memq justify '(full center right))
6865 (save-excursion (unjustify-current-line)))
6867 ;; Choose a fill-prefix automatically.
6868 (when (and adaptive-fill-mode
6869 (or (null fill-prefix) (string= fill-prefix "")))
6871 (fill-context-prefix
6872 (save-excursion (fill-forward-paragraph -1) (point))
6873 (save-excursion (fill-forward-paragraph 1) (point)))))
6874 (and prefix (not (equal prefix ""))
6875 ;; Use auto-indentation rather than a guessed empty prefix.
6876 (not (and fill-indent-according-to-mode
6877 (string-match "\\`[ \t]*\\'" prefix)))
6878 (setq fill-prefix prefix))))
6880 (while (and (not give-up) (> (current-column) fc))
6881 ;; Determine where to split the line.
6886 (setq after-prefix (point))
6888 (looking-at (regexp-quote fill-prefix))
6889 (setq after-prefix (match-end 0)))
6890 (move-to-column (1+ fc))
6891 (fill-move-to-break-point after-prefix)
6894 ;; See whether the place we found is any good.
6896 (goto-char fill-point)
6898 ;; There is no use breaking at end of line.
6899 (save-excursion (skip-chars-forward " ") (eolp))
6900 ;; It is futile to split at the end of the prefix
6901 ;; since we would just insert the prefix again.
6902 (and after-prefix (<= (point) after-prefix))
6903 ;; Don't split right after a comment starter
6904 ;; since we would just make another comment starter.
6905 (and comment-start-skip
6906 (let ((limit (point)))
6908 (and (re-search-forward comment-start-skip
6910 (eq (point) limit))))))
6911 ;; No good place to break => stop trying.
6913 ;; Ok, we have a useful place to break the line. Do it.
6914 (let ((prev-column (current-column)))
6915 ;; If point is at the fill-point, do not `save-excursion'.
6916 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6917 ;; point will end up before it rather than after it.
6919 (skip-chars-backward " \t")
6920 (= (point) fill-point))
6921 (default-indent-new-line t)
6923 (goto-char fill-point)
6924 (default-indent-new-line t)))
6925 ;; Now do justification, if required
6926 (if (not (eq justify 'left))
6929 (justify-current-line justify nil t)))
6930 ;; If making the new line didn't reduce the hpos of
6931 ;; the end of the line, then give up now;
6932 ;; trying again will not help.
6933 (if (>= (current-column) prev-column)
6934 (setq give-up t))))))
6935 ;; Justify last line.
6936 (justify-current-line justify t t)
6939 (defvar comment-line-break-function 'comment-indent-new-line
6940 "Mode-specific function which line breaks and continues a comment.
6941 This function is called during auto-filling when a comment syntax
6943 The function should take a single optional argument, which is a flag
6944 indicating whether it should use soft newlines.")
6946 (defun default-indent-new-line (&optional soft)
6947 "Break line at point and indent.
6948 If a comment syntax is defined, call `comment-indent-new-line'.
6950 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6951 unless optional argument SOFT is non-nil."
6954 (funcall comment-line-break-function soft)
6955 ;; Insert the newline before removing empty space so that markers
6956 ;; get preserved better.
6957 (if soft (insert-and-inherit ?\n) (newline 1))
6958 (save-excursion (forward-char -1) (delete-horizontal-space))
6959 (delete-horizontal-space)
6961 (if (and fill-prefix (not adaptive-fill-mode))
6962 ;; Blindly trust a non-adaptive fill-prefix.
6964 (indent-to-left-margin)
6965 (insert-before-markers-and-inherit fill-prefix))
6968 ;; If there's an adaptive prefix, use it unless we're inside
6969 ;; a comment and the prefix is not a comment starter.
6971 (indent-to-left-margin)
6972 (insert-and-inherit fill-prefix))
6973 ;; If we're not inside a comment, just try to indent.
6974 (t (indent-according-to-mode))))))
6976 (defvar normal-auto-fill-function 'do-auto-fill
6977 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6978 Some major modes set this.")
6980 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6981 ;; `functions' and `hooks' are usually unsafe to set, but setting
6982 ;; auto-fill-function to nil in a file-local setting is safe and
6983 ;; can be useful to prevent auto-filling.
6984 (put 'auto-fill-function 'safe-local-variable 'null)
6986 (define-minor-mode auto-fill-mode
6987 "Toggle automatic line breaking (Auto Fill mode).
6988 With a prefix argument ARG, enable Auto Fill mode if ARG is
6989 positive, and disable it otherwise. If called from Lisp, enable
6990 the mode if ARG is omitted or nil.
6992 When Auto Fill mode is enabled, inserting a space at a column
6993 beyond `current-fill-column' automatically breaks the line at a
6996 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6999 The value of `normal-auto-fill-function' specifies the function to use
7000 for `auto-fill-function' when turning Auto Fill mode on."
7001 :variable (auto-fill-function
7002 . (lambda (v) (setq auto-fill-function
7003 (if v normal-auto-fill-function)))))
7005 ;; This holds a document string used to document auto-fill-mode.
7006 (defun auto-fill-function ()
7007 "Automatically break line at a previous space, in insertion of text."
7010 (defun turn-on-auto-fill ()
7011 "Unconditionally turn on Auto Fill mode."
7014 (defun turn-off-auto-fill ()
7015 "Unconditionally turn off Auto Fill mode."
7016 (auto-fill-mode -1))
7018 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7020 (defun set-fill-column (arg)
7021 "Set `fill-column' to specified argument.
7022 Use \\[universal-argument] followed by a number to specify a column.
7023 Just \\[universal-argument] as argument means to use the current column."
7025 (list (or current-prefix-arg
7026 ;; We used to use current-column silently, but C-x f is too easily
7027 ;; typed as a typo for C-x C-f, so we turned it into an error and
7028 ;; now an interactive prompt.
7029 (read-number "Set fill-column to: " (current-column)))))
7031 (setq arg (current-column)))
7032 (if (not (integerp arg))
7033 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7034 (error "set-fill-column requires an explicit argument")
7035 (message "Fill column set to %d (was %d)" arg fill-column)
7036 (setq fill-column arg)))
7038 (defun set-selective-display (arg)
7039 "Set `selective-display' to ARG; clear it if no arg.
7040 When the value of `selective-display' is a number > 0,
7041 lines whose indentation is >= that value are not displayed.
7042 The variable `selective-display' has a separate value for each buffer."
7044 (if (eq selective-display t)
7045 (error "selective-display already in use for marked lines"))
7048 (narrow-to-region (point-min) (point))
7049 (goto-char (window-start))
7050 (vertical-motion (window-height)))))
7051 (setq selective-display
7052 (and arg (prefix-numeric-value arg)))
7053 (recenter current-vpos))
7054 (set-window-start (selected-window) (window-start))
7055 (princ "selective-display set to " t)
7056 (prin1 selective-display t)
7059 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7061 (defun toggle-truncate-lines (&optional arg)
7062 "Toggle truncating of long lines for the current buffer.
7063 When truncating is off, long lines are folded.
7064 With prefix argument ARG, truncate long lines if ARG is positive,
7065 otherwise fold them. Note that in side-by-side windows, this
7066 command has no effect if `truncate-partial-width-windows' is
7069 (setq truncate-lines
7071 (not truncate-lines)
7072 (> (prefix-numeric-value arg) 0)))
7073 (force-mode-line-update)
7074 (unless truncate-lines
7075 (let ((buffer (current-buffer)))
7076 (walk-windows (lambda (window)
7077 (if (eq buffer (window-buffer window))
7078 (set-window-hscroll window 0)))
7080 (message "Truncate long lines %s"
7081 (if truncate-lines "enabled" "disabled")))
7083 (defun toggle-word-wrap (&optional arg)
7084 "Toggle whether to use word-wrapping for continuation lines.
7085 With prefix argument ARG, wrap continuation lines at word boundaries
7086 if ARG is positive, otherwise wrap them at the right screen edge.
7087 This command toggles the value of `word-wrap'. It has no effect
7088 if long lines are truncated."
7093 (> (prefix-numeric-value arg) 0)))
7094 (force-mode-line-update)
7095 (message "Word wrapping %s"
7096 (if word-wrap "enabled" "disabled")))
7098 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7099 "The string displayed in the mode line when in overwrite mode.")
7100 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7101 "The string displayed in the mode line when in binary overwrite mode.")
7103 (define-minor-mode overwrite-mode
7104 "Toggle Overwrite mode.
7105 With a prefix argument ARG, enable Overwrite 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 When Overwrite mode is enabled, printing characters typed in
7110 replace existing text on a one-for-one basis, rather than pushing
7111 it to the right. At the end of a line, such characters extend
7112 the line. Before a tab, such characters insert until the tab is
7113 filled in. \\[quoted-insert] still inserts characters in
7114 overwrite mode; this is supposed to make it easier to insert
7115 characters when necessary."
7116 :variable (overwrite-mode
7117 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7119 (define-minor-mode binary-overwrite-mode
7120 "Toggle Binary Overwrite mode.
7121 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7122 is positive, and disable it otherwise. If called from Lisp,
7123 enable the mode if ARG is omitted or nil.
7125 When Binary Overwrite mode is enabled, printing characters typed
7126 in replace existing text. Newlines are not treated specially, so
7127 typing at the end of a line joins the line to the next, with the
7128 typed character between them. Typing before a tab character
7129 simply replaces the tab with the character typed.
7130 \\[quoted-insert] replaces the text at the cursor, just as
7131 ordinary typing characters do.
7133 Note that Binary Overwrite mode is not its own minor mode; it is
7134 a specialization of overwrite mode, entered by setting the
7135 `overwrite-mode' variable to `overwrite-mode-binary'."
7136 :variable (overwrite-mode
7137 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7139 (define-minor-mode line-number-mode
7140 "Toggle line number display in the mode line (Line Number mode).
7141 With a prefix argument ARG, enable Line Number mode if ARG is
7142 positive, and disable it otherwise. If called from Lisp, enable
7143 the mode if ARG is omitted or nil.
7145 Line numbers do not appear for very large buffers and buffers
7146 with very long lines; see variables `line-number-display-limit'
7147 and `line-number-display-limit-width'."
7148 :init-value t :global t :group 'mode-line)
7150 (define-minor-mode column-number-mode
7151 "Toggle column number display in the mode line (Column Number mode).
7152 With a prefix argument ARG, enable Column Number mode if ARG is
7153 positive, and disable it otherwise.
7155 If called from Lisp, enable the mode if ARG is omitted or nil."
7156 :global t :group 'mode-line)
7158 (define-minor-mode size-indication-mode
7159 "Toggle buffer size display in the mode line (Size Indication mode).
7160 With a prefix argument ARG, enable Size Indication mode if ARG is
7161 positive, and disable it otherwise.
7163 If called from Lisp, enable the mode if ARG is omitted or nil."
7164 :global t :group 'mode-line)
7166 (define-minor-mode auto-save-mode
7167 "Toggle auto-saving in the current buffer (Auto Save mode).
7168 With a prefix argument ARG, enable Auto Save mode if ARG is
7169 positive, and disable it otherwise.
7171 If called from Lisp, enable the mode if ARG is omitted or nil."
7172 :variable ((and buffer-auto-save-file-name
7173 ;; If auto-save is off because buffer has shrunk,
7174 ;; then toggling should turn it on.
7175 (>= buffer-saved-size 0))
7177 (setq buffer-auto-save-file-name
7180 ((and buffer-file-name auto-save-visited-file-name
7181 (not buffer-read-only))
7183 (t (make-auto-save-file-name))))))
7184 ;; If -1 was stored here, to temporarily turn off saving,
7186 (and (< buffer-saved-size 0)
7187 (setq buffer-saved-size 0)))
7189 (defgroup paren-blinking nil
7190 "Blinking matching of parens and expressions."
7191 :prefix "blink-matching-"
7192 :group 'paren-matching)
7194 (defcustom blink-matching-paren t
7195 "Non-nil means show matching open-paren when close-paren is inserted.
7196 If t, highlight the paren. If `jump', briefly move cursor to its
7197 position. If `jump-offscreen', move cursor there even if the
7198 position is off screen. With any other non-nil value, the
7199 off-screen position of the opening paren will be shown in the
7202 (const :tag "Disable" nil)
7203 (const :tag "Highlight" t)
7204 (const :tag "Move cursor" jump)
7205 (const :tag "Move cursor, even if off screen" jump-offscreen))
7206 :group 'paren-blinking)
7208 (defcustom blink-matching-paren-on-screen t
7209 "Non-nil means show matching open-paren when it is on screen.
7210 If nil, don't show it (but the open-paren can still be shown
7211 in the echo area when it is off screen).
7213 This variable has no effect if `blink-matching-paren' is nil.
7214 \(In that case, the open-paren is never shown.)
7215 It is also ignored if `show-paren-mode' is enabled."
7217 :group 'paren-blinking)
7219 (defcustom blink-matching-paren-distance (* 100 1024)
7220 "If non-nil, maximum distance to search backwards for matching open-paren.
7221 If nil, search stops at the beginning of the accessible portion of the buffer."
7222 :version "23.2" ; 25->100k
7223 :type '(choice (const nil) integer)
7224 :group 'paren-blinking)
7226 (defcustom blink-matching-delay 1
7227 "Time in seconds to delay after showing a matching paren."
7229 :group 'paren-blinking)
7231 (defcustom blink-matching-paren-dont-ignore-comments nil
7232 "If nil, `blink-matching-paren' ignores comments.
7233 More precisely, when looking for the matching parenthesis,
7234 it skips the contents of comments that end before point."
7236 :group 'paren-blinking)
7238 (defun blink-matching-check-mismatch (start end)
7239 "Return whether or not START...END are matching parens.
7240 END is the current point and START is the blink position.
7241 START might be nil if no matching starter was found.
7242 Returns non-nil if we find there is a mismatch."
7243 (let* ((end-syntax (syntax-after (1- end)))
7244 (matching-paren (and (consp end-syntax)
7245 (eq (syntax-class end-syntax) 5)
7247 ;; For self-matched chars like " and $, we can't know when they're
7248 ;; mismatched or unmatched, so we can only do it for parens.
7249 (when matching-paren
7252 (eq (char-after start) matching-paren)
7253 ;; The cdr might hold a new paren-class info rather than
7254 ;; a matching-char info, in which case the two CDRs
7256 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7258 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7259 "Function to check parentheses mismatches.
7260 The function takes two arguments (START and END) where START is the
7261 position just before the opening token and END is the position right after.
7262 START can be nil, if it was not found.
7263 The function should return non-nil if the two tokens do not match.")
7265 (defvar blink-matching--overlay
7266 (let ((ol (make-overlay (point) (point) nil t)))
7267 (overlay-put ol 'face 'show-paren-match)
7270 "Overlay used to highlight the matching paren.")
7272 (defun blink-matching-open ()
7273 "Momentarily highlight the beginning of the sexp before point."
7275 (when (and (not (bobp))
7276 blink-matching-paren)
7277 (let* ((oldpos (point))
7278 (message-log-max nil) ; Don't log messages about paren matching.
7282 (if blink-matching-paren-distance
7284 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7285 (- (point) blink-matching-paren-distance))
7287 (let ((parse-sexp-ignore-comments
7288 (and parse-sexp-ignore-comments
7289 (not blink-matching-paren-dont-ignore-comments))))
7292 (syntax-propertize (point))
7294 ;; backward-sexp skips backward over prefix chars,
7295 ;; so move back to the matching paren.
7296 (while (and (< (point) (1- oldpos))
7297 (let ((code (syntax-after (point))))
7298 (or (eq (syntax-class code) 6)
7299 (eq (logand 1048576 (car code))
7304 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7309 (minibuffer-message "Mismatched parentheses")
7310 (message "Mismatched parentheses"))
7312 (minibuffer-message "No matching parenthesis found")
7313 (message "No matching parenthesis found"))))
7314 ((not blinkpos) nil)
7316 (eq blink-matching-paren 'jump-offscreen)
7317 (pos-visible-in-window-p blinkpos))
7318 ;; Matching open within window, temporarily move to or highlight
7319 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7321 (and blink-matching-paren-on-screen
7322 (not show-paren-mode)
7323 (if (memq blink-matching-paren '(jump jump-offscreen))
7325 (goto-char blinkpos)
7326 (sit-for blink-matching-delay))
7329 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7331 (sit-for blink-matching-delay))
7332 (delete-overlay blink-matching--overlay)))))
7334 (let ((open-paren-line-string
7336 (goto-char blinkpos)
7337 ;; Show what precedes the open in its line, if anything.
7339 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7340 (buffer-substring (line-beginning-position)
7342 ;; Show what follows the open in its line, if anything.
7345 (skip-chars-forward " \t")
7347 (buffer-substring blinkpos
7348 (line-end-position)))
7349 ;; Otherwise show the previous nonblank line,
7351 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7353 (buffer-substring (progn
7354 (skip-chars-backward "\n \t")
7355 (line-beginning-position))
7356 (progn (end-of-line)
7357 (skip-chars-backward " \t")
7359 ;; Replace the newline and other whitespace with `...'.
7361 (buffer-substring blinkpos (1+ blinkpos))))
7362 ;; There is nothing to show except the char itself.
7363 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7366 (substring-no-properties open-paren-line-string))))))))
7368 (defvar blink-paren-function 'blink-matching-open
7369 "Function called, if non-nil, whenever a close parenthesis is inserted.
7370 More precisely, a char with closeparen syntax is self-inserted.")
7372 (defun blink-paren-post-self-insert-function ()
7373 (when (and (eq (char-before) last-command-event) ; Sanity check.
7374 (memq (char-syntax last-command-event) '(?\) ?\$))
7375 blink-paren-function
7376 (not executing-kbd-macro)
7377 (not noninteractive)
7378 ;; Verify an even number of quoting characters precede the close.
7379 ;; FIXME: Also check if this parenthesis closes a comment as
7380 ;; can happen in Pascal and SML.
7381 (= 1 (logand 1 (- (point)
7384 (skip-syntax-backward "/\\")
7386 (funcall blink-paren-function)))
7388 (put 'blink-paren-post-self-insert-function 'priority 100)
7390 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7391 ;; Most likely, this hook is nil, so this arg doesn't matter,
7392 ;; but I use it as a reminder that this function usually
7393 ;; likes to be run after others since it does
7394 ;; `sit-for'. That's also the reason it get a `priority' prop
7398 ;; This executes C-g typed while Emacs is waiting for a command.
7399 ;; Quitting out of a program does not go through here;
7400 ;; that happens in the QUIT macro at the C code level.
7401 (defun keyboard-quit ()
7402 "Signal a `quit' condition.
7403 During execution of Lisp code, this character causes a quit directly.
7404 At top-level, as an editor command, this simply beeps."
7406 ;; Avoid adding the region to the window selection.
7407 (setq saved-region-selection nil)
7408 (let (select-active-regions)
7410 (if (fboundp 'kmacro-keyboard-quit)
7411 (kmacro-keyboard-quit))
7412 (when completion-in-region-mode
7413 (completion-in-region-mode -1))
7414 ;; Force the next redisplay cycle to remove the "Def" indicator from
7415 ;; all the mode lines.
7416 (if defining-kbd-macro
7417 (force-mode-line-update t))
7418 (setq defining-kbd-macro nil)
7419 (let ((debug-on-quit nil))
7420 (signal 'quit nil)))
7422 (defvar buffer-quit-function nil
7423 "Function to call to \"quit\" the current buffer, or nil if none.
7424 \\[keyboard-escape-quit] calls this function when its more local actions
7425 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7427 (defun keyboard-escape-quit ()
7428 "Exit the current \"mode\" (in a generalized sense of the word).
7429 This command can exit an interactive command such as `query-replace',
7430 can clear out a prefix argument or a region,
7431 can get out of the minibuffer or other recursive edit,
7432 cancel the use of the current buffer (for special-purpose buffers),
7433 or go back to just one window (by deleting all but the selected window)."
7435 (cond ((eq last-command 'mode-exited) nil)
7438 ((> (minibuffer-depth) 0)
7439 (abort-recursive-edit))
7442 ((> (recursion-depth) 0)
7443 (exit-recursive-edit))
7444 (buffer-quit-function
7445 (funcall buffer-quit-function))
7446 ((not (one-window-p t))
7447 (delete-other-windows))
7448 ((string-match "^ \\*" (buffer-name (current-buffer)))
7451 (defun play-sound-file (file &optional volume device)
7452 "Play sound stored in FILE.
7453 VOLUME and DEVICE correspond to the keywords of the sound
7454 specification for `play-sound'."
7455 (interactive "fPlay sound file: ")
7456 (let ((sound (list :file file)))
7458 (plist-put sound :volume volume))
7460 (plist-put sound :device device))
7462 (play-sound sound)))
7465 (defcustom read-mail-command 'rmail
7466 "Your preference for a mail reading package.
7467 This is used by some keybindings which support reading mail.
7468 See also `mail-user-agent' concerning sending mail."
7469 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7470 (function-item :tag "Gnus" :format "%t\n" gnus)
7471 (function-item :tag "Emacs interface to MH"
7472 :format "%t\n" mh-rmail)
7473 (function :tag "Other"))
7477 (defcustom mail-user-agent 'message-user-agent
7478 "Your preference for a mail composition package.
7479 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7480 outgoing email message. This variable lets you specify which
7481 mail-sending package you prefer.
7483 Valid values include:
7485 `message-user-agent' -- use the Message package.
7486 See Info node `(message)'.
7487 `sendmail-user-agent' -- use the Mail package.
7488 See Info node `(emacs)Sending Mail'.
7489 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7490 See Info node `(mh-e)'.
7491 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7492 paraphernalia if Gnus is running, particularly
7493 the Gcc: header for archiving.
7495 Additional valid symbols may be available; check with the author of
7496 your package for details. The function should return non-nil if it
7499 See also `read-mail-command' concerning reading mail."
7500 :type '(radio (function-item :tag "Message package"
7503 (function-item :tag "Mail package"
7505 sendmail-user-agent)
7506 (function-item :tag "Emacs interface to MH"
7509 (function-item :tag "Message with full Gnus features"
7512 (function :tag "Other"))
7513 :version "23.2" ; sendmail->message
7516 (defcustom compose-mail-user-agent-warnings t
7517 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7518 If the value of `mail-user-agent' is the default, and the user
7519 appears to have customizations applying to the old default,
7520 `compose-mail' issues a warning."
7525 (defun rfc822-goto-eoh ()
7526 "If the buffer starts with a mail header, move point to the header's end.
7527 Otherwise, moves to `point-min'.
7528 The end of the header is the start of the next line, if there is one,
7529 else the end of the last line. This function obeys RFC822."
7530 (goto-char (point-min))
7531 (when (re-search-forward
7532 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7533 (goto-char (match-beginning 0))))
7535 ;; Used by Rmail (e.g., rmail-forward).
7536 (defvar mail-encode-mml nil
7537 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7538 the outgoing message before sending it.")
7540 (defun compose-mail (&optional to subject other-headers continue
7541 switch-function yank-action send-actions
7543 "Start composing a mail message to send.
7544 This uses the user's chosen mail composition package
7545 as selected with the variable `mail-user-agent'.
7546 The optional arguments TO and SUBJECT specify recipients
7547 and the initial Subject field, respectively.
7549 OTHER-HEADERS is an alist specifying additional
7550 header fields. Elements look like (HEADER . VALUE) where both
7551 HEADER and VALUE are strings.
7553 CONTINUE, if non-nil, says to continue editing a message already
7554 being composed. Interactively, CONTINUE is the prefix argument.
7556 SWITCH-FUNCTION, if non-nil, is a function to use to
7557 switch to and display the buffer used for mail composition.
7559 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7560 to insert the raw text of the message being replied to.
7561 It has the form (FUNCTION . ARGS). The user agent will apply
7562 FUNCTION to ARGS, to insert the raw text of the original message.
7563 \(The user agent will also run `mail-citation-hook', *after* the
7564 original text has been inserted in this way.)
7566 SEND-ACTIONS is a list of actions to call when the message is sent.
7567 Each action has the form (FUNCTION . ARGS).
7569 RETURN-ACTION, if non-nil, is an action for returning to the
7570 caller. It has the form (FUNCTION . ARGS). The function is
7571 called after the mail has been sent or put aside, and the mail
7574 (list nil nil nil current-prefix-arg))
7576 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7577 ;; from sendmail-user-agent to message-user-agent. Some users may
7578 ;; encounter incompatibilities. This hack tries to detect problems
7579 ;; and warn about them.
7580 (and compose-mail-user-agent-warnings
7581 (eq mail-user-agent 'message-user-agent)
7583 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7584 mail-yank-hooks mail-archive-file-name
7585 mail-default-reply-to mail-mailing-lists
7589 (push var warn-vars)))
7591 (display-warning 'mail
7593 The default mail mode is now Message mode.
7594 You have the following Mail mode variable%s customized:
7595 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7596 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7597 (if (> (length warn-vars) 1) "s" "")
7598 (mapconcat 'symbol-name
7601 (let ((function (get mail-user-agent 'composefunc)))
7602 (funcall function to subject other-headers continue switch-function
7603 yank-action send-actions return-action)))
7605 (defun compose-mail-other-window (&optional to subject other-headers continue
7606 yank-action send-actions
7608 "Like \\[compose-mail], but edit the outgoing message in another window."
7609 (interactive (list nil nil nil current-prefix-arg))
7610 (compose-mail to subject other-headers continue
7611 'switch-to-buffer-other-window yank-action send-actions
7614 (defun compose-mail-other-frame (&optional to subject other-headers continue
7615 yank-action send-actions
7617 "Like \\[compose-mail], but edit the outgoing message in another frame."
7618 (interactive (list nil nil nil current-prefix-arg))
7619 (compose-mail to subject other-headers continue
7620 'switch-to-buffer-other-frame yank-action send-actions
7624 (defvar set-variable-value-history nil
7625 "History of values entered with `set-variable'.
7627 Maximum length of the history list is determined by the value
7628 of `history-length', which see.")
7630 (defun set-variable (variable value &optional make-local)
7631 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7632 VARIABLE should be a user option variable name, a Lisp variable
7633 meant to be customized by users. You should enter VALUE in Lisp syntax,
7634 so if you want VALUE to be a string, you must surround it with doublequotes.
7635 VALUE is used literally, not evaluated.
7637 If VARIABLE has a `variable-interactive' property, that is used as if
7638 it were the arg to `interactive' (which see) to interactively read VALUE.
7640 If VARIABLE has been defined with `defcustom', then the type information
7641 in the definition is used to check that VALUE is valid.
7643 Note that this function is at heart equivalent to the basic `set' function.
7644 For a variable defined with `defcustom', it does not pay attention to
7645 any :set property that the variable might have (if you want that, use
7646 \\[customize-set-variable] instead).
7648 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7650 (let* ((default-var (variable-at-point))
7651 (var (if (custom-variable-p default-var)
7652 (read-variable (format "Set variable (default %s): " default-var)
7654 (read-variable "Set variable: ")))
7655 (minibuffer-help-form '(describe-variable var))
7656 (prop (get var 'variable-interactive))
7657 (obsolete (car (get var 'byte-obsolete-variable)))
7658 (prompt (format "Set %s %s to value: " var
7659 (cond ((local-variable-p var)
7661 ((or current-prefix-arg
7662 (local-variable-if-set-p var))
7667 (message (concat "`%S' is obsolete; "
7668 (if (symbolp obsolete) "use `%S' instead" "%s"))
7672 ;; Use VAR's `variable-interactive' property
7673 ;; as an interactive spec for prompting.
7674 (call-interactively `(lambda (arg)
7677 (read-from-minibuffer prompt nil
7678 read-expression-map t
7679 'set-variable-value-history
7680 (format "%S" (symbol-value var)))))))
7681 (list var val current-prefix-arg)))
7683 (and (custom-variable-p variable)
7684 (not (get variable 'custom-type))
7685 (custom-load-symbol variable))
7686 (let ((type (get variable 'custom-type)))
7688 ;; Match with custom type.
7690 (setq type (widget-convert type))
7691 (unless (widget-apply type :match value)
7692 (user-error "Value `%S' does not match type %S of %S"
7693 value (car type) variable))))
7696 (make-local-variable variable))
7698 (set variable value)
7700 ;; Force a thorough redisplay for the case that the variable
7701 ;; has an effect on the display, like `tab-width' has.
7702 (force-mode-line-update))
7704 ;; Define the major mode for lists of completions.
7706 (defvar completion-list-mode-map
7707 (let ((map (make-sparse-keymap)))
7708 (define-key map [mouse-2] 'choose-completion)
7709 (define-key map [follow-link] 'mouse-face)
7710 (define-key map [down-mouse-2] nil)
7711 (define-key map "\C-m" 'choose-completion)
7712 (define-key map "\e\e\e" 'delete-completion-window)
7713 (define-key map [left] 'previous-completion)
7714 (define-key map [right] 'next-completion)
7715 (define-key map [?\t] 'next-completion)
7716 (define-key map [backtab] 'previous-completion)
7717 (define-key map "q" 'quit-window)
7718 (define-key map "z" 'kill-this-buffer)
7720 "Local map for completion list buffers.")
7722 ;; Completion mode is suitable only for specially formatted data.
7723 (put 'completion-list-mode 'mode-class 'special)
7725 (defvar completion-reference-buffer nil
7726 "Record the buffer that was current when the completion list was requested.
7727 This is a local variable in the completion list buffer.
7728 Initial value is nil to avoid some compiler warnings.")
7730 (defvar completion-no-auto-exit nil
7731 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7732 This also applies to other functions such as `choose-completion'.")
7734 (defvar completion-base-position nil
7735 "Position of the base of the text corresponding to the shown completions.
7736 This variable is used in the *Completions* buffers.
7737 Its value is a list of the form (START END) where START is the place
7738 where the completion should be inserted and END (if non-nil) is the end
7739 of the text to replace. If END is nil, point is used instead.")
7741 (defvar completion-list-insert-choice-function #'completion--replace
7742 "Function to use to insert the text chosen in *Completions*.
7743 Called with three arguments (BEG END TEXT), it should replace the text
7744 between BEG and END with TEXT. Expected to be set buffer-locally
7745 in the *Completions* buffer.")
7747 (defvar completion-base-size nil
7748 "Number of chars before point not involved in completion.
7749 This is a local variable in the completion list buffer.
7750 It refers to the chars in the minibuffer if completing in the
7751 minibuffer, or in `completion-reference-buffer' otherwise.
7752 Only characters in the field at point are included.
7754 If nil, Emacs determines which part of the tail end of the
7755 buffer's text is involved in completion by comparing the text
7757 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7759 (defun delete-completion-window ()
7760 "Delete the completion list window.
7761 Go to the window from which completion was requested."
7763 (let ((buf completion-reference-buffer))
7764 (if (one-window-p t)
7765 (if (window-dedicated-p) (delete-frame))
7766 (delete-window (selected-window))
7767 (if (get-buffer-window buf)
7768 (select-window (get-buffer-window buf))))))
7770 (defun previous-completion (n)
7771 "Move to the previous item in the completion list."
7773 (next-completion (- n)))
7775 (defun next-completion (n)
7776 "Move to the next item in the completion list.
7777 With prefix argument N, move N items (negative N means move backward)."
7779 (let ((beg (point-min)) (end (point-max)))
7780 (while (and (> n 0) (not (eobp)))
7781 ;; If in a completion, move to the end of it.
7782 (when (get-text-property (point) 'mouse-face)
7783 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7784 ;; Move to start of next one.
7785 (unless (get-text-property (point) 'mouse-face)
7786 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7788 (while (and (< n 0) (not (bobp)))
7789 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7790 ;; If in a completion, move to the start of it.
7791 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7792 (goto-char (previous-single-property-change
7793 (point) 'mouse-face nil beg)))
7794 ;; Move to end of the previous completion.
7795 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7796 (goto-char (previous-single-property-change
7797 (point) 'mouse-face nil beg)))
7798 ;; Move to the start of that one.
7799 (goto-char (previous-single-property-change
7800 (point) 'mouse-face nil beg))
7803 (defun choose-completion (&optional event)
7804 "Choose the completion at point.
7805 If EVENT, use EVENT's position to determine the starting position."
7806 (interactive (list last-nonmenu-event))
7807 ;; In case this is run via the mouse, give temporary modes such as
7808 ;; isearch a chance to turn off.
7809 (run-hooks 'mouse-leave-buffer-hook)
7810 (with-current-buffer (window-buffer (posn-window (event-start event)))
7811 (let ((buffer completion-reference-buffer)
7812 (base-size completion-base-size)
7813 (base-position completion-base-position)
7814 (insert-function completion-list-insert-choice-function)
7817 (goto-char (posn-point (event-start event)))
7820 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7821 (setq end (point) beg (1+ (point))))
7823 (get-text-property (1- (point)) 'mouse-face))
7824 (setq end (1- (point)) beg (point)))
7825 (t (error "No completion here")))
7826 (setq beg (previous-single-property-change beg 'mouse-face))
7827 (setq end (or (next-single-property-change end 'mouse-face)
7829 (buffer-substring-no-properties beg end)))))
7831 (unless (buffer-live-p buffer)
7832 (error "Destination buffer is dead"))
7833 (quit-window nil (posn-window (event-start event)))
7835 (with-current-buffer buffer
7836 (choose-completion-string
7840 ;; Someone's using old completion code that doesn't know
7841 ;; about base-position yet.
7842 (list (+ base-size (field-beginning))))
7843 ;; If all else fails, just guess.
7844 (list (choose-completion-guess-base-position choice)))
7845 insert-function)))))
7847 ;; Delete the longest partial match for STRING
7848 ;; that can be found before POINT.
7849 (defun choose-completion-guess-base-position (string)
7851 (let ((opoint (point))
7853 ;; Try moving back by the length of the string.
7854 (goto-char (max (- (point) (length string))
7855 (minibuffer-prompt-end)))
7856 ;; See how far back we were actually able to move. That is the
7857 ;; upper bound on how much we can match and delete.
7858 (setq len (- opoint (point)))
7859 (if completion-ignore-case
7860 (setq string (downcase string)))
7861 (while (and (> len 0)
7862 (let ((tail (buffer-substring (point) opoint)))
7863 (if completion-ignore-case
7864 (setq tail (downcase tail)))
7865 (not (string= tail (substring string 0 len)))))
7870 (defun choose-completion-delete-max-match (string)
7871 (declare (obsolete choose-completion-guess-base-position "23.2"))
7872 (delete-region (choose-completion-guess-base-position string) (point)))
7874 (defvar choose-completion-string-functions nil
7875 "Functions that may override the normal insertion of a completion choice.
7876 These functions are called in order with three arguments:
7877 CHOICE - the string to insert in the buffer,
7878 BUFFER - the buffer in which the choice should be inserted,
7879 BASE-POSITION - where to insert the completion.
7881 If a function in the list returns non-nil, that function is supposed
7882 to have inserted the CHOICE in the BUFFER, and possibly exited
7883 the minibuffer; no further functions will be called.
7885 If all functions in the list return nil, that means to use
7886 the default method of inserting the completion in BUFFER.")
7888 (defun choose-completion-string (choice &optional
7889 buffer base-position insert-function)
7890 "Switch to BUFFER and insert the completion choice CHOICE.
7891 BASE-POSITION says where to insert the completion.
7892 INSERT-FUNCTION says how to insert the completion and falls
7893 back on `completion-list-insert-choice-function' when nil."
7895 ;; If BUFFER is the minibuffer, exit the minibuffer
7896 ;; unless it is reading a file name and CHOICE is a directory,
7897 ;; or completion-no-auto-exit is non-nil.
7899 ;; Some older code may call us passing `base-size' instead of
7900 ;; `base-position'. It's difficult to make any use of `base-size',
7901 ;; so we just ignore it.
7902 (unless (consp base-position)
7903 (message "Obsolete `base-size' passed to choose-completion-string")
7904 (setq base-position nil))
7906 (let* ((buffer (or buffer completion-reference-buffer))
7907 (mini-p (minibufferp buffer)))
7908 ;; If BUFFER is a minibuffer, barf unless it's the currently
7909 ;; active minibuffer.
7911 (not (and (active-minibuffer-window)
7913 (window-buffer (active-minibuffer-window))))))
7914 (error "Minibuffer is not active for completion")
7915 ;; Set buffer so buffer-local choose-completion-string-functions works.
7917 (unless (run-hook-with-args-until-success
7918 'choose-completion-string-functions
7919 ;; The fourth arg used to be `mini-p' but was useless
7920 ;; (since minibufferp can be used on the `buffer' arg)
7921 ;; and indeed unused. The last used to be `base-size', so we
7922 ;; keep it to try and avoid breaking old code.
7923 choice buffer base-position nil)
7924 ;; This remove-text-properties should be unnecessary since `choice'
7925 ;; comes from buffer-substring-no-properties.
7926 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7927 ;; Insert the completion into the buffer where it was requested.
7928 (funcall (or insert-function completion-list-insert-choice-function)
7929 (or (car base-position) (point))
7930 (or (cadr base-position) (point))
7932 ;; Update point in the window that BUFFER is showing in.
7933 (let ((window (get-buffer-window buffer t)))
7934 (set-window-point window (point)))
7935 ;; If completing for the minibuffer, exit it with this choice.
7936 (and (not completion-no-auto-exit)
7937 (minibufferp buffer)
7938 minibuffer-completion-table
7939 ;; If this is reading a file name, and the file name chosen
7940 ;; is a directory, don't exit the minibuffer.
7941 (let* ((result (buffer-substring (field-beginning) (point)))
7943 (completion-boundaries result minibuffer-completion-table
7944 minibuffer-completion-predicate
7946 (if (eq (car bounds) (length result))
7947 ;; The completion chosen leads to a new set of completions
7948 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7949 (let ((mini (active-minibuffer-window)))
7950 (select-window mini)
7951 (when minibuffer-auto-raise
7952 (raise-frame (window-frame mini))))
7953 (exit-minibuffer))))))))
7955 (define-derived-mode completion-list-mode nil "Completion List"
7956 "Major mode for buffers showing lists of possible completions.
7957 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7958 to select the completion near point.
7959 Or click to select one with the mouse.
7961 \\{completion-list-mode-map}"
7962 (set (make-local-variable 'completion-base-size) nil))
7964 (defun completion-list-mode-finish ()
7965 "Finish setup of the completions buffer.
7966 Called from `temp-buffer-show-hook'."
7967 (when (eq major-mode 'completion-list-mode)
7968 (setq buffer-read-only t)))
7970 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7973 ;; Variables and faces used in `completion-setup-function'.
7975 (defcustom completion-show-help t
7976 "Non-nil means show help message in *Completions* buffer."
7981 ;; This function goes in completion-setup-hook, so that it is called
7982 ;; after the text of the completion list buffer is written.
7983 (defun completion-setup-function ()
7984 (let* ((mainbuf (current-buffer))
7986 ;; FIXME: This is a bad hack. We try to set the default-directory
7987 ;; in the *Completions* buffer so that the relative file names
7988 ;; displayed there can be treated as valid file names, independently
7989 ;; from the completion context. But this suffers from many problems:
7990 ;; - It's not clear when the completions are file names. With some
7991 ;; completion tables (e.g. bzr revision specs), the listed
7992 ;; completions can mix file names and other things.
7993 ;; - It doesn't pay attention to possible quoting.
7994 ;; - With fancy completion styles, the code below will not always
7995 ;; find the right base directory.
7996 (if minibuffer-completing-file-name
7997 (file-name-as-directory
7999 (buffer-substring (minibuffer-prompt-end)
8000 (- (point) (or completion-base-size 0))))))))
8001 (with-current-buffer standard-output
8002 (let ((base-size completion-base-size) ;Read before killing localvars.
8003 (base-position completion-base-position)
8004 (insert-fun completion-list-insert-choice-function))
8005 (completion-list-mode)
8006 (set (make-local-variable 'completion-base-size) base-size)
8007 (set (make-local-variable 'completion-base-position) base-position)
8008 (set (make-local-variable 'completion-list-insert-choice-function)
8010 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8011 (if base-dir (setq default-directory base-dir))
8012 ;; Maybe insert help string.
8013 (when completion-show-help
8014 (goto-char (point-min))
8015 (if (display-mouse-p)
8016 (insert "Click on a completion to select it.\n"))
8017 (insert (substitute-command-keys
8018 "In this buffer, type \\[choose-completion] to \
8019 select the completion near point.\n\n"))))))
8021 (add-hook 'completion-setup-hook 'completion-setup-function)
8023 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8024 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8026 (defun switch-to-completions ()
8027 "Select the completion list window."
8029 (let ((window (or (get-buffer-window "*Completions*" 0)
8030 ;; Make sure we have a completions window.
8031 (progn (minibuffer-completion-help)
8032 (get-buffer-window "*Completions*" 0)))))
8034 (select-window window)
8035 ;; In the new buffer, go to the first completion.
8036 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8038 (next-completion 1)))))
8040 ;;; Support keyboard commands to turn on various modifiers.
8042 ;; These functions -- which are not commands -- each add one modifier
8043 ;; to the following event.
8045 (defun event-apply-alt-modifier (_ignore-prompt)
8046 "\\<function-key-map>Add the Alt modifier to the following event.
8047 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8048 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8049 (defun event-apply-super-modifier (_ignore-prompt)
8050 "\\<function-key-map>Add the Super modifier to the following event.
8051 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8052 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8053 (defun event-apply-hyper-modifier (_ignore-prompt)
8054 "\\<function-key-map>Add the Hyper modifier to the following event.
8055 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8056 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8057 (defun event-apply-shift-modifier (_ignore-prompt)
8058 "\\<function-key-map>Add the Shift modifier to the following event.
8059 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8060 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8061 (defun event-apply-control-modifier (_ignore-prompt)
8062 "\\<function-key-map>Add the Ctrl modifier to the following event.
8063 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8064 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8065 (defun event-apply-meta-modifier (_ignore-prompt)
8066 "\\<function-key-map>Add the Meta modifier to the following event.
8067 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8068 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8070 (defun event-apply-modifier (event symbol lshiftby prefix)
8071 "Apply a modifier flag to event EVENT.
8072 SYMBOL is the name of this modifier, as a symbol.
8073 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8074 PREFIX is the string that represents this modifier in an event type symbol."
8076 (cond ((eq symbol 'control)
8077 (if (and (<= (downcase event) ?z)
8078 (>= (downcase event) ?a))
8079 (- (downcase event) ?a -1)
8080 (if (and (<= (downcase event) ?Z)
8081 (>= (downcase event) ?A))
8082 (- (downcase event) ?A -1)
8083 (logior (lsh 1 lshiftby) event))))
8085 (if (and (<= (downcase event) ?z)
8086 (>= (downcase event) ?a))
8088 (logior (lsh 1 lshiftby) event)))
8090 (logior (lsh 1 lshiftby) event)))
8091 (if (memq symbol (event-modifiers event))
8093 (let ((event-type (if (symbolp event) event (car event))))
8094 (setq event-type (intern (concat prefix (symbol-name event-type))))
8097 (cons event-type (cdr event)))))))
8099 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8100 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8101 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8102 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8103 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8104 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8106 ;;;; Keypad support.
8108 ;; Make the keypad keys act like ordinary typing keys. If people add
8109 ;; bindings for the function key symbols, then those bindings will
8110 ;; override these, so this shouldn't interfere with any existing
8113 ;; Also tell read-char how to handle these keys.
8115 (lambda (keypad-normal)
8116 (let ((keypad (nth 0 keypad-normal))
8117 (normal (nth 1 keypad-normal)))
8118 (put keypad 'ascii-character normal)
8119 (define-key function-key-map (vector keypad) (vector normal))))
8120 ;; See also kp-keys bound in bindings.el.
8126 ;; Do the same for various keys that are represented as symbols under
8127 ;; GUIs but naturally correspond to characters.
8138 ;;;; forking a twin copy of a buffer.
8141 (defvar clone-buffer-hook nil
8142 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8144 (defvar clone-indirect-buffer-hook nil
8145 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8147 (defun clone-process (process &optional newname)
8148 "Create a twin copy of PROCESS.
8149 If NEWNAME is nil, it defaults to PROCESS' name;
8150 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8151 If PROCESS is associated with a buffer, the new process will be associated
8152 with the current buffer instead.
8153 Returns nil if PROCESS has already terminated."
8154 (setq newname (or newname (process-name process)))
8155 (if (string-match "<[0-9]+>\\'" newname)
8156 (setq newname (substring newname 0 (match-beginning 0))))
8157 (when (memq (process-status process) '(run stop open))
8158 (let* ((process-connection-type (process-tty-name process))
8160 (if (memq (process-status process) '(open))
8161 (let ((args (process-contact process t)))
8162 (setq args (plist-put args :name newname))
8163 (setq args (plist-put args :buffer
8164 (if (process-buffer process)
8166 (apply 'make-network-process args))
8167 (apply 'start-process newname
8168 (if (process-buffer process) (current-buffer))
8169 (process-command process)))))
8170 (set-process-query-on-exit-flag
8171 new-process (process-query-on-exit-flag process))
8172 (set-process-inherit-coding-system-flag
8173 new-process (process-inherit-coding-system-flag process))
8174 (set-process-filter new-process (process-filter process))
8175 (set-process-sentinel new-process (process-sentinel process))
8176 (set-process-plist new-process (copy-sequence (process-plist process)))
8179 ;; things to maybe add (currently partly covered by `funcall mode'):
8182 (defun clone-buffer (&optional newname display-flag)
8183 "Create and return a twin copy of the current buffer.
8184 Unlike an indirect buffer, the new buffer can be edited
8185 independently of the old one (if it is not read-only).
8186 NEWNAME is the name of the new buffer. It may be modified by
8187 adding or incrementing <N> at the end as necessary to create a
8188 unique buffer name. If nil, it defaults to the name of the
8189 current buffer, with the proper suffix. If DISPLAY-FLAG is
8190 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8191 clone a file-visiting buffer, or a buffer whose major mode symbol
8192 has a non-nil `no-clone' property, results in an error.
8194 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8195 current buffer with appropriate suffix. However, if a prefix
8196 argument is given, then the command prompts for NEWNAME in the
8199 This runs the normal hook `clone-buffer-hook' in the new buffer
8200 after it has been set up properly in other respects."
8203 (if buffer-file-name
8204 (error "Cannot clone a file-visiting buffer"))
8205 (if (get major-mode 'no-clone)
8206 (error "Cannot clone a buffer in %s mode" mode-name))
8207 (list (if current-prefix-arg
8208 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8210 (if buffer-file-name
8211 (error "Cannot clone a file-visiting buffer"))
8212 (if (get major-mode 'no-clone)
8213 (error "Cannot clone a buffer in %s mode" mode-name))
8214 (setq newname (or newname (buffer-name)))
8215 (if (string-match "<[0-9]+>\\'" newname)
8216 (setq newname (substring newname 0 (match-beginning 0))))
8217 (let ((buf (current-buffer))
8221 (mk (if mark-active (mark t)))
8222 (modified (buffer-modified-p))
8224 (lvars (buffer-local-variables))
8225 (process (get-buffer-process (current-buffer)))
8226 (new (generate-new-buffer (or newname (buffer-name)))))
8229 (with-current-buffer new
8230 (insert-buffer-substring buf)))
8231 (with-current-buffer new
8232 (narrow-to-region ptmin ptmax)
8234 (if mk (set-mark mk))
8235 (set-buffer-modified-p modified)
8237 ;; Clone the old buffer's process, if any.
8238 (when process (clone-process process))
8240 ;; Now set up the major mode.
8243 ;; Set up other local variables.
8245 (condition-case () ;in case var is read-only
8248 (set (make-local-variable (car v)) (cdr v)))
8252 ;; Run any hooks (typically set up by the major mode
8253 ;; for cloning to work properly).
8254 (run-hooks 'clone-buffer-hook))
8256 ;; Presumably the current buffer is shown in the selected frame, so
8257 ;; we want to display the clone elsewhere.
8258 (let ((same-window-regexps nil)
8259 (same-window-buffer-names))
8260 (pop-to-buffer new)))
8264 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8265 "Create an indirect buffer that is a twin copy of the current buffer.
8267 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8268 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8269 or if not called with a prefix arg, NEWNAME defaults to the current
8270 buffer's name. The name is modified by adding a `<N>' suffix to it
8271 or by incrementing the N in an existing suffix. Trying to clone a
8272 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8273 property results in an error.
8275 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8276 This is always done when called interactively.
8278 Optional third arg NORECORD non-nil means do not put this buffer at the
8279 front of the list of recently selected ones.
8281 Returns the newly created indirect buffer."
8284 (if (get major-mode 'no-clone-indirect)
8285 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8286 (list (if current-prefix-arg
8287 (read-buffer "Name of indirect buffer: " (current-buffer)))
8289 (if (get major-mode 'no-clone-indirect)
8290 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8291 (setq newname (or newname (buffer-name)))
8292 (if (string-match "<[0-9]+>\\'" newname)
8293 (setq newname (substring newname 0 (match-beginning 0))))
8294 (let* ((name (generate-new-buffer-name newname))
8295 (buffer (make-indirect-buffer (current-buffer) name t)))
8296 (with-current-buffer buffer
8297 (run-hooks 'clone-indirect-buffer-hook))
8299 (pop-to-buffer buffer norecord))
8303 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8304 "Like `clone-indirect-buffer' but display in another window."
8307 (if (get major-mode 'no-clone-indirect)
8308 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8309 (list (if current-prefix-arg
8310 (read-buffer "Name of indirect buffer: " (current-buffer)))
8312 (let ((pop-up-windows t))
8313 (clone-indirect-buffer newname display-flag norecord)))
8316 ;;; Handling of Backspace and Delete keys.
8318 (defcustom normal-erase-is-backspace 'maybe
8319 "Set the default behavior of the Delete and Backspace keys.
8321 If set to t, Delete key deletes forward and Backspace key deletes
8324 If set to nil, both Delete and Backspace keys delete backward.
8326 If set to `maybe' (which is the default), Emacs automatically
8327 selects a behavior. On window systems, the behavior depends on
8328 the keyboard used. If the keyboard has both a Backspace key and
8329 a Delete key, and both are mapped to their usual meanings, the
8330 option's default value is set to t, so that Backspace can be used
8331 to delete backward, and Delete can be used to delete forward.
8333 If not running under a window system, customizing this option
8334 accomplishes a similar effect by mapping C-h, which is usually
8335 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8336 via `keyboard-translate'. The former functionality of C-h is
8337 available on the F1 key. You should probably not use this
8338 setting if you don't have both Backspace, Delete and F1 keys.
8340 Setting this variable with setq doesn't take effect. Programmatically,
8341 call `normal-erase-is-backspace-mode' (which see) instead."
8342 :type '(choice (const :tag "Off" nil)
8343 (const :tag "Maybe" maybe)
8344 (other :tag "On" t))
8345 :group 'editing-basics
8347 :set (lambda (symbol value)
8348 ;; The fboundp is because of a problem with :set when
8349 ;; dumping Emacs. It doesn't really matter.
8350 (if (fboundp 'normal-erase-is-backspace-mode)
8351 (normal-erase-is-backspace-mode (or value 0))
8352 (set-default symbol value))))
8354 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8355 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8356 (unless frame (setq frame (selected-frame)))
8357 (with-selected-frame frame
8358 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8359 (normal-erase-is-backspace-mode
8360 (if (if (eq normal-erase-is-backspace 'maybe)
8361 (and (not noninteractive)
8362 (or (memq system-type '(ms-dos windows-nt))
8363 (memq window-system '(w32 ns))
8364 (and (memq window-system '(x))
8365 (fboundp 'x-backspace-delete-keys-p)
8366 (x-backspace-delete-keys-p))
8367 ;; If the terminal Emacs is running on has erase char
8368 ;; set to ^H, use the Backspace key for deleting
8369 ;; backward, and the Delete key for deleting forward.
8370 (and (null window-system)
8371 (eq tty-erase-char ?\^H))))
8372 normal-erase-is-backspace)
8375 (define-minor-mode normal-erase-is-backspace-mode
8376 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8377 With a prefix argument ARG, enable this feature if ARG is
8378 positive, and disable it otherwise. If called from Lisp, enable
8379 the mode if ARG is omitted or nil.
8381 On window systems, when this mode is on, Delete is mapped to C-d
8382 and Backspace is mapped to DEL; when this mode is off, both
8383 Delete and Backspace are mapped to DEL. (The remapping goes via
8384 `local-function-key-map', so binding Delete or Backspace in the
8385 global or local keymap will override that.)
8387 In addition, on window systems, the bindings of C-Delete, M-Delete,
8388 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8389 the global keymap in accordance with the functionality of Delete and
8390 Backspace. For example, if Delete is remapped to C-d, which deletes
8391 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8392 to DEL, which deletes backward, C-Delete is bound to
8393 `backward-kill-word'.
8395 If not running on a window system, a similar effect is accomplished by
8396 remapping C-h (normally produced by the Backspace key) and DEL via
8397 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8398 to C-d; if it's off, the keys are not remapped.
8400 When not running on a window system, and this mode is turned on, the
8401 former functionality of C-h is available on the F1 key. You should
8402 probably not turn on this mode on a text-only terminal if you don't
8403 have both Backspace, Delete and F1 keys.
8405 See also `normal-erase-is-backspace'."
8406 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8408 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8410 (let ((enabled (eq 1 (terminal-parameter
8411 nil 'normal-erase-is-backspace))))
8413 (cond ((or (memq window-system '(x w32 ns pc))
8414 (memq system-type '(ms-dos windows-nt)))
8416 `(([M-delete] [M-backspace])
8417 ([C-M-delete] [C-M-backspace])
8418 ([?\e C-delete] [?\e C-backspace]))))
8422 (define-key local-function-key-map [delete] [deletechar])
8423 (define-key local-function-key-map [kp-delete] [deletechar])
8424 (define-key local-function-key-map [backspace] [?\C-?])
8425 (dolist (b bindings)
8426 ;; Not sure if input-decode-map is really right, but
8427 ;; keyboard-translate-table (used below) only works
8428 ;; for integer events, and key-translation-table is
8429 ;; global (like the global-map, used earlier).
8430 (define-key input-decode-map (car b) nil)
8431 (define-key input-decode-map (cadr b) nil)))
8432 (define-key local-function-key-map [delete] [?\C-?])
8433 (define-key local-function-key-map [kp-delete] [?\C-?])
8434 (define-key local-function-key-map [backspace] [?\C-?])
8435 (dolist (b bindings)
8436 (define-key input-decode-map (car b) (cadr b))
8437 (define-key input-decode-map (cadr b) (car b))))))
8441 (keyboard-translate ?\C-h ?\C-?)
8442 (keyboard-translate ?\C-? ?\C-d))
8443 (keyboard-translate ?\C-h ?\C-h)
8444 (keyboard-translate ?\C-? ?\C-?))))
8446 (if (called-interactively-p 'interactive)
8447 (message "Delete key deletes %s"
8448 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8449 "forward" "backward")))))
8451 (defvar vis-mode-saved-buffer-invisibility-spec nil
8452 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8454 (define-minor-mode read-only-mode
8455 "Change whether the current buffer is read-only.
8456 With prefix argument ARG, make the buffer read-only if ARG is
8457 positive, otherwise make it writable. If buffer is read-only
8458 and `view-read-only' is non-nil, enter view mode.
8460 Do not call this from a Lisp program unless you really intend to
8461 do the same thing as the \\[read-only-mode] command, including
8462 possibly enabling or disabling View mode. Also, note that this
8463 command works by setting the variable `buffer-read-only', which
8464 does not affect read-only regions caused by text properties. To
8465 ignore read-only status in a Lisp program (whether due to text
8466 properties or buffer state), bind `inhibit-read-only' temporarily
8467 to a non-nil value."
8468 :variable buffer-read-only
8470 ((and (not buffer-read-only) view-mode)
8471 (View-exit-and-edit)
8472 (make-local-variable 'view-read-only)
8473 (setq view-read-only t)) ; Must leave view mode.
8474 ((and buffer-read-only view-read-only
8475 ;; If view-mode is already active, `view-mode-enter' is a nop.
8477 (not (eq (get major-mode 'mode-class) 'special)))
8478 (view-mode-enter))))
8480 (define-minor-mode visible-mode
8481 "Toggle making all invisible text temporarily visible (Visible mode).
8482 With a prefix argument ARG, enable Visible mode if ARG is
8483 positive, and disable it otherwise. If called from Lisp, enable
8484 the mode if ARG is omitted or nil.
8486 This mode works by saving the value of `buffer-invisibility-spec'
8487 and setting it to nil."
8489 :group 'editing-basics
8490 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8491 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8492 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8494 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8495 buffer-invisibility-spec)
8496 (setq buffer-invisibility-spec nil)))
8498 (defvar messages-buffer-mode-map
8499 (let ((map (make-sparse-keymap)))
8500 (set-keymap-parent map special-mode-map)
8501 (define-key map "g" nil) ; nothing to revert
8504 (define-derived-mode messages-buffer-mode special-mode "Messages"
8505 "Major mode used in the \"*Messages*\" buffer.")
8507 (defun messages-buffer ()
8508 "Return the \"*Messages*\" buffer.
8509 If it does not exist, create and it switch it to `messages-buffer-mode'."
8510 (or (get-buffer "*Messages*")
8511 (with-current-buffer (get-buffer-create "*Messages*")
8512 (messages-buffer-mode)
8516 ;; Minibuffer prompt stuff.
8518 ;;(defun minibuffer-prompt-modification (start end)
8519 ;; (error "You cannot modify the prompt"))
8522 ;;(defun minibuffer-prompt-insertion (start end)
8523 ;; (let ((inhibit-modification-hooks t))
8524 ;; (delete-region start end)
8525 ;; ;; Discard undo information for the text insertion itself
8526 ;; ;; and for the text deletion.above.
8527 ;; (when (consp buffer-undo-list)
8528 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8529 ;; (message "You cannot modify the prompt")))
8532 ;;(setq minibuffer-prompt-properties
8533 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8534 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8537 ;;;; Problematic external packages.
8539 ;; rms says this should be done by specifying symbols that define
8540 ;; versions together with bad values. This is therefore not as
8541 ;; flexible as it could be. See the thread:
8542 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8543 (defconst bad-packages-alist
8544 ;; Not sure exactly which semantic versions have problems.
8545 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8546 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8547 "The version of `semantic' loaded does not work in Emacs 22.
8548 It can cause constant high CPU load.
8549 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8550 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8551 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8552 ;; provided the `CUA-mode' feature. Since this is no longer true,
8553 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8555 "CUA-mode is now part of the standard GNU Emacs distribution,
8556 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8558 You have loaded an older version of CUA-mode which does not work
8559 correctly with this version of Emacs. You should remove the old
8560 version and use the one distributed with Emacs."))
8561 "Alist of packages known to cause problems in this version of Emacs.
8562 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8563 PACKAGE is either a regular expression to match file names, or a
8564 symbol (a feature name), like for `with-eval-after-load'.
8565 SYMBOL is either the name of a string variable, or t. Upon
8566 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8567 warning using STRING as the message.")
8569 (defun bad-package-check (package)
8570 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8572 (let* ((list (assoc package bad-packages-alist))
8573 (symbol (nth 1 list)))
8577 (and (stringp (setq symbol (eval symbol)))
8578 (string-match-p (nth 2 list) symbol)))
8579 (display-warning package (nth 3 list) :warning)))
8582 (dolist (elem bad-packages-alist)
8583 (let ((pkg (car elem)))
8584 (with-eval-after-load pkg
8585 (bad-package-check pkg))))
8588 ;;; Generic dispatcher commands
8590 ;; Macro `define-alternatives' is used to create generic commands.
8591 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8592 ;; that can have different alternative implementations where choosing
8593 ;; among them is exclusively a matter of user preference.
8595 ;; (define-alternatives COMMAND) creates a new interactive command
8596 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8597 ;; Typically, the user will not need to customize this variable; packages
8598 ;; wanting to add alternative implementations should use
8600 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8602 (defmacro define-alternatives (command &rest customizations)
8603 "Define the new command `COMMAND'.
8605 The argument `COMMAND' should be a symbol.
8607 Running `M-x COMMAND RET' for the first time prompts for which
8608 alternative to use and records the selected command as a custom
8611 Running `C-u M-x COMMAND RET' prompts again for an alternative
8612 and overwrites the previous choice.
8614 The variable `COMMAND-alternatives' contains an alist with
8615 alternative implementations of COMMAND. `define-alternatives'
8616 does not have any effect until this variable is set.
8618 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8619 `defcustom' keywords and values to add to the declaration of
8620 `COMMAND-alternatives' (typically :group and :version)."
8621 (let* ((command-name (symbol-name command))
8622 (varalt-name (concat command-name "-alternatives"))
8623 (varalt-sym (intern varalt-name))
8624 (varimp-sym (intern (concat command-name "--implementation"))))
8627 (defcustom ,varalt-sym nil
8628 ,(format "Alist of alternative implementations for the `%s' command.
8630 Each entry must be a pair (ALTNAME . ALTFUN), where:
8631 ALTNAME - The name shown at user to describe the alternative implementation.
8632 ALTFUN - The function called to implement this alternative."
8634 :type '(alist :key-type string :value-type function)
8637 (put ',varalt-sym 'definition-name ',command)
8638 (defvar ,varimp-sym nil "Internal use only.")
8640 (defun ,command (&optional arg)
8641 ,(format "Run generic command `%s'.
8642 If used for the first time, or with interactive ARG, ask the user which
8643 implementation to use for `%s'. The variable `%s'
8644 contains the list of implementations currently supported for this command."
8645 command-name command-name varalt-name)
8647 (when (or arg (null ,varimp-sym))
8648 (let ((val (completing-read
8650 "Select implementation for command `%s': "
8652 ,varalt-sym nil t)))
8653 (unless (string-equal val "")
8654 (when (null ,varimp-sym)
8656 "Use C-u M-x %s RET`to select another implementation"
8659 (customize-save-variable ',varimp-sym
8660 (cdr (assoc-string val ,varalt-sym))))))
8662 (call-interactively ,varimp-sym)
8663 (message "%s" ,(format-message
8664 "No implementation selected for command `%s'"
8668 ;;; Functions for changing capitalization that Do What I Mean
8669 (defun upcase-dwim (arg)
8670 "Upcase words in the region, if active; if not, upcase word at point.
8671 If the region is active, this function calls `upcase-region'.
8672 Otherwise, it calls `upcase-word', with prefix argument passed to it
8673 to upcase ARG words."
8676 (upcase-region (region-beginning) (region-end))
8679 (defun downcase-dwim (arg)
8680 "Downcase words in the region, if active; if not, downcase word at point.
8681 If the region is active, this function calls `downcase-region'.
8682 Otherwise, it calls `downcase-word', with prefix argument passed to it
8683 to downcase ARG words."
8686 (downcase-region (region-beginning) (region-end))
8687 (downcase-word arg)))
8689 (defun capitalize-dwim (arg)
8690 "Capitalize words in the region, if active; if not, capitalize word at point.
8691 If the region is active, this function calls `capitalize-region'.
8692 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8693 to capitalize ARG words."
8696 (capitalize-region (region-beginning) (region-end))
8697 (capitalize-word arg)))
8703 ;;; simple.el ends here