Fix off-by-one history pruning (bug#31211)
[emacs.git] / lisp / simple.el
blob9fde9a5c90a144d35da8f6cc8d41d20afc3de7af
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2018 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
29 ;;; Code:
31 (eval-when-compile (require 'cl-lib))
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
36 ;;; From compile.el
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."
44 :type 'number
45 :group 'display
46 :version "22.1")
48 (defgroup killing nil
49 "Killing and yanking commands."
50 :group 'editing)
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
54 :group 'matching)
56 ;;; next-error support framework
58 (defgroup next-error nil
59 "`next-error' support framework."
60 :group 'compilation
61 :version "22.1")
63 (defface next-error
64 '((t (:inherit region)))
65 "Face used to highlight next error locus."
66 :group 'next-error
67 :version "22.1")
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))
82 :group 'next-error
83 :version "22.1")
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))
96 :group 'next-error
97 :version "22.1")
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))
105 :group 'next-error
106 :version "23.1")
108 (defcustom next-error-hook nil
109 "List of hook functions run by `next-error' after visiting source file."
110 :type 'hook
111 :group 'next-error)
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-buffer nil
126 "The buffer-local value of the most recent `next-error' buffer.")
127 ;; next-error-buffer is made buffer-local to keep the reference
128 ;; to the parent buffer used to navigate to the current buffer, so the
129 ;; next call of next-buffer will use the same parent buffer to
130 ;; continue navigation from it.
131 (make-variable-buffer-local 'next-error-buffer)
133 (defvar next-error-function nil
134 "Function to use to find the next error in the current buffer.
135 The function is called with 2 parameters:
136 ARG is an integer specifying by how many errors to move.
137 RESET is a boolean which, if non-nil, says to go back to the beginning
138 of the errors before moving.
139 Major modes providing compile-like functionality should set this variable
140 to indicate to `next-error' that this is a candidate buffer and how
141 to navigate in it.")
142 (make-variable-buffer-local 'next-error-function)
144 (defvar next-error-move-function nil
145 "Function to use to move to an error locus.
146 It takes two arguments, a buffer position in the error buffer
147 and a buffer position in the error locus buffer.
148 The buffer for the error locus should already be current.
149 nil means use goto-char using the second argument position.")
150 (make-variable-buffer-local 'next-error-move-function)
152 (defsubst next-error-buffer-p (buffer
153 &optional avoid-current
154 extra-test-inclusive
155 extra-test-exclusive)
156 "Return non-nil if BUFFER is a `next-error' capable buffer.
157 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
158 return nil.
160 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
161 BUFFER would not normally qualify. If it returns non-nil, BUFFER
162 is considered `next-error' capable, anyway, and the function
163 returns non-nil.
165 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
166 buffer would normally qualify. If it returns nil, BUFFER is
167 rejected, and the function returns nil."
168 (and (buffer-name buffer) ;First make sure it's live.
169 (not (and avoid-current (eq buffer (current-buffer))))
170 (with-current-buffer buffer
171 (if next-error-function ; This is the normal test.
172 ;; Optionally reject some buffers.
173 (if extra-test-exclusive
174 (funcall extra-test-exclusive)
176 ;; Optionally accept some other buffers.
177 (and extra-test-inclusive
178 (funcall extra-test-inclusive))))))
180 (defcustom next-error-find-buffer-function #'ignore
181 "Function called to find a `next-error' capable buffer.
182 This functions takes the same three arguments as the function
183 `next-error-find-buffer', and should return the buffer to be
184 used by the subsequent invocation of the command `next-error'
185 and `previous-error'.
186 If the function returns nil, `next-error-find-buffer' will
187 try to use the buffer it used previously, and failing that
188 all other buffers."
189 :type '(choice (const :tag "No default" ignore)
190 (const :tag "Single next-error capable buffer on selected frame"
191 next-error-buffer-on-selected-frame)
192 (function :tag "Other function"))
193 :group 'next-error
194 :version "27.1")
196 (defcustom next-error-found-function #'ignore
197 "Function called when a next locus is found and displayed.
198 Function is called with two arguments: a FROM-BUFFER buffer
199 from which next-error navigated, and a target buffer TO-BUFFER."
200 :type '(choice (const :tag "No default" ignore)
201 (function :tag "Other function"))
202 :group 'next-error
203 :version "27.1")
205 (defun next-error-buffer-on-selected-frame (&optional _avoid-current
206 extra-test-inclusive
207 extra-test-exclusive)
208 "Return a single visible next-error buffer on the selected frame."
209 (let ((window-buffers
210 (delete-dups
211 (delq nil (mapcar (lambda (w)
212 (if (next-error-buffer-p
213 (window-buffer w)
215 extra-test-inclusive extra-test-exclusive)
216 (window-buffer w)))
217 (window-list))))))
218 (if (eq (length window-buffers) 1)
219 (car window-buffers))))
221 (defun next-error-find-buffer (&optional avoid-current
222 extra-test-inclusive
223 extra-test-exclusive)
224 "Return a `next-error' capable buffer.
226 If AVOID-CURRENT is non-nil, treat the current buffer
227 as an absolute last resort only.
229 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
230 that normally would not qualify. If it returns t, the buffer
231 in question is treated as usable.
233 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
234 that would normally be considered usable. If it returns nil,
235 that buffer is rejected."
237 ;; 1. If a customizable function returns a buffer, use it.
238 (funcall next-error-find-buffer-function avoid-current
239 extra-test-inclusive
240 extra-test-exclusive)
241 ;; 2. If next-error-buffer has no buffer-local value
242 ;; (i.e. never navigated to the current buffer from another),
243 ;; and the current buffer is a `next-error' capable buffer,
244 ;; use it unconditionally, so next-error will always use it.
245 (if (and (not (local-variable-p 'next-error-buffer))
246 (next-error-buffer-p (current-buffer) avoid-current
247 extra-test-inclusive extra-test-exclusive))
248 (current-buffer))
249 ;; 3. If next-error-last-buffer is an acceptable buffer, use that.
250 (if (and next-error-last-buffer
251 (next-error-buffer-p next-error-last-buffer avoid-current
252 extra-test-inclusive extra-test-exclusive))
253 next-error-last-buffer)
254 ;; 4. If the current buffer is acceptable, choose it.
255 (if (next-error-buffer-p (current-buffer) avoid-current
256 extra-test-inclusive extra-test-exclusive)
257 (current-buffer))
258 ;; 5. Look for any acceptable buffer.
259 (let ((buffers (buffer-list)))
260 (while (and buffers
261 (not (next-error-buffer-p
262 (car buffers) avoid-current
263 extra-test-inclusive extra-test-exclusive)))
264 (setq buffers (cdr buffers)))
265 (car buffers))
266 ;; 6. Use the current buffer as a last resort if it qualifies,
267 ;; even despite AVOID-CURRENT.
268 (and avoid-current
269 (next-error-buffer-p (current-buffer) nil
270 extra-test-inclusive extra-test-exclusive)
271 (progn
272 (message "This is the only buffer with error message locations")
273 (current-buffer)))
274 ;; 7. Give up.
275 (error "No buffers contain error message locations")))
277 (defun next-error (&optional arg reset)
278 "Visit next `next-error' message and corresponding source code.
280 If all the error messages parsed so far have been processed already,
281 the message buffer is checked for new ones.
283 A prefix ARG specifies how many error messages to move;
284 negative means move back to previous error messages.
285 Just \\[universal-argument] as a prefix means reparse the error message buffer
286 and start at the first error.
288 The RESET argument specifies that we should restart from the beginning.
290 \\[next-error] normally uses the most recently started
291 compilation, grep, or occur buffer. It can also operate on any
292 buffer with output from the \\[compile], \\[grep] commands, or,
293 more generally, on any buffer in Compilation mode or with
294 Compilation Minor mode enabled, or any buffer in which
295 `next-error-function' is bound to an appropriate function.
296 To specify use of a particular buffer for error messages, type
297 \\[next-error] in that buffer. You can also use the command
298 `next-error-select-buffer' to select the buffer to use for the subsequent
299 invocation of `next-error'.
301 Once \\[next-error] has chosen the buffer for error messages, it
302 runs `next-error-hook' with `run-hooks', and stays with that buffer
303 until you use it in some other buffer which uses Compilation mode
304 or Compilation Minor mode.
306 To control which errors are matched, customize the variable
307 `compilation-error-regexp-alist'."
308 (interactive "P")
309 (if (consp arg) (setq reset t arg nil))
310 (let ((buffer (next-error-find-buffer)))
311 (when buffer
312 ;; We know here that next-error-function is a valid symbol we can funcall
313 (with-current-buffer buffer
314 (funcall next-error-function (prefix-numeric-value arg) reset)
315 (next-error-found buffer (current-buffer))
316 (message "%s locus from %s"
317 (cond (reset "First")
318 ((eq (prefix-numeric-value arg) 0) "Current")
319 ((< (prefix-numeric-value arg) 0) "Previous")
320 (t "Next"))
321 next-error-last-buffer)))))
323 (defun next-error-internal ()
324 "Visit the source code corresponding to the `next-error' message at point."
325 (let ((buffer (current-buffer)))
326 ;; We know here that next-error-function is a valid symbol we can funcall
327 (funcall next-error-function 0 nil)
328 (next-error-found buffer (current-buffer))
329 (message "Current locus from %s" next-error-last-buffer)))
331 (defun next-error-found (&optional from-buffer to-buffer)
332 "Function to call when the next locus is found and displayed.
333 FROM-BUFFER is a buffer from which next-error navigated,
334 and TO-BUFFER is a target buffer."
335 (setq next-error-last-buffer (or from-buffer (current-buffer)))
336 (when to-buffer
337 (with-current-buffer to-buffer
338 (setq next-error-buffer from-buffer)))
339 (when next-error-recenter
340 (recenter next-error-recenter))
341 (funcall next-error-found-function from-buffer to-buffer)
342 (run-hooks 'next-error-hook))
344 (defun next-error-select-buffer (buffer)
345 "Select a `next-error' capable BUFFER and set it as the last used.
346 This means that the selected buffer becomes the source of locations
347 for the subsequent invocation of `next-error' or `previous-error'.
348 Interactively, this command allows selection only among buffers
349 where `next-error-function' is bound to an appropriate function."
350 (interactive
351 (list (get-buffer
352 (read-buffer "Select next-error buffer: " nil nil
353 (lambda (b) (next-error-buffer-p (cdr b)))))))
354 (setq next-error-last-buffer buffer))
356 (defalias 'goto-next-locus 'next-error)
357 (defalias 'next-match 'next-error)
359 (defun previous-error (&optional n)
360 "Visit previous `next-error' message and corresponding source code.
362 Prefix arg N says how many error messages to move backwards (or
363 forwards, if negative).
365 This operates on the output from the \\[compile] and \\[grep] commands.
367 See `next-error' for the details."
368 (interactive "p")
369 (next-error (- (or n 1))))
371 (defun first-error (&optional n)
372 "Restart at the first error.
373 Visit corresponding source code.
374 With prefix arg N, visit the source code of the Nth error.
375 This operates on the output from the \\[compile] command, for instance."
376 (interactive "p")
377 (next-error n t))
379 (defun next-error-no-select (&optional n)
380 "Move point to the next error in the `next-error' buffer and highlight match.
381 Prefix arg N says how many error messages to move forwards (or
382 backwards, if negative).
383 Finds and highlights the source line like \\[next-error], but does not
384 select the source buffer."
385 (interactive "p")
386 (let ((next-error-highlight next-error-highlight-no-select))
387 (next-error n))
388 (pop-to-buffer next-error-last-buffer))
390 (defun previous-error-no-select (&optional n)
391 "Move point to the previous error in the `next-error' buffer and highlight match.
392 Prefix arg N says how many error messages to move backwards (or
393 forwards, if negative).
394 Finds and highlights the source line like \\[previous-error], but does not
395 select the source buffer."
396 (interactive "p")
397 (next-error-no-select (- (or n 1))))
399 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
400 (defvar next-error-follow-last-line nil)
402 (define-minor-mode next-error-follow-minor-mode
403 "Minor mode for compilation, occur and diff modes.
404 With a prefix argument ARG, enable mode if ARG is positive, and
405 disable it otherwise. If called from Lisp, enable mode if ARG is
406 omitted or nil.
407 When turned on, cursor motion in the compilation, grep, occur or diff
408 buffer causes automatic display of the corresponding source code location."
409 :group 'next-error :init-value nil :lighter " Fol"
410 (if (not next-error-follow-minor-mode)
411 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
412 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
413 (make-local-variable 'next-error-follow-last-line)))
415 ;; Used as a `post-command-hook' by `next-error-follow-mode'
416 ;; for the *Compilation* *grep* and *Occur* buffers.
417 (defun next-error-follow-mode-post-command-hook ()
418 (unless (equal next-error-follow-last-line (line-number-at-pos))
419 (setq next-error-follow-last-line (line-number-at-pos))
420 (condition-case nil
421 (let ((compilation-context-lines nil))
422 (setq compilation-current-error (point))
423 (next-error-no-select 0))
424 (error t))))
429 (defun fundamental-mode ()
430 "Major mode not specialized for anything in particular.
431 Other major modes are defined by comparison with this one."
432 (interactive)
433 (kill-all-local-variables)
434 (run-mode-hooks))
436 ;; Special major modes to view specially formatted data rather than files.
438 (defvar special-mode-map
439 (let ((map (make-sparse-keymap)))
440 (suppress-keymap map)
441 (define-key map "q" 'quit-window)
442 (define-key map " " 'scroll-up-command)
443 (define-key map [?\S-\ ] 'scroll-down-command)
444 (define-key map "\C-?" 'scroll-down-command)
445 (define-key map "?" 'describe-mode)
446 (define-key map "h" 'describe-mode)
447 (define-key map ">" 'end-of-buffer)
448 (define-key map "<" 'beginning-of-buffer)
449 (define-key map "g" 'revert-buffer)
450 map))
452 (put 'special-mode 'mode-class 'special)
453 (define-derived-mode special-mode nil "Special"
454 "Parent major mode from which special major modes should inherit."
455 (setq buffer-read-only t))
457 ;; Making and deleting lines.
459 (defvar self-insert-uses-region-functions nil
460 "Special hook to tell if `self-insert-command' will use the region.
461 It must be called via `run-hook-with-args-until-success' with no arguments.
463 If any function on this hook returns a non-nil value, `delete-selection-mode'
464 will act on that value (see `delete-selection-helper'), and will
465 usually delete the region. If all the functions on this hook return
466 nil, it is an indiction that `self-insert-command' needs the region
467 untouched by `delete-selection-mode', and will itself do whatever is
468 appropriate with the region.
469 Any function on `post-self-insert-hook' which act on the region should
470 add a function to this hook so that `delete-selection-mode' could
471 refrain from deleting the region before `post-self-insert-hook'
472 functions are called.
473 This hook is run by `delete-selection-uses-region-p', which see.")
475 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
476 "Propertized string representing a hard newline character.")
478 (defun newline (&optional arg interactive)
479 "Insert a newline, and move to left margin of the new line if it's blank.
480 If option `use-hard-newlines' is non-nil, the newline is marked with the
481 text-property `hard'.
482 With ARG, insert that many newlines.
484 If `electric-indent-mode' is enabled, this indents the final new line
485 that it adds, and reindents the preceding line. To just insert
486 a newline, use \\[electric-indent-just-newline].
488 Calls `auto-fill-function' if the current column number is greater
489 than the value of `fill-column' and ARG is nil.
490 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
491 (interactive "*P\np")
492 (barf-if-buffer-read-only)
493 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
494 ;; Set last-command-event to tell self-insert what to insert.
495 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
496 (beforepos (point))
497 (last-command-event ?\n)
498 ;; Don't auto-fill if we have a numeric argument.
499 (auto-fill-function (if arg nil auto-fill-function))
500 (arg (prefix-numeric-value arg))
501 (postproc
502 ;; Do the rest in post-self-insert-hook, because we want to do it
503 ;; *before* other functions on that hook.
504 (lambda ()
505 ;; Mark the newline(s) `hard'.
506 (if use-hard-newlines
507 (set-hard-newline-properties
508 (- (point) arg) (point)))
509 ;; If the newline leaves the previous line blank, and we
510 ;; have a left margin, delete that from the blank line.
511 (save-excursion
512 (goto-char beforepos)
513 (beginning-of-line)
514 (and (looking-at "[ \t]$")
515 (> (current-left-margin) 0)
516 (delete-region (point)
517 (line-end-position))))
518 ;; Indent the line after the newline, except in one case:
519 ;; when we added the newline at the beginning of a line which
520 ;; starts a page.
521 (or was-page-start
522 (move-to-left-margin nil t)))))
523 (if (not interactive)
524 ;; FIXME: For non-interactive uses, many calls actually
525 ;; just want (insert "\n"), so maybe we should do just
526 ;; that, so as to avoid the risk of filling or running
527 ;; abbrevs unexpectedly.
528 (let ((post-self-insert-hook (list postproc)))
529 (self-insert-command arg))
530 (unwind-protect
531 (progn
532 (add-hook 'post-self-insert-hook postproc nil t)
533 (self-insert-command arg))
534 ;; We first used let-binding to protect the hook, but that
535 ;; was naive since add-hook affects the symbol-default
536 ;; value of the variable, whereas the let-binding might
537 ;; only protect the buffer-local value.
538 (remove-hook 'post-self-insert-hook postproc t))))
539 nil)
541 (defun set-hard-newline-properties (from to)
542 (let ((sticky (get-text-property from 'rear-nonsticky)))
543 (put-text-property from to 'hard 't)
544 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
545 (if (and (listp sticky) (not (memq 'hard sticky)))
546 (put-text-property from (point) 'rear-nonsticky
547 (cons 'hard sticky)))))
549 (defun open-line (n)
550 "Insert a newline and leave point before it.
551 If there is a fill prefix and/or a `left-margin', insert them on
552 the new line if the line would have been blank.
553 With arg N, insert N newlines."
554 (interactive "*p")
555 (let* ((do-fill-prefix (and fill-prefix (bolp)))
556 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
557 (loc (point-marker))
558 ;; Don't expand an abbrev before point.
559 (abbrev-mode nil))
560 (newline n)
561 (goto-char loc)
562 (while (> n 0)
563 (cond ((bolp)
564 (if do-left-margin (indent-to (current-left-margin)))
565 (if do-fill-prefix (insert-and-inherit fill-prefix))))
566 (forward-line 1)
567 (setq n (1- n)))
568 (goto-char loc)
569 ;; Necessary in case a margin or prefix was inserted.
570 (end-of-line)))
572 (defun split-line (&optional arg)
573 "Split current line, moving portion beyond point vertically down.
574 If the current line starts with `fill-prefix', insert it on the new
575 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
577 When called from Lisp code, ARG may be a prefix string to copy."
578 (interactive "*P")
579 (skip-chars-forward " \t")
580 (let* ((col (current-column))
581 (pos (point))
582 ;; What prefix should we check for (nil means don't).
583 (prefix (cond ((stringp arg) arg)
584 (arg nil)
585 (t fill-prefix)))
586 ;; Does this line start with it?
587 (have-prfx (and prefix
588 (save-excursion
589 (beginning-of-line)
590 (looking-at (regexp-quote prefix))))))
591 (newline 1)
592 (if have-prfx (insert-and-inherit prefix))
593 (indent-to col 0)
594 (goto-char pos)))
596 (defun delete-indentation (&optional arg)
597 "Join this line to previous and fix up whitespace at join.
598 If there is a fill prefix, delete it from the beginning of this line.
599 With argument, join this line to following line."
600 (interactive "*P")
601 (beginning-of-line)
602 (if arg (forward-line 1))
603 (if (eq (preceding-char) ?\n)
604 (progn
605 (delete-region (point) (1- (point)))
606 ;; If the second line started with the fill prefix,
607 ;; delete the prefix.
608 (if (and fill-prefix
609 (<= (+ (point) (length fill-prefix)) (point-max))
610 (string= fill-prefix
611 (buffer-substring (point)
612 (+ (point) (length fill-prefix)))))
613 (delete-region (point) (+ (point) (length fill-prefix))))
614 (fixup-whitespace))))
616 (defalias 'join-line #'delete-indentation) ; easier to find
618 (defun delete-blank-lines ()
619 "On blank line, delete all surrounding blank lines, leaving just one.
620 On isolated blank line, delete that one.
621 On nonblank line, delete any immediately following blank lines."
622 (interactive "*")
623 (let (thisblank singleblank)
624 (save-excursion
625 (beginning-of-line)
626 (setq thisblank (looking-at "[ \t]*$"))
627 ;; Set singleblank if there is just one blank line here.
628 (setq singleblank
629 (and thisblank
630 (not (looking-at "[ \t]*\n[ \t]*$"))
631 (or (bobp)
632 (progn (forward-line -1)
633 (not (looking-at "[ \t]*$")))))))
634 ;; Delete preceding blank lines, and this one too if it's the only one.
635 (if thisblank
636 (progn
637 (beginning-of-line)
638 (if singleblank (forward-line 1))
639 (delete-region (point)
640 (if (re-search-backward "[^ \t\n]" nil t)
641 (progn (forward-line 1) (point))
642 (point-min)))))
643 ;; Delete following blank lines, unless the current line is blank
644 ;; and there are no following blank lines.
645 (if (not (and thisblank singleblank))
646 (save-excursion
647 (end-of-line)
648 (forward-line 1)
649 (delete-region (point)
650 (if (re-search-forward "[^ \t\n]" nil t)
651 (progn (beginning-of-line) (point))
652 (point-max)))))
653 ;; Handle the special case where point is followed by newline and eob.
654 ;; Delete the line, leaving point at eob.
655 (if (looking-at "^[ \t]*\n\\'")
656 (delete-region (point) (point-max)))))
658 (defcustom delete-trailing-lines t
659 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
660 Trailing lines are deleted only if `delete-trailing-whitespace'
661 is called on the entire buffer (rather than an active region)."
662 :type 'boolean
663 :group 'editing
664 :version "24.3")
666 (defun region-modifiable-p (start end)
667 "Return non-nil if the region contains no read-only text."
668 (and (not (get-text-property start 'read-only))
669 (eq end (next-single-property-change start 'read-only nil end))))
671 (defun delete-trailing-whitespace (&optional start end)
672 "Delete trailing whitespace between START and END.
673 If called interactively, START and END are the start/end of the
674 region if the mark is active, or of the buffer's accessible
675 portion if the mark is inactive.
677 This command deletes whitespace characters after the last
678 non-whitespace character in each line between START and END. It
679 does not consider formfeed characters to be whitespace.
681 If this command acts on the entire buffer (i.e. if called
682 interactively with the mark inactive, or called from Lisp with
683 END nil), it also deletes all trailing lines at the end of the
684 buffer if the variable `delete-trailing-lines' is non-nil."
685 (interactive (progn
686 (barf-if-buffer-read-only)
687 (if (use-region-p)
688 (list (region-beginning) (region-end))
689 (list nil nil))))
690 (save-match-data
691 (save-excursion
692 (let ((end-marker (and end (copy-marker end))))
693 (goto-char (or start (point-min)))
694 (with-syntax-table (make-syntax-table (syntax-table))
695 ;; Don't delete formfeeds, even if they are considered whitespace.
696 (modify-syntax-entry ?\f "_")
697 (while (re-search-forward "\\s-$" end-marker t)
698 (skip-syntax-backward "-" (line-beginning-position))
699 (let ((b (point)) (e (match-end 0)))
700 (when (region-modifiable-p b e)
701 (delete-region b e)))))
702 (if end
703 (set-marker end-marker nil)
704 ;; Delete trailing empty lines.
705 (and delete-trailing-lines
706 ;; Really the end of buffer.
707 (= (goto-char (point-max)) (1+ (buffer-size)))
708 (<= (skip-chars-backward "\n") -2)
709 (region-modifiable-p (1+ (point)) (point-max))
710 (delete-region (1+ (point)) (point-max)))))))
711 ;; Return nil for the benefit of `write-file-functions'.
712 nil)
714 (defun newline-and-indent ()
715 "Insert a newline, then indent according to major mode.
716 Indentation is done using the value of `indent-line-function'.
717 In programming language modes, this is the same as TAB.
718 In some text modes, where TAB inserts a tab, this command indents to the
719 column specified by the function `current-left-margin'."
720 (interactive "*")
721 (delete-horizontal-space t)
722 (newline nil t)
723 (indent-according-to-mode))
725 (defun reindent-then-newline-and-indent ()
726 "Reindent current line, insert newline, then indent the new line.
727 Indentation of both lines is done according to the current major mode,
728 which means calling the current value of `indent-line-function'.
729 In programming language modes, this is the same as TAB.
730 In some text modes, where TAB inserts a tab, this indents to the
731 column specified by the function `current-left-margin'."
732 (interactive "*")
733 (let ((pos (point)))
734 ;; Be careful to insert the newline before indenting the line.
735 ;; Otherwise, the indentation might be wrong.
736 (newline)
737 (save-excursion
738 (goto-char pos)
739 ;; We are at EOL before the call to indent-according-to-mode, and
740 ;; after it we usually are as well, but not always. We tried to
741 ;; address it with `save-excursion' but that uses a normal marker
742 ;; whereas we need `move after insertion', so we do the save/restore
743 ;; by hand.
744 (setq pos (copy-marker pos t))
745 (indent-according-to-mode)
746 (goto-char pos)
747 ;; Remove the trailing white-space after indentation because
748 ;; indentation may introduce the whitespace.
749 (delete-horizontal-space t))
750 (indent-according-to-mode)))
752 (defcustom read-quoted-char-radix 8
753 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
754 Legitimate radix values are 8, 10 and 16."
755 :type '(choice (const 8) (const 10) (const 16))
756 :group 'editing-basics)
758 (defun read-quoted-char (&optional prompt)
759 "Like `read-char', but do not allow quitting.
760 Also, if the first character read is an octal digit,
761 we read any number of octal digits and return the
762 specified character code. Any nondigit terminates the sequence.
763 If the terminator is RET, it is discarded;
764 any other terminator is used itself as input.
766 The optional argument PROMPT specifies a string to use to prompt the user.
767 The variable `read-quoted-char-radix' controls which radix to use
768 for numeric input."
769 (let ((message-log-max nil)
770 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
771 help-event-list)))
772 done (first t) (code 0) char translated)
773 (while (not done)
774 (let ((inhibit-quit first)
775 ;; Don't let C-h or other help chars get the help
776 ;; message--only help function keys. See bug#16617.
777 (help-char nil)
778 (help-event-list help-events)
779 (help-form
780 "Type the special character you want to use,
781 or the octal character code.
782 RET terminates the character code and is discarded;
783 any other non-digit terminates the character code and is then used as input."))
784 (setq char (read-event (and prompt (format "%s-" prompt)) t))
785 (if inhibit-quit (setq quit-flag nil)))
786 ;; Translate TAB key into control-I ASCII character, and so on.
787 ;; Note: `read-char' does it using the `ascii-character' property.
788 ;; We tried using read-key instead, but that disables the keystroke
789 ;; echo produced by 'C-q', see bug#24635.
790 (let ((translation (lookup-key local-function-key-map (vector char))))
791 (setq translated (if (arrayp translation)
792 (aref translation 0)
793 char)))
794 (if (integerp translated)
795 (setq translated (char-resolve-modifiers translated)))
796 (cond ((null translated))
797 ((not (integerp translated))
798 (setq unread-command-events (list char)
799 done t))
800 ((/= (logand translated ?\M-\^@) 0)
801 ;; Turn a meta-character into a character with the 0200 bit set.
802 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
803 done t))
804 ((and (<= ?0 translated)
805 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
806 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
807 (and prompt (setq prompt (message "%s %c" prompt translated))))
808 ((and (<= ?a (downcase translated))
809 (< (downcase translated)
810 (+ ?a -10 (min 36 read-quoted-char-radix))))
811 (setq code (+ (* code read-quoted-char-radix)
812 (+ 10 (- (downcase translated) ?a))))
813 (and prompt (setq prompt (message "%s %c" prompt translated))))
814 ((and (not first) (eq translated ?\C-m))
815 (setq done t))
816 ((not first)
817 (setq unread-command-events (list char)
818 done t))
819 (t (setq code translated
820 done t)))
821 (setq first nil))
822 code))
824 (defun quoted-insert (arg)
825 "Read next input character and insert it.
826 This is useful for inserting control characters.
827 With argument, insert ARG copies of the character.
829 If the first character you type after this command is an octal digit,
830 you should type a sequence of octal digits which specify a character code.
831 Any nondigit terminates the sequence. If the terminator is a RET,
832 it is discarded; any other terminator is used itself as input.
833 The variable `read-quoted-char-radix' specifies the radix for this feature;
834 set it to 10 or 16 to use decimal or hex instead of octal.
836 In overwrite mode, this function inserts the character anyway, and
837 does not handle octal digits specially. This means that if you use
838 overwrite as your normal editing mode, you can use this function to
839 insert characters when necessary.
841 In binary overwrite mode, this function does overwrite, and octal
842 digits are interpreted as a character code. This is intended to be
843 useful for editing binary files."
844 (interactive "*p")
845 (let* ((char
846 ;; Avoid "obsolete" warnings for translation-table-for-input.
847 (with-no-warnings
848 (let (translation-table-for-input input-method-function)
849 (if (or (not overwrite-mode)
850 (eq overwrite-mode 'overwrite-mode-binary))
851 (read-quoted-char)
852 (read-char))))))
853 ;; This used to assume character codes 0240 - 0377 stand for
854 ;; characters in some single-byte character set, and converted them
855 ;; to Emacs characters. But in 23.1 this feature is deprecated
856 ;; in favor of inserting the corresponding Unicode characters.
857 ;; (if (and enable-multibyte-characters
858 ;; (>= char ?\240)
859 ;; (<= char ?\377))
860 ;; (setq char (unibyte-char-to-multibyte char)))
861 (unless (characterp char)
862 (user-error "%s is not a valid character"
863 (key-description (vector char))))
864 (if (> arg 0)
865 (if (eq overwrite-mode 'overwrite-mode-binary)
866 (delete-char arg)))
867 (while (> arg 0)
868 (insert-and-inherit char)
869 (setq arg (1- arg)))))
871 (defun forward-to-indentation (&optional arg)
872 "Move forward ARG lines and position at first nonblank character."
873 (interactive "^p")
874 (forward-line (or arg 1))
875 (skip-chars-forward " \t"))
877 (defun backward-to-indentation (&optional arg)
878 "Move backward ARG lines and position at first nonblank character."
879 (interactive "^p")
880 (forward-line (- (or arg 1)))
881 (skip-chars-forward " \t"))
883 (defun back-to-indentation ()
884 "Move point to the first non-whitespace character on this line."
885 (interactive "^")
886 (beginning-of-line 1)
887 (skip-syntax-forward " " (line-end-position))
888 ;; Move back over chars that have whitespace syntax but have the p flag.
889 (backward-prefix-chars))
891 (defun fixup-whitespace ()
892 "Fixup white space between objects around point.
893 Leave one space or none, according to the context."
894 (interactive "*")
895 (save-excursion
896 (delete-horizontal-space)
897 (if (or (looking-at "^\\|$\\|\\s)")
898 (save-excursion (forward-char -1)
899 (looking-at "$\\|\\s(\\|\\s'")))
901 (insert ?\s))))
903 (defun delete-horizontal-space (&optional backward-only)
904 "Delete all spaces and tabs around point.
905 If BACKWARD-ONLY is non-nil, only delete them before point."
906 (interactive "*P")
907 (let ((orig-pos (point)))
908 (delete-region
909 (if backward-only
910 orig-pos
911 (progn
912 (skip-chars-forward " \t")
913 (constrain-to-field nil orig-pos t)))
914 (progn
915 (skip-chars-backward " \t")
916 (constrain-to-field nil orig-pos)))))
918 (defun just-one-space (&optional n)
919 "Delete all spaces and tabs around point, leaving one space (or N spaces).
920 If N is negative, delete newlines as well, leaving -N spaces.
921 See also `cycle-spacing'."
922 (interactive "*p")
923 (cycle-spacing n nil 'single-shot))
925 (defvar cycle-spacing--context nil
926 "Store context used in consecutive calls to `cycle-spacing' command.
927 The first time `cycle-spacing' runs, it saves in this variable:
928 its N argument, the original point position, and the original spacing
929 around point.")
931 (defun cycle-spacing (&optional n preserve-nl-back mode)
932 "Manipulate whitespace around point in a smart way.
933 In interactive use, this function behaves differently in successive
934 consecutive calls.
936 The first call in a sequence acts like `just-one-space'.
937 It deletes all spaces and tabs around point, leaving one space
938 \(or N spaces). N is the prefix argument. If N is negative,
939 it deletes newlines as well, leaving -N spaces.
940 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
942 The second call in a sequence deletes all spaces.
944 The third call in a sequence restores the original whitespace (and point).
946 If MODE is `single-shot', it only performs the first step in the sequence.
947 If MODE is `fast' and the first step would not result in any change
948 \(i.e., there are exactly (abs N) spaces around point),
949 the function goes straight to the second step.
951 Repeatedly calling the function with different values of N starts a
952 new sequence each time."
953 (interactive "*p")
954 (let ((orig-pos (point))
955 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
956 (num (abs (or n 1))))
957 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
958 (constrain-to-field nil orig-pos)
959 (cond
960 ;; Command run for the first time, single-shot mode or different argument
961 ((or (eq 'single-shot mode)
962 (not (equal last-command this-command))
963 (not cycle-spacing--context)
964 (not (eq (car cycle-spacing--context) n)))
965 (let* ((start (point))
966 (num (- num (skip-chars-forward " " (+ num (point)))))
967 (mid (point))
968 (end (progn
969 (skip-chars-forward skip-characters)
970 (constrain-to-field nil orig-pos t))))
971 (setq cycle-spacing--context ;; Save for later.
972 ;; Special handling for case where there was no space at all.
973 (unless (= start end)
974 (cons n (cons orig-pos (buffer-substring start (point))))))
975 ;; If this run causes no change in buffer content, delete all spaces,
976 ;; otherwise delete all excess spaces.
977 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
978 start mid) end)
979 (insert (make-string num ?\s))))
981 ;; Command run for the second time.
982 ((not (equal orig-pos (point)))
983 (delete-region (point) orig-pos))
985 ;; Command run for the third time.
987 (insert (cddr cycle-spacing--context))
988 (goto-char (cadr cycle-spacing--context))
989 (setq cycle-spacing--context nil)))))
991 (defun beginning-of-buffer (&optional arg)
992 "Move point to the beginning of the buffer.
993 With numeric arg N, put point N/10 of the way from the beginning.
994 If the buffer is narrowed, this command uses the beginning of the
995 accessible part of the buffer.
997 Push mark at previous position, unless either a \\[universal-argument] prefix
998 is supplied, or Transient Mark mode is enabled and the mark is active."
999 (declare (interactive-only "use `(goto-char (point-min))' instead."))
1000 (interactive "^P")
1001 (or (consp arg)
1002 (region-active-p)
1003 (push-mark))
1004 (let ((size (- (point-max) (point-min))))
1005 (goto-char (if (and arg (not (consp arg)))
1006 (+ (point-min)
1007 (if (> size 10000)
1008 ;; Avoid overflow for large buffer sizes!
1009 (* (prefix-numeric-value arg)
1010 (/ size 10))
1011 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
1012 (point-min))))
1013 (if (and arg (not (consp arg))) (forward-line 1)))
1015 (defun end-of-buffer (&optional arg)
1016 "Move point to the end of the buffer.
1017 With numeric arg N, put point N/10 of the way from the end.
1018 If the buffer is narrowed, this command uses the end of the
1019 accessible part of the buffer.
1021 Push mark at previous position, unless either a \\[universal-argument] prefix
1022 is supplied, or Transient Mark mode is enabled and the mark is active."
1023 (declare (interactive-only "use `(goto-char (point-max))' instead."))
1024 (interactive "^P")
1025 (or (consp arg) (region-active-p) (push-mark))
1026 (let ((size (- (point-max) (point-min))))
1027 (goto-char (if (and arg (not (consp arg)))
1028 (- (point-max)
1029 (if (> size 10000)
1030 ;; Avoid overflow for large buffer sizes!
1031 (* (prefix-numeric-value arg)
1032 (/ size 10))
1033 (/ (* size (prefix-numeric-value arg)) 10)))
1034 (point-max))))
1035 ;; If we went to a place in the middle of the buffer,
1036 ;; adjust it to the beginning of a line.
1037 (cond ((and arg (not (consp arg))) (forward-line 1))
1038 ((and (eq (current-buffer) (window-buffer))
1039 (> (point) (window-end nil t)))
1040 ;; If the end of the buffer is not already on the screen,
1041 ;; then scroll specially to put it near, but not at, the bottom.
1042 (overlay-recenter (point))
1043 (recenter -3))))
1045 (defcustom delete-active-region t
1046 "Whether single-char deletion commands delete an active region.
1047 This has an effect only if Transient Mark mode is enabled, and
1048 affects `delete-forward-char' and `delete-backward-char', though
1049 not `delete-char'.
1051 If the value is the symbol `kill', the active region is killed
1052 instead of deleted."
1053 :type '(choice (const :tag "Delete active region" t)
1054 (const :tag "Kill active region" kill)
1055 (const :tag "Do ordinary deletion" nil))
1056 :group 'killing
1057 :version "24.1")
1059 (defvar region-extract-function
1060 (lambda (method)
1061 (when (region-beginning)
1062 (cond
1063 ((eq method 'bounds)
1064 (list (cons (region-beginning) (region-end))))
1065 ((eq method 'delete-only)
1066 (delete-region (region-beginning) (region-end)))
1068 (filter-buffer-substring (region-beginning) (region-end) method)))))
1069 "Function to get the region's content.
1070 Called with one argument METHOD which can be:
1071 - nil: return the content as a string.
1072 - `delete-only': delete the region; the return value is undefined.
1073 - `bounds': return the boundaries of the region as a list of cons
1074 cells of the form (START . END).
1075 - anything else: delete the region and return its content
1076 as a string, after filtering it with `filter-buffer-substring', which
1077 is called with METHOD as its 3rd argument.")
1079 (defvar region-insert-function
1080 (lambda (lines)
1081 (let ((first t))
1082 (while lines
1083 (or first
1084 (insert ?\n))
1085 (insert-for-yank (car lines))
1086 (setq lines (cdr lines)
1087 first nil))))
1088 "Function to insert the region's content.
1089 Called with one argument LINES.
1090 Insert the region as a list of lines.")
1092 (defun delete-backward-char (n &optional killflag)
1093 "Delete the previous N characters (following if N is negative).
1094 If Transient Mark mode is enabled, the mark is active, and N is 1,
1095 delete the text in the region and deactivate the mark instead.
1096 To disable this, set option `delete-active-region' to nil.
1098 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1099 kill ring) instead of delete. Interactively, N is the prefix
1100 arg, and KILLFLAG is set if N is explicitly specified.
1102 When killing, the killed text is filtered by
1103 `filter-buffer-substring' before it is saved in the kill ring, so
1104 the actual saved text might be different from what was killed.
1106 In Overwrite mode, single character backward deletion may replace
1107 tabs with spaces so as to back over columns, unless point is at
1108 the end of the line."
1109 (declare (interactive-only delete-char))
1110 (interactive "p\nP")
1111 (unless (integerp n)
1112 (signal 'wrong-type-argument (list 'integerp n)))
1113 (cond ((and (use-region-p)
1114 delete-active-region
1115 (= n 1))
1116 ;; If a region is active, kill or delete it.
1117 (if (eq delete-active-region 'kill)
1118 (kill-region (region-beginning) (region-end) 'region)
1119 (funcall region-extract-function 'delete-only)))
1120 ;; In Overwrite mode, maybe untabify while deleting
1121 ((null (or (null overwrite-mode)
1122 (<= n 0)
1123 (memq (char-before) '(?\t ?\n))
1124 (eobp)
1125 (eq (char-after) ?\n)))
1126 (let ((ocol (current-column)))
1127 (delete-char (- n) killflag)
1128 (save-excursion
1129 (insert-char ?\s (- ocol (current-column)) nil))))
1130 ;; Otherwise, do simple deletion.
1131 (t (delete-char (- n) killflag))))
1133 (defun delete-forward-char (n &optional killflag)
1134 "Delete the following N characters (previous if N is negative).
1135 If Transient Mark mode is enabled, the mark is active, and N is 1,
1136 delete the text in the region and deactivate the mark instead.
1137 To disable this, set variable `delete-active-region' to nil.
1139 Optional second arg KILLFLAG non-nil means to kill (save in kill
1140 ring) instead of delete. Interactively, N is the prefix arg, and
1141 KILLFLAG is set if N was explicitly specified.
1143 When killing, the killed text is filtered by
1144 `filter-buffer-substring' before it is saved in the kill ring, so
1145 the actual saved text might be different from what was killed."
1146 (declare (interactive-only delete-char))
1147 (interactive "p\nP")
1148 (unless (integerp n)
1149 (signal 'wrong-type-argument (list 'integerp n)))
1150 (cond ((and (use-region-p)
1151 delete-active-region
1152 (= n 1))
1153 ;; If a region is active, kill or delete it.
1154 (if (eq delete-active-region 'kill)
1155 (kill-region (region-beginning) (region-end) 'region)
1156 (funcall region-extract-function 'delete-only)))
1158 ;; Otherwise, do simple deletion.
1159 (t (delete-char n killflag))))
1161 (defun mark-whole-buffer ()
1162 "Put point at beginning and mark at end of buffer.
1163 Also push mark at point before pushing mark at end of buffer.
1164 If narrowing is in effect, only uses the accessible part of the buffer.
1165 You probably should not use this function in Lisp programs;
1166 it is usually a mistake for a Lisp function to use any subroutine
1167 that uses or sets the mark."
1168 (declare (interactive-only t))
1169 (interactive)
1170 (push-mark)
1171 (push-mark (point-max) nil t)
1172 ;; This is really `point-min' in most cases, but if we're in the
1173 ;; minibuffer, this is at the end of the prompt.
1174 (goto-char (minibuffer-prompt-end)))
1177 ;; Counting lines, one way or another.
1179 (defun goto-line (line &optional buffer)
1180 "Go to LINE, counting from line 1 at beginning of buffer.
1181 If called interactively, a numeric prefix argument specifies
1182 LINE; without a numeric prefix argument, read LINE from the
1183 minibuffer.
1185 If optional argument BUFFER is non-nil, switch to that buffer and
1186 move to line LINE there. If called interactively with \\[universal-argument]
1187 as argument, BUFFER is the most recently selected other buffer.
1189 Prior to moving point, this function sets the mark (without
1190 activating it), unless Transient Mark mode is enabled and the
1191 mark is already active.
1193 This function is usually the wrong thing to use in a Lisp program.
1194 What you probably want instead is something like:
1195 (goto-char (point-min))
1196 (forward-line (1- N))
1197 If at all possible, an even better solution is to use char counts
1198 rather than line counts."
1199 (declare (interactive-only forward-line))
1200 (interactive
1201 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1202 (list (prefix-numeric-value current-prefix-arg))
1203 ;; Look for a default, a number in the buffer at point.
1204 (let* ((default
1205 (save-excursion
1206 (skip-chars-backward "0-9")
1207 (if (looking-at "[0-9]")
1208 (string-to-number
1209 (buffer-substring-no-properties
1210 (point)
1211 (progn (skip-chars-forward "0-9")
1212 (point)))))))
1213 ;; Decide if we're switching buffers.
1214 (buffer
1215 (if (consp current-prefix-arg)
1216 (other-buffer (current-buffer) t)))
1217 (buffer-prompt
1218 (if buffer
1219 (concat " in " (buffer-name buffer))
1220 "")))
1221 ;; Read the argument, offering that number (if any) as default.
1222 (list (read-number (format "Goto line%s: " buffer-prompt)
1223 (list default (line-number-at-pos)))
1224 buffer))))
1225 ;; Switch to the desired buffer, one way or another.
1226 (if buffer
1227 (let ((window (get-buffer-window buffer)))
1228 (if window (select-window window)
1229 (switch-to-buffer-other-window buffer))))
1230 ;; Leave mark at previous position
1231 (or (region-active-p) (push-mark))
1232 ;; Move to the specified line number in that buffer.
1233 (save-restriction
1234 (widen)
1235 (goto-char (point-min))
1236 (if (eq selective-display t)
1237 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1238 (forward-line (1- line)))))
1240 (defun count-words-region (start end &optional arg)
1241 "Count the number of words in the region.
1242 If called interactively, print a message reporting the number of
1243 lines, words, and characters in the region (whether or not the
1244 region is active); with prefix ARG, report for the entire buffer
1245 rather than the region.
1247 If called from Lisp, return the number of words between positions
1248 START and END."
1249 (interactive (if current-prefix-arg
1250 (list nil nil current-prefix-arg)
1251 (list (region-beginning) (region-end) nil)))
1252 (cond ((not (called-interactively-p 'any))
1253 (count-words start end))
1254 (arg
1255 (count-words--buffer-message))
1257 (count-words--message "Region" start end))))
1259 (defun count-words (start end)
1260 "Count words between START and END.
1261 If called interactively, START and END are normally the start and
1262 end of the buffer; but if the region is active, START and END are
1263 the start and end of the region. Print a message reporting the
1264 number of lines, words, and chars.
1266 If called from Lisp, return the number of words between START and
1267 END, without printing any message."
1268 (interactive (list nil nil))
1269 (cond ((not (called-interactively-p 'any))
1270 (let ((words 0))
1271 (save-excursion
1272 (save-restriction
1273 (narrow-to-region start end)
1274 (goto-char (point-min))
1275 (while (forward-word-strictly 1)
1276 (setq words (1+ words)))))
1277 words))
1278 ((use-region-p)
1279 (call-interactively 'count-words-region))
1281 (count-words--buffer-message))))
1283 (defun count-words--buffer-message ()
1284 (count-words--message
1285 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1286 (point-min) (point-max)))
1288 (defun count-words--message (str start end)
1289 (let ((lines (count-lines start end))
1290 (words (count-words start end))
1291 (chars (- end start)))
1292 (message "%s has %d line%s, %d word%s, and %d character%s."
1294 lines (if (= lines 1) "" "s")
1295 words (if (= words 1) "" "s")
1296 chars (if (= chars 1) "" "s"))))
1298 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1300 (defun what-line ()
1301 "Print the current buffer line number and narrowed line number of point."
1302 (interactive)
1303 (let ((start (point-min))
1304 (n (line-number-at-pos)))
1305 (if (= start 1)
1306 (message "Line %d" n)
1307 (save-excursion
1308 (save-restriction
1309 (widen)
1310 (message "line %d (narrowed line %d)"
1311 (+ n (line-number-at-pos start) -1) n))))))
1313 (defun count-lines (start end)
1314 "Return number of lines between START and END.
1315 This is usually the number of newlines between them,
1316 but can be one more if START is not equal to END
1317 and the greater of them is not at the start of a line."
1318 (save-excursion
1319 (save-restriction
1320 (narrow-to-region start end)
1321 (goto-char (point-min))
1322 (if (eq selective-display t)
1323 (save-match-data
1324 (let ((done 0))
1325 (while (re-search-forward "[\n\C-m]" nil t 40)
1326 (setq done (+ 40 done)))
1327 (while (re-search-forward "[\n\C-m]" nil t 1)
1328 (setq done (+ 1 done)))
1329 (goto-char (point-max))
1330 (if (and (/= start end)
1331 (not (bolp)))
1332 (1+ done)
1333 done)))
1334 (- (buffer-size) (forward-line (buffer-size)))))))
1336 (defun line-number-at-pos (&optional pos absolute)
1337 "Return buffer line number at position POS.
1338 If POS is nil, use current buffer location.
1340 If ABSOLUTE is nil, the default, counting starts
1341 at (point-min), so the value refers to the contents of the
1342 accessible portion of the (potentially narrowed) buffer. If
1343 ABSOLUTE is non-nil, ignore any narrowing and return the
1344 absolute line number."
1345 (save-restriction
1346 (when absolute
1347 (widen))
1348 (let ((opoint (or pos (point))) start)
1349 (save-excursion
1350 (goto-char (point-min))
1351 (setq start (point))
1352 (goto-char opoint)
1353 (forward-line 0)
1354 (1+ (count-lines start (point)))))))
1356 (defun what-cursor-position (&optional detail)
1357 "Print info on cursor position (on screen and within buffer).
1358 Also describe the character after point, and give its character code
1359 in octal, decimal and hex.
1361 For a non-ASCII multibyte character, also give its encoding in the
1362 buffer's selected coding system if the coding system encodes the
1363 character safely. If the character is encoded into one byte, that
1364 code is shown in hex. If the character is encoded into more than one
1365 byte, just \"...\" is shown.
1367 In addition, with prefix argument, show details about that character
1368 in *Help* buffer. See also the command `describe-char'."
1369 (interactive "P")
1370 (let* ((char (following-char))
1371 (bidi-fixer
1372 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1373 ;; start a directional embedding, which could completely
1374 ;; disrupt the rest of the line (e.g., RLO will display the
1375 ;; rest of the line right-to-left). So we put an invisible
1376 ;; PDF character after these characters, to end the
1377 ;; embedding, which eliminates any effects on the rest of
1378 ;; the line. For RLE and RLO we also append an invisible
1379 ;; LRM, to avoid reordering the following numerical
1380 ;; characters. For LRI/RLI/FSI we append a PDI.
1381 (cond ((memq char '(?\x202a ?\x202d))
1382 (propertize (string ?\x202c) 'invisible t))
1383 ((memq char '(?\x202b ?\x202e))
1384 (propertize (string ?\x202c ?\x200e) 'invisible t))
1385 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1386 (propertize (string ?\x2069) 'invisible t))
1387 ;; Strong right-to-left characters cause reordering of
1388 ;; the following numerical characters which show the
1389 ;; codepoint, so append LRM to countermand that.
1390 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1391 (propertize (string ?\x200e) 'invisible t))
1393 "")))
1394 (beg (point-min))
1395 (end (point-max))
1396 (pos (point))
1397 (total (buffer-size))
1398 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1399 (hscroll (if (= (window-hscroll) 0)
1401 (format " Hscroll=%d" (window-hscroll))))
1402 (col (current-column)))
1403 (if (= pos end)
1404 (if (or (/= beg 1) (/= end (1+ total)))
1405 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1406 pos total percent beg end col hscroll)
1407 (message "point=%d of %d (EOB) column=%d%s"
1408 pos total col hscroll))
1409 (let ((coding buffer-file-coding-system)
1410 encoded encoding-msg display-prop under-display)
1411 (if (or (not coding)
1412 (eq (coding-system-type coding) t))
1413 (setq coding (default-value 'buffer-file-coding-system)))
1414 (if (eq (char-charset char) 'eight-bit)
1415 (setq encoding-msg
1416 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1417 ;; Check if the character is displayed with some `display'
1418 ;; text property. In that case, set under-display to the
1419 ;; buffer substring covered by that property.
1420 (setq display-prop (get-char-property pos 'display))
1421 (if display-prop
1422 (let ((to (or (next-single-char-property-change pos 'display)
1423 (point-max))))
1424 (if (< to (+ pos 4))
1425 (setq under-display "")
1426 (setq under-display "..."
1427 to (+ pos 4)))
1428 (setq under-display
1429 (concat (buffer-substring-no-properties pos to)
1430 under-display)))
1431 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1432 (setq encoding-msg
1433 (if display-prop
1434 (if (not (stringp display-prop))
1435 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1436 char char char under-display)
1437 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1438 char char char under-display display-prop))
1439 (if encoded
1440 (format "(%d, #o%o, #x%x, file %s)"
1441 char char char
1442 (if (> (length encoded) 1)
1443 "..."
1444 (encoded-string-description encoded coding)))
1445 (format "(%d, #o%o, #x%x)" char char char)))))
1446 (if detail
1447 ;; We show the detailed information about CHAR.
1448 (describe-char (point)))
1449 (if (or (/= beg 1) (/= end (1+ total)))
1450 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1451 (if (< char 256)
1452 (single-key-description char)
1453 (buffer-substring-no-properties (point) (1+ (point))))
1454 bidi-fixer
1455 encoding-msg pos total percent beg end col hscroll)
1456 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1457 (if enable-multibyte-characters
1458 (if (< char 128)
1459 (single-key-description char)
1460 (buffer-substring-no-properties (point) (1+ (point))))
1461 (single-key-description char))
1462 bidi-fixer encoding-msg pos total percent col hscroll))))))
1464 ;; Initialize read-expression-map. It is defined at C level.
1465 (defvar read-expression-map
1466 (let ((m (make-sparse-keymap)))
1467 (define-key m "\M-\t" 'completion-at-point)
1468 ;; Might as well bind TAB to completion, since inserting a TAB char is
1469 ;; much too rarely useful.
1470 (define-key m "\t" 'completion-at-point)
1471 (set-keymap-parent m minibuffer-local-map)
1474 (defun read-minibuffer (prompt &optional initial-contents)
1475 "Return a Lisp object read using the minibuffer, unevaluated.
1476 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1477 is a string to insert in the minibuffer before reading.
1478 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1479 Such arguments are used as in `read-from-minibuffer'.)"
1480 ;; Used for interactive spec `x'.
1481 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1482 t 'minibuffer-history))
1484 (defun eval-minibuffer (prompt &optional initial-contents)
1485 "Return value of Lisp expression read using the minibuffer.
1486 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1487 is a string to insert in the minibuffer before reading.
1488 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1489 Such arguments are used as in `read-from-minibuffer'.)"
1490 ;; Used for interactive spec `X'.
1491 (eval (read--expression prompt initial-contents)))
1493 (defvar minibuffer-completing-symbol nil
1494 "Non-nil means completing a Lisp symbol in the minibuffer.")
1495 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1497 (defvar minibuffer-default nil
1498 "The current default value or list of default values in the minibuffer.
1499 The functions `read-from-minibuffer' and `completing-read' bind
1500 this variable locally.")
1502 (defcustom eval-expression-print-level 4
1503 "Value for `print-level' while printing value in `eval-expression'.
1504 A value of nil means no limit."
1505 :group 'lisp
1506 :type '(choice (const :tag "No Limit" nil) integer)
1507 :version "21.1")
1509 (defcustom eval-expression-print-length 12
1510 "Value for `print-length' while printing value in `eval-expression'.
1511 A value of nil means no limit."
1512 :group 'lisp
1513 :type '(choice (const :tag "No Limit" nil) integer)
1514 :version "21.1")
1516 (defcustom eval-expression-debug-on-error t
1517 "If non-nil set `debug-on-error' to t in `eval-expression'.
1518 If nil, don't change the value of `debug-on-error'."
1519 :group 'lisp
1520 :type 'boolean
1521 :version "21.1")
1523 (defcustom eval-expression-print-maximum-character 127
1524 "The largest integer that will be displayed as a character.
1525 This affects printing by `eval-expression' (via
1526 `eval-expression-print-format')."
1527 :group 'lisp
1528 :type 'integer
1529 :version "26.1")
1531 (defun eval-expression-print-format (value)
1532 "If VALUE in an integer, return a specially formatted string.
1533 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1534 If VALUE is not an integer, nil is returned.
1535 This function is used by commands like `eval-expression' that
1536 display the result of expression evaluation."
1537 (when (integerp value)
1538 (let ((char-string
1539 (and (characterp value)
1540 (<= value eval-expression-print-maximum-character)
1541 (char-displayable-p value)
1542 (prin1-char value))))
1543 (if char-string
1544 (format " (#o%o, #x%x, %s)" value value char-string)
1545 (format " (#o%o, #x%x)" value value)))))
1547 (defvar eval-expression-minibuffer-setup-hook nil
1548 "Hook run by `eval-expression' when entering the minibuffer.")
1550 (defun read--expression (prompt &optional initial-contents)
1551 (let ((minibuffer-completing-symbol t))
1552 (minibuffer-with-setup-hook
1553 (lambda ()
1554 ;; FIXME: call emacs-lisp-mode?
1555 (add-function :before-until (local 'eldoc-documentation-function)
1556 #'elisp-eldoc-documentation-function)
1557 (eldoc-mode 1)
1558 (add-hook 'completion-at-point-functions
1559 #'elisp-completion-at-point nil t)
1560 (run-hooks 'eval-expression-minibuffer-setup-hook))
1561 (read-from-minibuffer prompt initial-contents
1562 read-expression-map t
1563 'read-expression-history))))
1565 (defun eval-expression-get-print-arguments (prefix-argument)
1566 "Get arguments for commands that print an expression result.
1567 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1568 based on PREFIX-ARG. This function determines the interpretation
1569 of the prefix argument for `eval-expression' and
1570 `eval-last-sexp'."
1571 (let ((num (prefix-numeric-value prefix-argument)))
1572 (list (not (memq prefix-argument '(- nil)))
1573 (= num 0)
1574 (cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
1575 ((= num -1) most-positive-fixnum)
1576 (t eval-expression-print-maximum-character)))))
1578 ;; We define this, rather than making `eval' interactive,
1579 ;; for the sake of completion of names like eval-region, eval-buffer.
1580 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
1581 "Evaluate EXP and print value in the echo area.
1582 When called interactively, read an Emacs Lisp expression and
1583 evaluate it. Value is also consed on to front of the variable
1584 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1585 with a non `-' prefix argument) means insert the result into the
1586 current buffer instead of printing it in the echo area.
1588 Normally, this function truncates long output according to the
1589 value of the variables `eval-expression-print-length' and
1590 `eval-expression-print-level'. When NO-TRUNCATE is
1591 non-nil (interactively, with a prefix argument of zero), however,
1592 there is no such truncation.
1594 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1595 non-nil (interactively, unless given a positive prefix argument)
1596 it will be printed in several additional formats (octal,
1597 hexadecimal, and character). The character format is only used
1598 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1599 prefix argument is -1 or the value is below
1600 `eval-expression-print-maximum-character').
1602 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1603 minibuffer.
1605 If `eval-expression-debug-on-error' is non-nil, which is the default,
1606 this command arranges for all errors to enter the debugger."
1607 (interactive
1608 (cons (read--expression "Eval: ")
1609 (eval-expression-get-print-arguments current-prefix-arg)))
1611 (if (null eval-expression-debug-on-error)
1612 (push (eval exp lexical-binding) values)
1613 (let ((old-value (make-symbol "t")) new-value)
1614 ;; Bind debug-on-error to something unique so that we can
1615 ;; detect when evalled code changes it.
1616 (let ((debug-on-error old-value))
1617 (push (eval (macroexpand-all exp) lexical-binding) values)
1618 (setq new-value debug-on-error))
1619 ;; If evalled code has changed the value of debug-on-error,
1620 ;; propagate that change to the global binding.
1621 (unless (eq old-value new-value)
1622 (setq debug-on-error new-value))))
1624 (let ((print-length (unless no-truncate eval-expression-print-length))
1625 (print-level (unless no-truncate eval-expression-print-level))
1626 (eval-expression-print-maximum-character char-print-limit)
1627 (deactivate-mark))
1628 (let ((out (if insert-value (current-buffer) t)))
1629 (prog1
1630 (prin1 (car values) out)
1631 (let ((str (and char-print-limit
1632 (eval-expression-print-format (car values)))))
1633 (when str (princ str out)))))))
1635 (defun edit-and-eval-command (prompt command)
1636 "Prompting with PROMPT, let user edit COMMAND and eval result.
1637 COMMAND is a Lisp expression. Let user edit that expression in
1638 the minibuffer, then read and evaluate the result."
1639 (let ((command
1640 (let ((print-level nil)
1641 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1642 (unwind-protect
1643 (read-from-minibuffer prompt
1644 (prin1-to-string command)
1645 read-expression-map t
1646 'command-history)
1647 ;; If command was added to command-history as a string,
1648 ;; get rid of that. We want only evaluable expressions there.
1649 (when (stringp (car command-history))
1650 (pop command-history))))))
1652 (add-to-history 'command-history command)
1653 (eval command)))
1655 (defun repeat-complex-command (arg)
1656 "Edit and re-evaluate last complex command, or ARGth from last.
1657 A complex command is one which used the minibuffer.
1658 The command is placed in the minibuffer as a Lisp form for editing.
1659 The result is executed, repeating the command as changed.
1660 If the command has been changed or is not the most recent previous
1661 command it is added to the front of the command history.
1662 You can use the minibuffer history commands \
1663 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1664 to get different commands to edit and resubmit."
1665 (interactive "p")
1666 (let ((elt (nth (1- arg) command-history))
1667 newcmd)
1668 (if elt
1669 (progn
1670 (setq newcmd
1671 (let ((print-level nil)
1672 (minibuffer-history-position arg)
1673 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1674 (unwind-protect
1675 (read-from-minibuffer
1676 "Redo: " (prin1-to-string elt) read-expression-map t
1677 (cons 'command-history arg))
1679 ;; If command was added to command-history as a
1680 ;; string, get rid of that. We want only
1681 ;; evaluable expressions there.
1682 (when (stringp (car command-history))
1683 (pop command-history)))))
1685 (add-to-history 'command-history newcmd)
1686 (apply #'funcall-interactively
1687 (car newcmd)
1688 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1689 (if command-history
1690 (error "Argument %d is beyond length of command history" arg)
1691 (error "There are no previous complex commands to repeat")))))
1694 (defvar extended-command-history nil)
1695 (defvar execute-extended-command--last-typed nil)
1697 (defun read-extended-command ()
1698 "Read command name to invoke in `execute-extended-command'."
1699 (minibuffer-with-setup-hook
1700 (lambda ()
1701 (add-hook 'post-self-insert-hook
1702 (lambda ()
1703 (setq execute-extended-command--last-typed
1704 (minibuffer-contents)))
1705 nil 'local)
1706 (set (make-local-variable 'minibuffer-default-add-function)
1707 (lambda ()
1708 ;; Get a command name at point in the original buffer
1709 ;; to propose it after M-n.
1710 (with-current-buffer (window-buffer (minibuffer-selected-window))
1711 (and (commandp (function-called-at-point))
1712 (format "%S" (function-called-at-point)))))))
1713 ;; Read a string, completing from and restricting to the set of
1714 ;; all defined commands. Don't provide any initial input.
1715 ;; Save the command read on the extended-command history list.
1716 (completing-read
1717 (concat (cond
1718 ((eq current-prefix-arg '-) "- ")
1719 ((and (consp current-prefix-arg)
1720 (eq (car current-prefix-arg) 4)) "C-u ")
1721 ((and (consp current-prefix-arg)
1722 (integerp (car current-prefix-arg)))
1723 (format "%d " (car current-prefix-arg)))
1724 ((integerp current-prefix-arg)
1725 (format "%d " current-prefix-arg)))
1726 ;; This isn't strictly correct if `execute-extended-command'
1727 ;; is bound to anything else (e.g. [menu]).
1728 ;; It could use (key-description (this-single-command-keys)),
1729 ;; but actually a prompt other than "M-x" would be confusing,
1730 ;; because "M-x" is a well-known prompt to read a command
1731 ;; and it serves as a shorthand for "Extended command: ".
1732 "M-x ")
1733 (lambda (string pred action)
1734 (let ((pred
1735 (if (memq action '(nil t))
1736 ;; Exclude obsolete commands from completions.
1737 (lambda (sym)
1738 (and (funcall pred sym)
1739 (or (equal string (symbol-name sym))
1740 (not (get sym 'byte-obsolete-info)))))
1741 pred)))
1742 (complete-with-action action obarray string pred)))
1743 #'commandp t nil 'extended-command-history)))
1745 (defcustom suggest-key-bindings t
1746 "Non-nil means show the equivalent key-binding when M-x command has one.
1747 The value can be a length of time to show the message for.
1748 If the value is non-nil and not a number, we wait 2 seconds."
1749 :group 'keyboard
1750 :type '(choice (const :tag "off" nil)
1751 (integer :tag "time" 2)
1752 (other :tag "on")))
1754 (defcustom extended-command-suggest-shorter t
1755 "If non-nil, show a shorter M-x invocation when there is one."
1756 :group 'keyboard
1757 :type 'boolean
1758 :version "26.1")
1760 (defun execute-extended-command--shorter-1 (name length)
1761 (cond
1762 ((zerop length) (list ""))
1763 ((equal name "") nil)
1765 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1766 (execute-extended-command--shorter-1
1767 (substring name 1) (1- length)))
1768 (when (string-match "\\`\\(-\\)?[^-]*" name)
1769 (execute-extended-command--shorter-1
1770 (substring name (match-end 0)) length))))))
1772 (defun execute-extended-command--shorter (name typed)
1773 (let ((candidates '())
1774 (max (length typed))
1775 (len 1)
1776 binding)
1777 (while (and (not binding)
1778 (progn
1779 (unless candidates
1780 (setq len (1+ len))
1781 (setq candidates (execute-extended-command--shorter-1
1782 name len)))
1783 ;; Don't show the help message if the binding isn't
1784 ;; significantly shorter than the M-x command the user typed.
1785 (< len (- max 5))))
1786 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1787 (let ((candidate (pop candidates)))
1788 (when (equal name
1789 (car-safe (completion-try-completion
1790 candidate obarray 'commandp len)))
1791 (setq binding candidate))))
1792 binding))
1794 (defun execute-extended-command (prefixarg &optional command-name typed)
1795 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1796 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1797 "Read a command name, then read the arguments and call the command.
1798 To pass a prefix argument to the command you are
1799 invoking, give a prefix argument to `execute-extended-command'."
1800 (declare (interactive-only command-execute))
1801 ;; FIXME: Remember the actual text typed by the user before completion,
1802 ;; so that we don't later on suggest the same shortening.
1803 (interactive
1804 (let ((execute-extended-command--last-typed nil))
1805 (list current-prefix-arg
1806 (read-extended-command)
1807 execute-extended-command--last-typed)))
1808 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1809 (unless command-name
1810 (let ((current-prefix-arg prefixarg) ; for prompt
1811 (execute-extended-command--last-typed nil))
1812 (setq command-name (read-extended-command))
1813 (setq typed execute-extended-command--last-typed)))
1814 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1815 (binding (and suggest-key-bindings
1816 (not executing-kbd-macro)
1817 (where-is-internal function overriding-local-map t))))
1818 (unless (commandp function)
1819 (error "`%s' is not a valid command name" command-name))
1820 ;; Some features, such as novice.el, rely on this-command-keys
1821 ;; including M-x COMMAND-NAME RET.
1822 (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
1823 (setq this-command function)
1824 ;; Normally `real-this-command' should never be changed, but here we really
1825 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1826 ;; binding" for <cmd>, so the command the user really wanted to run is
1827 ;; `function' and not `execute-extended-command'. The difference is
1828 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1829 (setq real-this-command function)
1830 (let ((prefix-arg prefixarg))
1831 (command-execute function 'record))
1832 ;; If enabled, show which key runs this command.
1833 ;; But first wait, and skip the message if there is input.
1834 (let* ((waited
1835 ;; If this command displayed something in the echo area;
1836 ;; wait a few seconds, then display our suggestion message.
1837 ;; FIXME: Wait *after* running post-command-hook!
1838 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1839 ;; find a better answer anyway!
1840 (when suggest-key-bindings
1841 (sit-for (cond
1842 ((zerop (length (current-message))) 0)
1843 ((numberp suggest-key-bindings) suggest-key-bindings)
1844 (t 2))))))
1845 (when (and waited (not (consp unread-command-events)))
1846 (unless (or (not extended-command-suggest-shorter)
1847 binding executing-kbd-macro (not (symbolp function))
1848 (<= (length (symbol-name function)) 2))
1849 ;; There's no binding for CMD. Let's try and find the shortest
1850 ;; string to use in M-x.
1851 ;; FIXME: Can be slow. Cache it maybe?
1852 (while-no-input
1853 (setq binding (execute-extended-command--shorter
1854 (symbol-name function) typed))))
1855 (when binding
1856 (with-temp-message
1857 (format-message "You can run the command `%s' with %s"
1858 function
1859 (if (stringp binding)
1860 (concat "M-x " binding " RET")
1861 (key-description binding)))
1862 (sit-for (if (numberp suggest-key-bindings)
1863 suggest-key-bindings
1864 2))))))))
1866 (defun command-execute (cmd &optional record-flag keys special)
1867 ;; BEWARE: Called directly from the C code.
1868 "Execute CMD as an editor command.
1869 CMD must be a symbol that satisfies the `commandp' predicate.
1870 Optional second arg RECORD-FLAG non-nil
1871 means unconditionally put this command in the variable `command-history'.
1872 Otherwise, that is done only if an arg is read using the minibuffer.
1873 The argument KEYS specifies the value to use instead of (this-command-keys)
1874 when reading the arguments; if it is nil, (this-command-keys) is used.
1875 The argument SPECIAL, if non-nil, means that this command is executing
1876 a special event, so ignore the prefix argument and don't clear it."
1877 (setq debug-on-next-call nil)
1878 (let ((prefixarg (unless special
1879 ;; FIXME: This should probably be done around
1880 ;; pre-command-hook rather than here!
1881 (prog1 prefix-arg
1882 (setq current-prefix-arg prefix-arg)
1883 (setq prefix-arg nil)
1884 (when current-prefix-arg
1885 (prefix-command-update))))))
1886 (if (and (symbolp cmd)
1887 (get cmd 'disabled)
1888 disabled-command-function)
1889 ;; FIXME: Weird calling convention!
1890 (run-hooks 'disabled-command-function)
1891 (let ((final cmd))
1892 (while
1893 (progn
1894 (setq final (indirect-function final))
1895 (if (autoloadp final)
1896 (setq final (autoload-do-load final cmd)))))
1897 (cond
1898 ((arrayp final)
1899 ;; If requested, place the macro in the command history. For
1900 ;; other sorts of commands, call-interactively takes care of this.
1901 (when record-flag
1902 (add-to-history
1903 'command-history `(execute-kbd-macro ,final ,prefixarg) nil t))
1904 (execute-kbd-macro final prefixarg))
1906 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1907 (prog1 (call-interactively cmd record-flag keys)
1908 (when (and (symbolp cmd)
1909 (get cmd 'byte-obsolete-info)
1910 (not (get cmd 'command-execute-obsolete-warned)))
1911 (put cmd 'command-execute-obsolete-warned t)
1912 (message "%s" (macroexp--obsolete-warning
1913 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1915 (defvar minibuffer-history nil
1916 "Default minibuffer history list.
1917 This is used for all minibuffer input
1918 except when an alternate history list is specified.
1920 Maximum length of the history list is determined by the value
1921 of `history-length', which see.")
1922 (defvar minibuffer-history-sexp-flag nil
1923 "Control whether history list elements are expressions or strings.
1924 If the value of this variable equals current minibuffer depth,
1925 they are expressions; otherwise they are strings.
1926 \(That convention is designed to do the right thing for
1927 recursive uses of the minibuffer.)")
1928 (setq minibuffer-history-variable 'minibuffer-history)
1929 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1930 (defvar minibuffer-history-search-history nil)
1932 (defvar minibuffer-text-before-history nil
1933 "Text that was in this minibuffer before any history commands.
1934 This is nil if there have not yet been any history commands
1935 in this use of the minibuffer.")
1937 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1939 (defun minibuffer-history-initialize ()
1940 (setq minibuffer-text-before-history nil))
1942 (defun minibuffer-avoid-prompt (_new _old)
1943 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1944 (declare (obsolete cursor-intangible-mode "25.1"))
1945 (constrain-to-field nil (point-max)))
1947 (defcustom minibuffer-history-case-insensitive-variables nil
1948 "Minibuffer history variables for which matching should ignore case.
1949 If a history variable is a member of this list, then the
1950 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1951 commands ignore case when searching it, regardless of `case-fold-search'."
1952 :type '(repeat variable)
1953 :group 'minibuffer)
1955 (defun previous-matching-history-element (regexp n)
1956 "Find the previous history element that matches REGEXP.
1957 \(Previous history elements refer to earlier actions.)
1958 With prefix argument N, search for Nth previous match.
1959 If N is negative, find the next or Nth next match.
1960 Normally, history elements are matched case-insensitively if
1961 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1962 makes the search case-sensitive.
1963 See also `minibuffer-history-case-insensitive-variables'."
1964 (interactive
1965 (let* ((enable-recursive-minibuffers t)
1966 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1968 minibuffer-local-map
1970 'minibuffer-history-search-history
1971 (car minibuffer-history-search-history))))
1972 ;; Use the last regexp specified, by default, if input is empty.
1973 (list (if (string= regexp "")
1974 (if minibuffer-history-search-history
1975 (car minibuffer-history-search-history)
1976 (user-error "No previous history search regexp"))
1977 regexp)
1978 (prefix-numeric-value current-prefix-arg))))
1979 (unless (zerop n)
1980 (if (and (zerop minibuffer-history-position)
1981 (null minibuffer-text-before-history))
1982 (setq minibuffer-text-before-history
1983 (minibuffer-contents-no-properties)))
1984 (let ((history (symbol-value minibuffer-history-variable))
1985 (case-fold-search
1986 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1987 ;; On some systems, ignore case for file names.
1988 (if (memq minibuffer-history-variable
1989 minibuffer-history-case-insensitive-variables)
1991 ;; Respect the user's setting for case-fold-search:
1992 case-fold-search)
1993 nil))
1994 prevpos
1995 match-string
1996 match-offset
1997 (pos minibuffer-history-position))
1998 (while (/= n 0)
1999 (setq prevpos pos)
2000 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
2001 (when (= pos prevpos)
2002 (user-error (if (= pos 1)
2003 "No later matching history item"
2004 "No earlier matching history item")))
2005 (setq match-string
2006 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
2007 (let ((print-level nil))
2008 (prin1-to-string (nth (1- pos) history)))
2009 (nth (1- pos) history)))
2010 (setq match-offset
2011 (if (< n 0)
2012 (and (string-match regexp match-string)
2013 (match-end 0))
2014 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
2015 (match-beginning 1))))
2016 (when match-offset
2017 (setq n (+ n (if (< n 0) 1 -1)))))
2018 (setq minibuffer-history-position pos)
2019 (goto-char (point-max))
2020 (delete-minibuffer-contents)
2021 (insert match-string)
2022 (goto-char (+ (minibuffer-prompt-end) match-offset))))
2023 (if (memq (car (car command-history)) '(previous-matching-history-element
2024 next-matching-history-element))
2025 (setq command-history (cdr command-history))))
2027 (defun next-matching-history-element (regexp n)
2028 "Find the next history element that matches REGEXP.
2029 \(The next history element refers to a more recent action.)
2030 With prefix argument N, search for Nth next match.
2031 If N is negative, find the previous or Nth previous match.
2032 Normally, history elements are matched case-insensitively if
2033 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
2034 makes the search case-sensitive."
2035 (interactive
2036 (let* ((enable-recursive-minibuffers t)
2037 (regexp (read-from-minibuffer "Next element matching (regexp): "
2039 minibuffer-local-map
2041 'minibuffer-history-search-history
2042 (car minibuffer-history-search-history))))
2043 ;; Use the last regexp specified, by default, if input is empty.
2044 (list (if (string= regexp "")
2045 (if minibuffer-history-search-history
2046 (car minibuffer-history-search-history)
2047 (user-error "No previous history search regexp"))
2048 regexp)
2049 (prefix-numeric-value current-prefix-arg))))
2050 (previous-matching-history-element regexp (- n)))
2052 (defvar minibuffer-temporary-goal-position nil)
2054 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
2055 "Function run by `goto-history-element' before consuming default values.
2056 This is useful to dynamically add more elements to the list of default values
2057 when `goto-history-element' reaches the end of this list.
2058 Before calling this function `goto-history-element' sets the variable
2059 `minibuffer-default-add-done' to t, so it will call this function only
2060 once. In special cases, when this function needs to be called more
2061 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2062 overriding the setting of this variable to t in `goto-history-element'.")
2064 (defvar minibuffer-default-add-done nil
2065 "When nil, add more elements to the end of the list of default values.
2066 The value nil causes `goto-history-element' to add more elements to
2067 the list of defaults when it reaches the end of this list. It does
2068 this by calling a function defined by `minibuffer-default-add-function'.")
2070 (make-variable-buffer-local 'minibuffer-default-add-done)
2072 (defun minibuffer-default-add-completions ()
2073 "Return a list of all completions without the default value.
2074 This function is used to add all elements of the completion table to
2075 the end of the list of defaults just after the default value."
2076 (let ((def minibuffer-default)
2077 (all (all-completions ""
2078 minibuffer-completion-table
2079 minibuffer-completion-predicate)))
2080 (if (listp def)
2081 (append def all)
2082 (cons def (delete def all)))))
2084 (defun goto-history-element (nabs)
2085 "Puts element of the minibuffer history in the minibuffer.
2086 The argument NABS specifies the absolute history position."
2087 (interactive "p")
2088 (when (and (not minibuffer-default-add-done)
2089 (functionp minibuffer-default-add-function)
2090 (< nabs (- (if (listp minibuffer-default)
2091 (length minibuffer-default)
2092 1))))
2093 (setq minibuffer-default-add-done t
2094 minibuffer-default (funcall minibuffer-default-add-function)))
2095 (let ((minimum (if minibuffer-default
2096 (- (if (listp minibuffer-default)
2097 (length minibuffer-default)
2100 elt minibuffer-returned-to-present)
2101 (if (and (zerop minibuffer-history-position)
2102 (null minibuffer-text-before-history))
2103 (setq minibuffer-text-before-history
2104 (minibuffer-contents-no-properties)))
2105 (if (< nabs minimum)
2106 (user-error (if minibuffer-default
2107 "End of defaults; no next item"
2108 "End of history; no default available")))
2109 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2110 (length (symbol-value minibuffer-history-variable))
2112 (user-error "Beginning of history; no preceding item"))
2113 (unless (memq last-command '(next-history-element
2114 previous-history-element))
2115 (let ((prompt-end (minibuffer-prompt-end)))
2116 (set (make-local-variable 'minibuffer-temporary-goal-position)
2117 (cond ((<= (point) prompt-end) prompt-end)
2118 ((eobp) nil)
2119 (t (point))))))
2120 (goto-char (point-max))
2121 (delete-minibuffer-contents)
2122 (setq minibuffer-history-position nabs)
2123 (cond ((< nabs 0)
2124 (setq elt (if (listp minibuffer-default)
2125 (nth (1- (abs nabs)) minibuffer-default)
2126 minibuffer-default)))
2127 ((= nabs 0)
2128 (setq elt (or minibuffer-text-before-history ""))
2129 (setq minibuffer-returned-to-present t)
2130 (setq minibuffer-text-before-history nil))
2131 (t (setq elt (nth (1- minibuffer-history-position)
2132 (symbol-value minibuffer-history-variable)))))
2133 (insert
2134 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2135 (not minibuffer-returned-to-present))
2136 (let ((print-level nil))
2137 (prin1-to-string elt))
2138 elt))
2139 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2141 (defun next-history-element (n)
2142 "Puts next element of the minibuffer history in the minibuffer.
2143 With argument N, it uses the Nth following element."
2144 (interactive "p")
2145 (or (zerop n)
2146 (goto-history-element (- minibuffer-history-position n))))
2148 (defun previous-history-element (n)
2149 "Puts previous element of the minibuffer history in the minibuffer.
2150 With argument N, it uses the Nth previous element."
2151 (interactive "p")
2152 (or (zerop n)
2153 (goto-history-element (+ minibuffer-history-position n))))
2155 (defun next-line-or-history-element (&optional arg)
2156 "Move cursor vertically down ARG lines, or to the next history element.
2157 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2158 next element of the minibuffer history in the minibuffer."
2159 (interactive "^p")
2160 (or arg (setq arg 1))
2161 (let* ((old-point (point))
2162 ;; Don't add newlines if they have the mode enabled globally.
2163 (next-line-add-newlines nil)
2164 ;; Remember the original goal column of possibly multi-line input
2165 ;; excluding the length of the prompt on the first line.
2166 (prompt-end (minibuffer-prompt-end))
2167 (old-column (unless (and (eolp) (> (point) prompt-end))
2168 (if (= (line-number-at-pos) 1)
2169 (max (- (current-column) (1- prompt-end)) 0)
2170 (current-column)))))
2171 (condition-case nil
2172 (with-no-warnings
2173 (next-line arg))
2174 (end-of-buffer
2175 ;; Restore old position since `line-move-visual' moves point to
2176 ;; the end of the line when it fails to go to the next line.
2177 (goto-char old-point)
2178 (next-history-element arg)
2179 ;; Reset `temporary-goal-column' because a correct value is not
2180 ;; calculated when `next-line' above fails by bumping against
2181 ;; the bottom of the minibuffer (bug#22544).
2182 (setq temporary-goal-column 0)
2183 ;; Restore the original goal column on the last line
2184 ;; of possibly multi-line input.
2185 (goto-char (point-max))
2186 (when old-column
2187 (if (= (line-number-at-pos) 1)
2188 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2189 (move-to-column old-column)))))))
2191 (defun previous-line-or-history-element (&optional arg)
2192 "Move cursor vertically up ARG lines, or to the previous history element.
2193 When point moves over the top line of multi-line minibuffer, puts ARGth
2194 previous element of the minibuffer history in the minibuffer."
2195 (interactive "^p")
2196 (or arg (setq arg 1))
2197 (let* ((old-point (point))
2198 ;; Remember the original goal column of possibly multi-line input
2199 ;; excluding the length of the prompt on the first line.
2200 (prompt-end (minibuffer-prompt-end))
2201 (old-column (unless (and (eolp) (> (point) prompt-end))
2202 (if (= (line-number-at-pos) 1)
2203 (max (- (current-column) (1- prompt-end)) 0)
2204 (current-column)))))
2205 (condition-case nil
2206 (with-no-warnings
2207 (previous-line arg))
2208 (beginning-of-buffer
2209 ;; Restore old position since `line-move-visual' moves point to
2210 ;; the beginning of the line when it fails to go to the previous line.
2211 (goto-char old-point)
2212 (previous-history-element arg)
2213 ;; Reset `temporary-goal-column' because a correct value is not
2214 ;; calculated when `previous-line' above fails by bumping against
2215 ;; the top of the minibuffer (bug#22544).
2216 (setq temporary-goal-column 0)
2217 ;; Restore the original goal column on the first line
2218 ;; of possibly multi-line input.
2219 (goto-char (minibuffer-prompt-end))
2220 (if old-column
2221 (if (= (line-number-at-pos) 1)
2222 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2223 (move-to-column old-column))
2224 ;; Put the cursor at the end of the visual line instead of the
2225 ;; logical line, so the next `previous-line-or-history-element'
2226 ;; would move to the previous history element, not to a possible upper
2227 ;; visual line from the end of logical line in `line-move-visual' mode.
2228 (end-of-visual-line)
2229 ;; Since `end-of-visual-line' puts the cursor at the beginning
2230 ;; of the next visual line, move it one char back to the end
2231 ;; of the first visual line (bug#22544).
2232 (unless (eolp) (backward-char 1)))))))
2234 (defun next-complete-history-element (n)
2235 "Get next history element which completes the minibuffer before the point.
2236 The contents of the minibuffer after the point are deleted, and replaced
2237 by the new completion."
2238 (interactive "p")
2239 (let ((point-at-start (point)))
2240 (next-matching-history-element
2241 (concat
2242 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2244 ;; next-matching-history-element always puts us at (point-min).
2245 ;; Move to the position we were at before changing the buffer contents.
2246 ;; This is still sensible, because the text before point has not changed.
2247 (goto-char point-at-start)))
2249 (defun previous-complete-history-element (n)
2251 Get previous history element which completes the minibuffer before the point.
2252 The contents of the minibuffer after the point are deleted, and replaced
2253 by the new completion."
2254 (interactive "p")
2255 (next-complete-history-element (- n)))
2257 ;; For compatibility with the old subr of the same name.
2258 (defun minibuffer-prompt-width ()
2259 "Return the display width of the minibuffer prompt.
2260 Return 0 if current buffer is not a minibuffer."
2261 ;; Return the width of everything before the field at the end of
2262 ;; the buffer; this should be 0 for normal buffers.
2263 (1- (minibuffer-prompt-end)))
2265 ;; isearch minibuffer history
2266 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2268 (defvar minibuffer-history-isearch-message-overlay)
2269 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2271 (defun minibuffer-history-isearch-setup ()
2272 "Set up a minibuffer for using isearch to search the minibuffer history.
2273 Intended to be added to `minibuffer-setup-hook'."
2274 (set (make-local-variable 'isearch-search-fun-function)
2275 'minibuffer-history-isearch-search)
2276 (set (make-local-variable 'isearch-message-function)
2277 'minibuffer-history-isearch-message)
2278 (set (make-local-variable 'isearch-wrap-function)
2279 'minibuffer-history-isearch-wrap)
2280 (set (make-local-variable 'isearch-push-state-function)
2281 'minibuffer-history-isearch-push-state)
2282 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2284 (defun minibuffer-history-isearch-end ()
2285 "Clean up the minibuffer after terminating isearch in the minibuffer."
2286 (if minibuffer-history-isearch-message-overlay
2287 (delete-overlay minibuffer-history-isearch-message-overlay)))
2289 (defun minibuffer-history-isearch-search ()
2290 "Return the proper search function, for isearch in minibuffer history."
2291 (lambda (string bound noerror)
2292 (let ((search-fun
2293 ;; Use standard functions to search within minibuffer text
2294 (isearch-search-fun-default))
2295 found)
2296 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2297 ;; searching forward. Lazy-highlight calls this lambda with the
2298 ;; bound arg, so skip the minibuffer prompt.
2299 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2300 (goto-char (minibuffer-prompt-end)))
2302 ;; 1. First try searching in the initial minibuffer text
2303 (funcall search-fun string
2304 (if isearch-forward bound (minibuffer-prompt-end))
2305 noerror)
2306 ;; 2. If the above search fails, start putting next/prev history
2307 ;; elements in the minibuffer successively, and search the string
2308 ;; in them. Do this only when bound is nil (i.e. not while
2309 ;; lazy-highlighting search strings in the current minibuffer text).
2310 (unless bound
2311 (condition-case nil
2312 (progn
2313 (while (not found)
2314 (cond (isearch-forward
2315 (next-history-element 1)
2316 (goto-char (minibuffer-prompt-end)))
2318 (previous-history-element 1)
2319 (goto-char (point-max))))
2320 (setq isearch-barrier (point) isearch-opoint (point))
2321 ;; After putting the next/prev history element, search
2322 ;; the string in them again, until next-history-element
2323 ;; or previous-history-element raises an error at the
2324 ;; beginning/end of history.
2325 (setq found (funcall search-fun string
2326 (unless isearch-forward
2327 ;; For backward search, don't search
2328 ;; in the minibuffer prompt
2329 (minibuffer-prompt-end))
2330 noerror)))
2331 ;; Return point of the new search result
2332 (point))
2333 ;; Return nil when next(prev)-history-element fails
2334 (error nil)))))))
2336 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2337 "Display the minibuffer history search prompt.
2338 If there are no search errors, this function displays an overlay with
2339 the isearch prompt which replaces the original minibuffer prompt.
2340 Otherwise, it displays the standard isearch message returned from
2341 the function `isearch-message'."
2342 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2343 ;; Use standard function `isearch-message' when not in the minibuffer,
2344 ;; or search fails, or has an error (like incomplete regexp).
2345 ;; This function overwrites minibuffer text with isearch message,
2346 ;; so it's possible to see what is wrong in the search string.
2347 (isearch-message c-q-hack ellipsis)
2348 ;; Otherwise, put the overlay with the standard isearch prompt over
2349 ;; the initial minibuffer prompt.
2350 (if (overlayp minibuffer-history-isearch-message-overlay)
2351 (move-overlay minibuffer-history-isearch-message-overlay
2352 (point-min) (minibuffer-prompt-end))
2353 (setq minibuffer-history-isearch-message-overlay
2354 (make-overlay (point-min) (minibuffer-prompt-end)))
2355 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2356 (overlay-put minibuffer-history-isearch-message-overlay
2357 'display (isearch-message-prefix c-q-hack ellipsis))
2358 ;; And clear any previous isearch message.
2359 (message "")))
2361 (defun minibuffer-history-isearch-wrap ()
2362 "Wrap the minibuffer history search when search fails.
2363 Move point to the first history element for a forward search,
2364 or to the last history element for a backward search."
2365 ;; When `minibuffer-history-isearch-search' fails on reaching the
2366 ;; beginning/end of the history, wrap the search to the first/last
2367 ;; minibuffer history element.
2368 (if isearch-forward
2369 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2370 (goto-history-element 0))
2371 (setq isearch-success t)
2372 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2374 (defun minibuffer-history-isearch-push-state ()
2375 "Save a function restoring the state of minibuffer history search.
2376 Save `minibuffer-history-position' to the additional state parameter
2377 in the search status stack."
2378 (let ((pos minibuffer-history-position))
2379 (lambda (cmd)
2380 (minibuffer-history-isearch-pop-state cmd pos))))
2382 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2383 "Restore the minibuffer history search state.
2384 Go to the history element by the absolute history position HIST-POS."
2385 (goto-history-element hist-pos))
2388 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2389 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2391 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2392 "Table mapping redo records to the corresponding undo one.
2393 A redo record for undo-in-region maps to t.
2394 A redo record for ordinary undo maps to the following (earlier) undo.")
2396 (defvar undo-in-region nil
2397 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2399 (defvar undo-no-redo nil
2400 "If t, `undo' doesn't go through redo entries.")
2402 (defvar pending-undo-list nil
2403 "Within a run of consecutive undo commands, list remaining to be undone.
2404 If t, we undid all the way to the end of it.")
2406 (defun undo (&optional arg)
2407 "Undo some previous changes.
2408 Repeat this command to undo more changes.
2409 A numeric ARG serves as a repeat count.
2411 In Transient Mark mode when the mark is active, only undo changes within
2412 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2413 as an argument limits undo to changes within the current region."
2414 (interactive "*P")
2415 ;; Make last-command indicate for the next command that this was an undo.
2416 ;; That way, another undo will undo more.
2417 ;; If we get to the end of the undo history and get an error,
2418 ;; another undo command will find the undo history empty
2419 ;; and will get another error. To begin undoing the undos,
2420 ;; you must type some other command.
2421 (let* ((modified (buffer-modified-p))
2422 ;; For an indirect buffer, look in the base buffer for the
2423 ;; auto-save data.
2424 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2425 (recent-save (with-current-buffer base-buffer
2426 (recent-auto-save-p)))
2427 message)
2428 ;; If we get an error in undo-start,
2429 ;; the next command should not be a "consecutive undo".
2430 ;; So set `this-command' to something other than `undo'.
2431 (setq this-command 'undo-start)
2433 (unless (and (eq last-command 'undo)
2434 (or (eq pending-undo-list t)
2435 ;; If something (a timer or filter?) changed the buffer
2436 ;; since the previous command, don't continue the undo seq.
2437 (let ((list buffer-undo-list))
2438 (while (eq (car list) nil)
2439 (setq list (cdr list)))
2440 ;; If the last undo record made was made by undo
2441 ;; it shows nothing else happened in between.
2442 (gethash list undo-equiv-table))))
2443 (setq undo-in-region
2444 (or (region-active-p) (and arg (not (numberp arg)))))
2445 (if undo-in-region
2446 (undo-start (region-beginning) (region-end))
2447 (undo-start))
2448 ;; get rid of initial undo boundary
2449 (undo-more 1))
2450 ;; If we got this far, the next command should be a consecutive undo.
2451 (setq this-command 'undo)
2452 ;; Check to see whether we're hitting a redo record, and if
2453 ;; so, ask the user whether she wants to skip the redo/undo pair.
2454 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2455 (or (eq (selected-window) (minibuffer-window))
2456 (setq message (format "%s%s!"
2457 (if (or undo-no-redo (not equiv))
2458 "Undo" "Redo")
2459 (if undo-in-region " in region" ""))))
2460 (when (and (consp equiv) undo-no-redo)
2461 ;; The equiv entry might point to another redo record if we have done
2462 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2463 (while (let ((next (gethash equiv undo-equiv-table)))
2464 (if next (setq equiv next))))
2465 (setq pending-undo-list equiv)))
2466 (undo-more
2467 (if (numberp arg)
2468 (prefix-numeric-value arg)
2470 ;; Record the fact that the just-generated undo records come from an
2471 ;; undo operation--that is, they are redo records.
2472 ;; In the ordinary case (not within a region), map the redo
2473 ;; record to the following undos.
2474 ;; I don't know how to do that in the undo-in-region case.
2475 (let ((list buffer-undo-list))
2476 ;; Strip any leading undo boundaries there might be, like we do
2477 ;; above when checking.
2478 (while (eq (car list) nil)
2479 (setq list (cdr list)))
2480 (puthash list
2481 ;; Prevent identity mapping. This can happen if
2482 ;; consecutive nils are erroneously in undo list.
2483 (if (or undo-in-region (eq list pending-undo-list))
2485 pending-undo-list)
2486 undo-equiv-table))
2487 ;; Don't specify a position in the undo record for the undo command.
2488 ;; Instead, undoing this should move point to where the change is.
2489 (let ((tail buffer-undo-list)
2490 (prev nil))
2491 (while (car tail)
2492 (when (integerp (car tail))
2493 (let ((pos (car tail)))
2494 (if prev
2495 (setcdr prev (cdr tail))
2496 (setq buffer-undo-list (cdr tail)))
2497 (setq tail (cdr tail))
2498 (while (car tail)
2499 (if (eq pos (car tail))
2500 (if prev
2501 (setcdr prev (cdr tail))
2502 (setq buffer-undo-list (cdr tail)))
2503 (setq prev tail))
2504 (setq tail (cdr tail)))
2505 (setq tail nil)))
2506 (setq prev tail tail (cdr tail))))
2507 ;; Record what the current undo list says,
2508 ;; so the next command can tell if the buffer was modified in between.
2509 (and modified (not (buffer-modified-p))
2510 (with-current-buffer base-buffer
2511 (delete-auto-save-file-if-necessary recent-save)))
2512 ;; Display a message announcing success.
2513 (if message
2514 (message "%s" message))))
2516 (defun buffer-disable-undo (&optional buffer)
2517 "Make BUFFER stop keeping undo information.
2518 No argument or nil as argument means do this for the current buffer."
2519 (interactive)
2520 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2521 (setq buffer-undo-list t)))
2523 (defun undo-only (&optional arg)
2524 "Undo some previous changes.
2525 Repeat this command to undo more changes.
2526 A numeric ARG serves as a repeat count.
2527 Contrary to `undo', this will not redo a previous undo."
2528 (interactive "*p")
2529 (let ((undo-no-redo t)) (undo arg)))
2531 (defvar undo-in-progress nil
2532 "Non-nil while performing an undo.
2533 Some change-hooks test this variable to do something different.")
2535 (defun undo-more (n)
2536 "Undo back N undo-boundaries beyond what was already undone recently.
2537 Call `undo-start' to get ready to undo recent changes,
2538 then call `undo-more' one or more times to undo them."
2539 (or (listp pending-undo-list)
2540 (user-error (concat "No further undo information"
2541 (and undo-in-region " for region"))))
2542 (let ((undo-in-progress t))
2543 ;; Note: The following, while pulling elements off
2544 ;; `pending-undo-list' will call primitive change functions which
2545 ;; will push more elements onto `buffer-undo-list'.
2546 (setq pending-undo-list (primitive-undo n pending-undo-list))
2547 (if (null pending-undo-list)
2548 (setq pending-undo-list t))))
2550 (defun primitive-undo (n list)
2551 "Undo N records from the front of the list LIST.
2552 Return what remains of the list."
2554 ;; This is a good feature, but would make undo-start
2555 ;; unable to do what is expected.
2556 ;;(when (null (car (list)))
2557 ;; ;; If the head of the list is a boundary, it is the boundary
2558 ;; ;; preceding this command. Get rid of it and don't count it.
2559 ;; (setq list (cdr list))))
2561 (let ((arg n)
2562 ;; In a writable buffer, enable undoing read-only text that is
2563 ;; so because of text properties.
2564 (inhibit-read-only t)
2565 ;; Don't let `intangible' properties interfere with undo.
2566 (inhibit-point-motion-hooks t)
2567 ;; We use oldlist only to check for EQ. ++kfs
2568 (oldlist buffer-undo-list)
2569 (did-apply nil)
2570 (next nil))
2571 (while (> arg 0)
2572 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2573 ;; Handle an integer by setting point to that value.
2574 (pcase next
2575 ((pred integerp) (goto-char next))
2576 ;; Element (t . TIME) records previous modtime.
2577 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2578 ;; UNKNOWN_MODTIME_NSECS.
2579 (`(t . ,time)
2580 ;; If this records an obsolete save
2581 ;; (not matching the actual disk file)
2582 ;; then don't mark unmodified.
2583 (when (or (equal time (visited-file-modtime))
2584 (and (consp time)
2585 (equal (list (car time) (cdr time))
2586 (visited-file-modtime))))
2587 (when (fboundp 'unlock-buffer)
2588 (unlock-buffer))
2589 (set-buffer-modified-p nil)))
2590 ;; Element (nil PROP VAL BEG . END) is property change.
2591 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2592 (when (or (> (point-min) beg) (< (point-max) end))
2593 (error "Changes to be undone are outside visible portion of buffer"))
2594 (put-text-property beg end prop val))
2595 ;; Element (BEG . END) means range was inserted.
2596 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2597 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2598 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2599 (when (or (> (point-min) beg) (< (point-max) end))
2600 (error "Changes to be undone are outside visible portion of buffer"))
2601 ;; Set point first thing, so that undoing this undo
2602 ;; does not send point back to where it is now.
2603 (goto-char beg)
2604 (delete-region beg end))
2605 ;; Element (apply FUN . ARGS) means call FUN to undo.
2606 (`(apply . ,fun-args)
2607 (let ((currbuff (current-buffer)))
2608 (if (integerp (car fun-args))
2609 ;; Long format: (apply DELTA START END FUN . ARGS).
2610 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2611 (start-mark (copy-marker start nil))
2612 (end-mark (copy-marker end t)))
2613 (when (or (> (point-min) start) (< (point-max) end))
2614 (error "Changes to be undone are outside visible portion of buffer"))
2615 (apply fun args) ;; Use `save-current-buffer'?
2616 ;; Check that the function did what the entry
2617 ;; said it would do.
2618 (unless (and (= start start-mark)
2619 (= (+ delta end) end-mark))
2620 (error "Changes to be undone by function different than announced"))
2621 (set-marker start-mark nil)
2622 (set-marker end-mark nil))
2623 (apply fun-args))
2624 (unless (eq currbuff (current-buffer))
2625 (error "Undo function switched buffer"))
2626 (setq did-apply t)))
2627 ;; Element (STRING . POS) means STRING was deleted.
2628 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2629 (let ((valid-marker-adjustments nil)
2630 (apos (abs pos)))
2631 (when (or (< apos (point-min)) (> apos (point-max)))
2632 (error "Changes to be undone are outside visible portion of buffer"))
2633 ;; Check that marker adjustments which were recorded
2634 ;; with the (STRING . POS) record are still valid, ie
2635 ;; the markers haven't moved. We check their validity
2636 ;; before reinserting the string so as we don't need to
2637 ;; mind marker insertion-type.
2638 (while (and (markerp (car-safe (car list)))
2639 (integerp (cdr-safe (car list))))
2640 (let* ((marker-adj (pop list))
2641 (m (car marker-adj)))
2642 (and (eq (marker-buffer m) (current-buffer))
2643 (= apos m)
2644 (push marker-adj valid-marker-adjustments))))
2645 ;; Insert string and adjust point
2646 (if (< pos 0)
2647 (progn
2648 (goto-char (- pos))
2649 (insert string))
2650 (goto-char pos)
2651 (insert string)
2652 (goto-char pos))
2653 ;; Adjust the valid marker adjustments
2654 (dolist (adj valid-marker-adjustments)
2655 ;; Insert might have invalidated some of the markers
2656 ;; via modification hooks. Update only the currently
2657 ;; valid ones (bug#25599).
2658 (if (marker-buffer (car adj))
2659 (set-marker (car adj)
2660 (- (car adj) (cdr adj)))))))
2661 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2662 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2663 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2664 next)
2665 ;; Even though these elements are not expected in the undo
2666 ;; list, adjust them to be conservative for the 24.4
2667 ;; release. (Bug#16818)
2668 (when (marker-buffer marker)
2669 (set-marker marker
2670 (- marker offset)
2671 (marker-buffer marker))))
2672 (_ (error "Unrecognized entry in undo list %S" next))))
2673 (setq arg (1- arg)))
2674 ;; Make sure an apply entry produces at least one undo entry,
2675 ;; so the test in `undo' for continuing an undo series
2676 ;; will work right.
2677 (if (and did-apply
2678 (eq oldlist buffer-undo-list))
2679 (setq buffer-undo-list
2680 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2681 list)
2683 ;; Deep copy of a list
2684 (defun undo-copy-list (list)
2685 "Make a copy of undo list LIST."
2686 (mapcar 'undo-copy-list-1 list))
2688 (defun undo-copy-list-1 (elt)
2689 (if (consp elt)
2690 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2691 elt))
2693 (defun undo-start (&optional beg end)
2694 "Set `pending-undo-list' to the front of the undo list.
2695 The next call to `undo-more' will undo the most recently made change.
2696 If BEG and END are specified, then only undo elements
2697 that apply to text between BEG and END are used; other undo elements
2698 are ignored. If BEG and END are nil, all undo elements are used."
2699 (if (eq buffer-undo-list t)
2700 (user-error "No undo information in this buffer"))
2701 (setq pending-undo-list
2702 (if (and beg end (not (= beg end)))
2703 (undo-make-selective-list (min beg end) (max beg end))
2704 buffer-undo-list)))
2706 ;; The positions given in elements of the undo list are the positions
2707 ;; as of the time that element was recorded to undo history. In
2708 ;; general, subsequent buffer edits render those positions invalid in
2709 ;; the current buffer, unless adjusted according to the intervening
2710 ;; undo elements.
2712 ;; Undo in region is a use case that requires adjustments to undo
2713 ;; elements. It must adjust positions of elements in the region based
2714 ;; on newer elements not in the region so as they may be correctly
2715 ;; applied in the current buffer. undo-make-selective-list
2716 ;; accomplishes this with its undo-deltas list of adjustments. An
2717 ;; example undo history from oldest to newest:
2719 ;; buf pos:
2720 ;; 123456789 buffer-undo-list undo-deltas
2721 ;; --------- ---------------- -----------
2722 ;; aaa (1 . 4) (1 . -3)
2723 ;; aaba (3 . 4) N/A (in region)
2724 ;; ccaaba (1 . 3) (1 . -2)
2725 ;; ccaabaddd (7 . 10) (7 . -3)
2726 ;; ccaabdd ("ad" . 6) (6 . 2)
2727 ;; ccaabaddd (6 . 8) (6 . -2)
2728 ;; | |<-- region: "caab", from 2 to 6
2730 ;; When the user starts a run of undos in region,
2731 ;; undo-make-selective-list is called to create the full list of in
2732 ;; region elements. Each element is adjusted forward chronologically
2733 ;; through undo-deltas to determine if it is in the region.
2735 ;; In the above example, the insertion of "b" is (3 . 4) in the
2736 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2737 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2738 ;; . 6) is assessed as in the region and placed in the selective list.
2739 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2740 ;; due to the selected element. The "b" insertion is the only element
2741 ;; fully in the region, so in this example undo-make-selective-list
2742 ;; returns (nil (5 . 6)).
2744 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2745 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2746 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2747 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2748 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2750 ;; More interesting is how to adjust the "ddd" insertion due to the
2751 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2752 ;; If the reinsertion was a manual retyping of "ad", then the total
2753 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2754 ;; the reinsertion was due to undo, one might expect the first "d"
2755 ;; character would again be a part of the "ddd" text, meaning its
2756 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2758 ;; undo-make-selective-list assumes in this situation that "ad" was a
2759 ;; new edit, even if it was inserted because of an undo.
2760 ;; Consequently, if the user undos in region "8 to 10" of the
2761 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2762 ;; "ccaabad", as though the first "d" became detached from the
2763 ;; original "ddd" insertion. This quirk is a FIXME.
2765 (defun undo-make-selective-list (start end)
2766 "Return a list of undo elements for the region START to END.
2767 The elements come from `buffer-undo-list', but we keep only the
2768 elements inside this region, and discard those outside this
2769 region. The elements' positions are adjusted so as the returned
2770 list can be applied to the current buffer."
2771 (let ((ulist buffer-undo-list)
2772 ;; A list of position adjusted undo elements in the region.
2773 (selective-list (list nil))
2774 ;; A list of undo-deltas for out of region undo elements.
2775 undo-deltas
2776 undo-elt)
2777 (while ulist
2778 (when undo-no-redo
2779 (while (gethash ulist undo-equiv-table)
2780 (setq ulist (gethash ulist undo-equiv-table))))
2781 (setq undo-elt (car ulist))
2782 (cond
2783 ((null undo-elt)
2784 ;; Don't put two nils together in the list
2785 (when (car selective-list)
2786 (push nil selective-list)))
2787 ((and (consp undo-elt) (eq (car undo-elt) t))
2788 ;; This is a "was unmodified" element. Keep it
2789 ;; if we have kept everything thus far.
2790 (when (not undo-deltas)
2791 (push undo-elt selective-list)))
2792 ;; Skip over marker adjustments, instead relying
2793 ;; on finding them after (TEXT . POS) elements
2794 ((markerp (car-safe undo-elt))
2795 nil)
2797 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2798 undo-deltas)))
2799 (if (undo-elt-in-region adjusted-undo-elt start end)
2800 (progn
2801 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2802 (push adjusted-undo-elt selective-list)
2803 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2804 ;; kept. primitive-undo may discard them later.
2805 (when (and (stringp (car-safe adjusted-undo-elt))
2806 (integerp (cdr-safe adjusted-undo-elt)))
2807 (let ((list-i (cdr ulist)))
2808 (while (markerp (car-safe (car list-i)))
2809 (push (pop list-i) selective-list)))))
2810 (let ((delta (undo-delta undo-elt)))
2811 (when (/= 0 (cdr delta))
2812 (push delta undo-deltas)))))))
2813 (pop ulist))
2814 (nreverse selective-list)))
2816 (defun undo-elt-in-region (undo-elt start end)
2817 "Determine whether UNDO-ELT falls inside the region START ... END.
2818 If it crosses the edge, we return nil.
2820 Generally this function is not useful for determining
2821 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2822 because markers can be arbitrarily relocated. Instead, pass the
2823 marker adjustment's corresponding (TEXT . POS) element."
2824 (cond ((integerp undo-elt)
2825 (and (>= undo-elt start)
2826 (<= undo-elt end)))
2827 ((eq undo-elt nil)
2829 ((atom undo-elt)
2830 nil)
2831 ((stringp (car undo-elt))
2832 ;; (TEXT . POSITION)
2833 (and (>= (abs (cdr undo-elt)) start)
2834 (<= (abs (cdr undo-elt)) end)))
2835 ((and (consp undo-elt) (markerp (car undo-elt)))
2836 ;; (MARKER . ADJUSTMENT)
2837 (<= start (car undo-elt) end))
2838 ((null (car undo-elt))
2839 ;; (nil PROPERTY VALUE BEG . END)
2840 (let ((tail (nthcdr 3 undo-elt)))
2841 (and (>= (car tail) start)
2842 (<= (cdr tail) end))))
2843 ((integerp (car undo-elt))
2844 ;; (BEGIN . END)
2845 (and (>= (car undo-elt) start)
2846 (<= (cdr undo-elt) end)))))
2848 (defun undo-elt-crosses-region (undo-elt start end)
2849 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2850 This assumes we have already decided that UNDO-ELT
2851 is not *inside* the region START...END."
2852 (declare (obsolete nil "25.1"))
2853 (cond ((atom undo-elt) nil)
2854 ((null (car undo-elt))
2855 ;; (nil PROPERTY VALUE BEG . END)
2856 (let ((tail (nthcdr 3 undo-elt)))
2857 (and (< (car tail) end)
2858 (> (cdr tail) start))))
2859 ((integerp (car undo-elt))
2860 ;; (BEGIN . END)
2861 (and (< (car undo-elt) end)
2862 (> (cdr undo-elt) start)))))
2864 (defun undo-adjust-elt (elt deltas)
2865 "Return adjustment of undo element ELT by the undo DELTAS
2866 list."
2867 (pcase elt
2868 ;; POSITION
2869 ((pred integerp)
2870 (undo-adjust-pos elt deltas))
2871 ;; (BEG . END)
2872 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2873 (undo-adjust-beg-end beg end deltas))
2874 ;; (TEXT . POSITION)
2875 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2876 (cons text (* (if (< pos 0) -1 1)
2877 (undo-adjust-pos (abs pos) deltas))))
2878 ;; (nil PROPERTY VALUE BEG . END)
2879 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2880 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2881 ;; (apply DELTA START END FUN . ARGS)
2882 ;; FIXME
2883 ;; All others return same elt
2884 (_ elt)))
2886 ;; (BEG . END) can adjust to the same positions, commonly when an
2887 ;; insertion was undone and they are out of region, for example:
2889 ;; buf pos:
2890 ;; 123456789 buffer-undo-list undo-deltas
2891 ;; --------- ---------------- -----------
2892 ;; [...]
2893 ;; abbaa (2 . 4) (2 . -2)
2894 ;; aaa ("bb" . 2) (2 . 2)
2895 ;; [...]
2897 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2898 ;; undo. Further adjustments to such an element should be the same as
2899 ;; for (TEXT . POSITION) elements. The options are:
2901 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2902 ;; analogous to marker insertion-type t.
2904 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2905 ;; marker insertion-type nil.
2907 ;; There was no strong reason to prefer one or the other, except that
2908 ;; the first is more consistent with prior undo in region behavior.
2909 (defun undo-adjust-beg-end (beg end deltas)
2910 "Return cons of adjustments to BEG and END by the undo DELTAS
2911 list."
2912 (let ((adj-beg (undo-adjust-pos beg deltas)))
2913 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2914 (cons adj-beg
2915 (max adj-beg (undo-adjust-pos end deltas t)))))
2917 (defun undo-adjust-pos (pos deltas &optional use-<)
2918 "Return adjustment of POS by the undo DELTAS list, comparing
2919 with < or <= based on USE-<."
2920 (dolist (d deltas pos)
2921 (when (if use-<
2922 (< (car d) pos)
2923 (<= (car d) pos))
2924 (setq pos
2925 ;; Don't allow pos to become less than the undo-delta
2926 ;; position. This edge case is described in the overview
2927 ;; comments.
2928 (max (car d) (- pos (cdr d)))))))
2930 ;; Return the first affected buffer position and the delta for an undo element
2931 ;; delta is defined as the change in subsequent buffer positions if we *did*
2932 ;; the undo.
2933 (defun undo-delta (undo-elt)
2934 (if (consp undo-elt)
2935 (cond ((stringp (car undo-elt))
2936 ;; (TEXT . POSITION)
2937 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2938 ((integerp (car undo-elt))
2939 ;; (BEGIN . END)
2940 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2942 '(0 . 0)))
2943 '(0 . 0)))
2945 ;;; Default undo-boundary addition
2947 ;; This section adds a new undo-boundary at either after a command is
2948 ;; called or in some cases on a timer called after a change is made in
2949 ;; any buffer.
2950 (defvar-local undo-auto--last-boundary-cause nil
2951 "Describe the cause of the last undo-boundary.
2953 If `explicit', the last boundary was caused by an explicit call to
2954 `undo-boundary', that is one not called by the code in this
2955 section.
2957 If it is equal to `timer', then the last boundary was inserted
2958 by `undo-auto--boundary-timer'.
2960 If it is equal to `command', then the last boundary was inserted
2961 automatically after a command, that is by the code defined in
2962 this section.
2964 If it is equal to a list, then the last boundary was inserted by
2965 an amalgamating command. The car of the list is the number of
2966 times an amalgamating command has been called, and the cdr are the
2967 buffers that were changed during the last command.")
2969 (defvar undo-auto-current-boundary-timer nil
2970 "Current timer which will run `undo-auto--boundary-timer' or nil.
2972 If set to non-nil, this will effectively disable the timer.")
2974 (defvar undo-auto--this-command-amalgamating nil
2975 "Non-nil if `this-command' should be amalgamated.
2976 This variable is set to nil by `undo-auto--boundaries' and is set
2977 by `undo-auto-amalgamate'." )
2979 (defun undo-auto--needs-boundary-p ()
2980 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2981 (car-safe buffer-undo-list))
2983 (defun undo-auto--last-boundary-amalgamating-number ()
2984 "Return the number of amalgamating last commands or nil.
2985 Amalgamating commands are, by default, either
2986 `self-insert-command' and `delete-char', but can be any command
2987 that calls `undo-auto-amalgamate'."
2988 (car-safe undo-auto--last-boundary-cause))
2990 (defun undo-auto--ensure-boundary (cause)
2991 "Add an `undo-boundary' to the current buffer if needed.
2992 REASON describes the reason that the boundary is being added; see
2993 `undo-auto--last-boundary-cause' for more information."
2994 (when (and
2995 (undo-auto--needs-boundary-p))
2996 (let ((last-amalgamating
2997 (undo-auto--last-boundary-amalgamating-number)))
2998 (undo-boundary)
2999 (setq undo-auto--last-boundary-cause
3000 (if (eq 'amalgamate cause)
3001 (cons
3002 (if last-amalgamating (1+ last-amalgamating) 0)
3003 undo-auto--undoably-changed-buffers)
3004 cause)))))
3006 (defun undo-auto--boundaries (cause)
3007 "Check recently changed buffers and add a boundary if necessary.
3008 REASON describes the reason that the boundary is being added; see
3009 `undo-last-boundary' for more information."
3010 ;; (Bug #23785) All commands should ensure that there is an undo
3011 ;; boundary whether they have changed the current buffer or not.
3012 (when (eq cause 'command)
3013 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
3014 (dolist (b undo-auto--undoably-changed-buffers)
3015 (when (buffer-live-p b)
3016 (with-current-buffer b
3017 (undo-auto--ensure-boundary cause))))
3018 (setq undo-auto--undoably-changed-buffers nil))
3020 (defun undo-auto--boundary-timer ()
3021 "Timer function run by `undo-auto-current-boundary-timer'."
3022 (setq undo-auto-current-boundary-timer nil)
3023 (undo-auto--boundaries 'timer))
3025 (defun undo-auto--boundary-ensure-timer ()
3026 "Ensure that the `undo-auto-current-boundary-timer' is set."
3027 (unless undo-auto-current-boundary-timer
3028 (setq undo-auto-current-boundary-timer
3029 (run-at-time 10 nil #'undo-auto--boundary-timer))))
3031 (defvar undo-auto--undoably-changed-buffers nil
3032 "List of buffers that have changed recently.
3034 This list is maintained by `undo-auto--undoable-change' and
3035 `undo-auto--boundaries' and can be affected by changes to their
3036 default values.")
3038 (defun undo-auto--add-boundary ()
3039 "Add an `undo-boundary' in appropriate buffers."
3040 (undo-auto--boundaries
3041 (let ((amal undo-auto--this-command-amalgamating))
3042 (setq undo-auto--this-command-amalgamating nil)
3043 (if amal
3044 'amalgamate
3045 'command))))
3047 (defun undo-auto-amalgamate ()
3048 "Amalgamate undo if necessary.
3049 This function can be called before an amalgamating command. It
3050 removes the previous `undo-boundary' if a series of such calls
3051 have been made. By default `self-insert-command' and
3052 `delete-char' are the only amalgamating commands, although this
3053 function could be called by any command wishing to have this
3054 behavior."
3055 (let ((last-amalgamating-count
3056 (undo-auto--last-boundary-amalgamating-number)))
3057 (setq undo-auto--this-command-amalgamating t)
3058 (when last-amalgamating-count
3059 (if (and (< last-amalgamating-count 20)
3060 (eq this-command last-command))
3061 ;; Amalgamate all buffers that have changed.
3062 ;; This may be needed for example if some *-change-functions
3063 ;; reflected these changes in some other buffer.
3064 (dolist (b (cdr undo-auto--last-boundary-cause))
3065 (when (buffer-live-p b)
3066 (with-current-buffer
3068 (when (and (consp buffer-undo-list)
3069 ;; `car-safe' doesn't work because
3070 ;; `buffer-undo-list' need not be a list!
3071 (null (car buffer-undo-list)))
3072 ;; The head of `buffer-undo-list' is nil.
3073 (setq buffer-undo-list
3074 (cdr buffer-undo-list))))))
3075 (setq undo-auto--last-boundary-cause 0)))))
3077 (defun undo-auto--undoable-change ()
3078 "Called after every undoable buffer change."
3079 (unless (memq (current-buffer) undo-auto--undoably-changed-buffers)
3080 (let ((bufs undo-auto--undoably-changed-buffers))
3081 ;; Drop dead buffers from the list, to avoid memory leak in
3082 ;; (while t (with-temp-buffer (setq buffer-undo-list nil) (insert "a")))
3083 (while bufs
3084 (let ((next (cdr bufs)))
3085 (if (or (buffer-live-p (car bufs)) (null next))
3086 (setq bufs next)
3087 (setcar bufs (car next))
3088 (setcdr bufs (cdr next))))))
3089 (push (current-buffer) undo-auto--undoably-changed-buffers))
3090 (undo-auto--boundary-ensure-timer))
3091 ;; End auto-boundary section
3093 (defun undo-amalgamate-change-group (handle)
3094 "Amalgamate changes in change-group since HANDLE.
3095 Remove all undo boundaries between the state of HANDLE and now.
3096 HANDLE is as returned by `prepare-change-group'."
3097 (dolist (elt handle)
3098 (with-current-buffer (car elt)
3099 (setq elt (cdr elt))
3100 (when (consp buffer-undo-list)
3101 (let ((old-car (car-safe elt))
3102 (old-cdr (cdr-safe elt)))
3103 (unwind-protect
3104 (progn
3105 ;; Temporarily truncate the undo log at ELT.
3106 (when (consp elt)
3107 (setcar elt t) (setcdr elt nil))
3108 (when
3109 (or (null elt) ;The undo-log was empty.
3110 ;; `elt' is still in the log: normal case.
3111 (eq elt (last buffer-undo-list))
3112 ;; `elt' is not in the log any more, but that's because
3113 ;; the log is "all new", so we should remove all
3114 ;; boundaries from it.
3115 (not (eq (last buffer-undo-list) (last old-cdr))))
3116 (cl-callf (lambda (x) (delq nil x))
3117 (if (car buffer-undo-list)
3118 buffer-undo-list
3119 ;; Preserve the undo-boundaries at either ends of the
3120 ;; change-groups.
3121 (cdr buffer-undo-list)))))
3122 ;; Reset the modified cons cell ELT to its original content.
3123 (when (consp elt)
3124 (setcar elt old-car)
3125 (setcdr elt old-cdr))))))))
3128 (defcustom undo-ask-before-discard nil
3129 "If non-nil ask about discarding undo info for the current command.
3130 Normally, Emacs discards the undo info for the current command if
3131 it exceeds `undo-outer-limit'. But if you set this option
3132 non-nil, it asks in the echo area whether to discard the info.
3133 If you answer no, there is a slight risk that Emacs might crash, so
3134 only do it if you really want to undo the command.
3136 This option is mainly intended for debugging. You have to be
3137 careful if you use it for other purposes. Garbage collection is
3138 inhibited while the question is asked, meaning that Emacs might
3139 leak memory. So you should make sure that you do not wait
3140 excessively long before answering the question."
3141 :type 'boolean
3142 :group 'undo
3143 :version "22.1")
3145 (defvar undo-extra-outer-limit nil
3146 "If non-nil, an extra level of size that's ok in an undo item.
3147 We don't ask the user about truncating the undo list until the
3148 current item gets bigger than this amount.
3150 This variable only matters if `undo-ask-before-discard' is non-nil.")
3151 (make-variable-buffer-local 'undo-extra-outer-limit)
3153 ;; When the first undo batch in an undo list is longer than
3154 ;; undo-outer-limit, this function gets called to warn the user that
3155 ;; the undo info for the current command was discarded. Garbage
3156 ;; collection is inhibited around the call, so it had better not do a
3157 ;; lot of consing.
3158 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3159 (defun undo-outer-limit-truncate (size)
3160 (if undo-ask-before-discard
3161 (when (or (null undo-extra-outer-limit)
3162 (> size undo-extra-outer-limit))
3163 ;; Don't ask the question again unless it gets even bigger.
3164 ;; This applies, in particular, if the user quits from the question.
3165 ;; Such a quit quits out of GC, but something else will call GC
3166 ;; again momentarily. It will call this function again,
3167 ;; but we don't want to ask the question again.
3168 (setq undo-extra-outer-limit (+ size 50000))
3169 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3170 (yes-or-no-p (format-message
3171 "Buffer `%s' undo info is %d bytes long; discard it? "
3172 (buffer-name) size)))
3173 (progn (setq buffer-undo-list nil)
3174 (setq undo-extra-outer-limit nil)
3176 nil))
3177 (display-warning '(undo discard-info)
3178 (concat
3179 (format-message
3180 "Buffer `%s' undo info was %d bytes long.\n"
3181 (buffer-name) size)
3182 "The undo info was discarded because it exceeded \
3183 `undo-outer-limit'.
3185 This is normal if you executed a command that made a huge change
3186 to the buffer. In that case, to prevent similar problems in the
3187 future, set `undo-outer-limit' to a value that is large enough to
3188 cover the maximum size of normal changes you expect a single
3189 command to make, but not so large that it might exceed the
3190 maximum memory allotted to Emacs.
3192 If you did not execute any such command, the situation is
3193 probably due to a bug and you should report it.
3195 You can disable the popping up of this buffer by adding the entry
3196 \(undo discard-info) to the user option `warning-suppress-types',
3197 which is defined in the `warnings' library.\n")
3198 :warning)
3199 (setq buffer-undo-list nil)
3202 (defvar shell-command-history nil
3203 "History list for some commands that read shell commands.
3205 Maximum length of the history list is determined by the value
3206 of `history-length', which see.")
3208 (defvar shell-command-switch (purecopy "-c")
3209 "Switch used to have the shell execute its command line argument.")
3211 (defvar shell-command-default-error-buffer nil
3212 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3213 This buffer is used when `shell-command' or `shell-command-on-region'
3214 is run interactively. A value of nil means that output to stderr and
3215 stdout will be intermixed in the output stream.")
3217 (declare-function mailcap-file-default-commands "mailcap" (files))
3218 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3220 (defun minibuffer-default-add-shell-commands ()
3221 "Return a list of all commands associated with the current file.
3222 This function is used to add all related commands retrieved by `mailcap'
3223 to the end of the list of defaults just after the default value."
3224 (interactive)
3225 (let* ((filename (if (listp minibuffer-default)
3226 (car minibuffer-default)
3227 minibuffer-default))
3228 (commands (and filename (require 'mailcap nil t)
3229 (mailcap-file-default-commands (list filename)))))
3230 (setq commands (mapcar (lambda (command)
3231 (concat command " " filename))
3232 commands))
3233 (if (listp minibuffer-default)
3234 (append minibuffer-default commands)
3235 (cons minibuffer-default commands))))
3237 (declare-function shell-completion-vars "shell" ())
3239 (defvar minibuffer-local-shell-command-map
3240 (let ((map (make-sparse-keymap)))
3241 (set-keymap-parent map minibuffer-local-map)
3242 (define-key map "\t" 'completion-at-point)
3243 map)
3244 "Keymap used for completing shell commands in minibuffer.")
3246 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3247 "Read a shell command from the minibuffer.
3248 The arguments are the same as the ones of `read-from-minibuffer',
3249 except READ and KEYMAP are missing and HIST defaults
3250 to `shell-command-history'."
3251 (require 'shell)
3252 (minibuffer-with-setup-hook
3253 (lambda ()
3254 (shell-completion-vars)
3255 (set (make-local-variable 'minibuffer-default-add-function)
3256 'minibuffer-default-add-shell-commands))
3257 (apply 'read-from-minibuffer prompt initial-contents
3258 minibuffer-local-shell-command-map
3260 (or hist 'shell-command-history)
3261 args)))
3263 (defcustom async-shell-command-buffer 'confirm-new-buffer
3264 "What to do when the output buffer is used by another shell command.
3265 This option specifies how to resolve the conflict where a new command
3266 wants to direct its output to the buffer `*Async Shell Command*',
3267 but this buffer is already taken by another running shell command.
3269 The value `confirm-kill-process' is used to ask for confirmation before
3270 killing the already running process and running a new process
3271 in the same buffer, `confirm-new-buffer' for confirmation before running
3272 the command in a new buffer with a name other than the default buffer name,
3273 `new-buffer' for doing the same without confirmation,
3274 `confirm-rename-buffer' for confirmation before renaming the existing
3275 output buffer and running a new command in the default buffer,
3276 `rename-buffer' for doing the same without confirmation."
3277 :type '(choice (const :tag "Confirm killing of running command"
3278 confirm-kill-process)
3279 (const :tag "Confirm creation of a new buffer"
3280 confirm-new-buffer)
3281 (const :tag "Create a new buffer"
3282 new-buffer)
3283 (const :tag "Confirm renaming of existing buffer"
3284 confirm-rename-buffer)
3285 (const :tag "Rename the existing buffer"
3286 rename-buffer))
3287 :group 'shell
3288 :version "24.3")
3290 (defcustom async-shell-command-display-buffer t
3291 "Whether to display the command buffer immediately.
3292 If t, display the buffer immediately; if nil, wait until there
3293 is output."
3294 :type '(choice (const :tag "Display buffer immediately"
3296 (const :tag "Display buffer on output"
3297 nil))
3298 :group 'shell
3299 :version "26.1")
3301 (defcustom shell-command-dont-erase-buffer nil
3302 "If non-nil, output buffer is not erased between shell commands.
3303 Also, a non-nil value sets the point in the output buffer
3304 once the command completes.
3305 The value `beg-last-out' sets point at the beginning of the output,
3306 `end-last-out' sets point at the end of the buffer, `save-point'
3307 restores the buffer position before the command."
3308 :type '(choice
3309 (const :tag "Erase buffer" nil)
3310 (const :tag "Set point to beginning of last output" beg-last-out)
3311 (const :tag "Set point to end of last output" end-last-out)
3312 (const :tag "Save point" save-point))
3313 :group 'shell
3314 :version "26.1")
3316 (defvar shell-command-saved-pos nil
3317 "Record of point positions in output buffers after command completion.
3318 The value is an alist whose elements are of the form (BUFFER . POS),
3319 where BUFFER is the output buffer, and POS is the point position
3320 in BUFFER once the command finishes.
3321 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
3323 (defun shell-command--save-pos-or-erase ()
3324 "Store a buffer position or erase the buffer.
3325 See `shell-command-dont-erase-buffer'."
3326 (let ((sym shell-command-dont-erase-buffer)
3327 pos)
3328 (setq buffer-read-only nil)
3329 ;; Setting buffer-read-only to nil doesn't suffice
3330 ;; if some text has a non-nil read-only property,
3331 ;; which comint sometimes adds for prompts.
3332 (setq pos
3333 (cond ((eq sym 'save-point) (point))
3334 ((eq sym 'beg-last-out) (point-max))
3335 ((not sym)
3336 (let ((inhibit-read-only t))
3337 (erase-buffer) nil))))
3338 (when pos
3339 (goto-char (point-max))
3340 (push (cons (current-buffer) pos)
3341 shell-command-saved-pos))))
3343 (defun shell-command--set-point-after-cmd (&optional buffer)
3344 "Set point in BUFFER after command complete.
3345 BUFFER is the output buffer of the command; if nil, then defaults
3346 to the current BUFFER.
3347 Set point to the `cdr' of the element in `shell-command-saved-pos'
3348 whose `car' is BUFFER."
3349 (when shell-command-dont-erase-buffer
3350 (let* ((sym shell-command-dont-erase-buffer)
3351 (buf (or buffer (current-buffer)))
3352 (pos (alist-get buf shell-command-saved-pos)))
3353 (setq shell-command-saved-pos
3354 (assq-delete-all buf shell-command-saved-pos))
3355 (when (buffer-live-p buf)
3356 (let ((win (car (get-buffer-window-list buf)))
3357 (pmax (with-current-buffer buf (point-max))))
3358 (unless (and pos (memq sym '(save-point beg-last-out)))
3359 (setq pos pmax))
3360 ;; Set point in the window displaying buf, if any; otherwise
3361 ;; display buf temporary in selected frame and set the point.
3362 (if win
3363 (set-window-point win pos)
3364 (save-window-excursion
3365 (let ((win (display-buffer
3367 '(nil (inhibit-switch-frame . t)))))
3368 (set-window-point win pos)))))))))
3370 (defun async-shell-command (command &optional output-buffer error-buffer)
3371 "Execute string COMMAND asynchronously in background.
3373 Like `shell-command', but adds `&' at the end of COMMAND
3374 to execute it asynchronously.
3376 The output appears in the buffer `*Async Shell Command*'.
3377 That buffer is in shell mode.
3379 You can configure `async-shell-command-buffer' to specify what to do
3380 when the `*Async Shell Command*' buffer is already taken by another
3381 running shell command. To run COMMAND without displaying the output
3382 in a window you can configure `display-buffer-alist' to use the action
3383 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3385 In Elisp, you will often be better served by calling `start-process'
3386 directly, since it offers more control and does not impose the use of
3387 a shell (with its need to quote arguments)."
3388 (interactive
3389 (list
3390 (read-shell-command "Async shell command: " nil nil
3391 (let ((filename
3392 (cond
3393 (buffer-file-name)
3394 ((eq major-mode 'dired-mode)
3395 (dired-get-filename nil t)))))
3396 (and filename (file-relative-name filename))))
3397 current-prefix-arg
3398 shell-command-default-error-buffer))
3399 (unless (string-match "&[ \t]*\\'" command)
3400 (setq command (concat command " &")))
3401 (shell-command command output-buffer error-buffer))
3403 (defun shell-command (command &optional output-buffer error-buffer)
3404 "Execute string COMMAND in inferior shell; display output, if any.
3405 With prefix argument, insert the COMMAND's output at point.
3407 Interactively, prompt for COMMAND in the minibuffer.
3409 If COMMAND ends in `&', execute it asynchronously.
3410 The output appears in the buffer `*Async Shell Command*'.
3411 That buffer is in shell mode. You can also use
3412 `async-shell-command' that automatically adds `&'.
3414 Otherwise, COMMAND is executed synchronously. The output appears in
3415 the buffer `*Shell Command Output*'. If the output is short enough to
3416 display in the echo area (which is determined by the variables
3417 `resize-mini-windows' and `max-mini-window-height'), it is shown
3418 there, but it is nonetheless available in buffer `*Shell Command
3419 Output*' even though that buffer is not automatically displayed.
3421 To specify a coding system for converting non-ASCII characters
3422 in the shell command output, use \\[universal-coding-system-argument] \
3423 before this command.
3425 Noninteractive callers can specify coding systems by binding
3426 `coding-system-for-read' and `coding-system-for-write'.
3428 The optional second argument OUTPUT-BUFFER, if non-nil,
3429 says to put the output in some other buffer.
3430 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3431 and insert the output there; a non-nil value of
3432 `shell-command-dont-erase-buffer' prevents the buffer from being
3433 erased. If OUTPUT-BUFFER is not a buffer and not nil, insert the
3434 output in current buffer after point leaving mark after it. This
3435 cannot be done asynchronously.
3437 If the command terminates without error, but generates output,
3438 and you did not specify \"insert it in the current buffer\",
3439 the output can be displayed in the echo area or in its buffer.
3440 If the output is short enough to display in the echo area
3441 \(determined by the variable `max-mini-window-height' if
3442 `resize-mini-windows' is non-nil), it is shown there.
3443 Otherwise, the buffer containing the output is displayed.
3445 If there is output and an error, and you did not specify \"insert it
3446 in the current buffer\", a message about the error goes at the end
3447 of the output.
3449 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3450 or buffer name to which to direct the command's standard error output.
3451 If it is nil, error output is mingled with regular output.
3452 In an interactive call, the variable `shell-command-default-error-buffer'
3453 specifies the value of ERROR-BUFFER.
3455 In Elisp, you will often be better served by calling `call-process' or
3456 `start-process' directly, since they offer more control and do not
3457 impose the use of a shell (with its need to quote arguments)."
3459 (interactive
3460 (list
3461 (read-shell-command "Shell command: " nil nil
3462 (let ((filename
3463 (cond
3464 (buffer-file-name)
3465 ((eq major-mode 'dired-mode)
3466 (dired-get-filename nil t)))))
3467 (and filename (file-relative-name filename))))
3468 current-prefix-arg
3469 shell-command-default-error-buffer))
3470 ;; Look for a handler in case default-directory is a remote file name.
3471 (let ((handler
3472 (find-file-name-handler (directory-file-name default-directory)
3473 'shell-command)))
3474 (if handler
3475 (funcall handler 'shell-command command output-buffer error-buffer)
3476 (if (and output-buffer
3477 (not (or (bufferp output-buffer) (stringp output-buffer))))
3478 ;; Output goes in current buffer.
3479 (let ((error-file
3480 (if error-buffer
3481 (make-temp-file
3482 (expand-file-name "scor"
3483 (or small-temporary-file-directory
3484 temporary-file-directory)))
3485 nil)))
3486 (barf-if-buffer-read-only)
3487 (push-mark nil t)
3488 ;; We do not use -f for csh; we will not support broken use of
3489 ;; .cshrcs. Even the BSD csh manual says to use
3490 ;; "if ($?prompt) exit" before things which are not useful
3491 ;; non-interactively. Besides, if someone wants their other
3492 ;; aliases for shell commands then they can still have them.
3493 (call-process shell-file-name nil
3494 (if error-file
3495 (list t error-file)
3497 nil shell-command-switch command)
3498 (when (and error-file (file-exists-p error-file))
3499 (if (< 0 (nth 7 (file-attributes error-file)))
3500 (with-current-buffer (get-buffer-create error-buffer)
3501 (let ((pos-from-end (- (point-max) (point))))
3502 (or (bobp)
3503 (insert "\f\n"))
3504 ;; Do no formatting while reading error file,
3505 ;; because that can run a shell command, and we
3506 ;; don't want that to cause an infinite recursion.
3507 (format-insert-file error-file nil)
3508 ;; Put point after the inserted errors.
3509 (goto-char (- (point-max) pos-from-end)))
3510 (display-buffer (current-buffer))))
3511 (delete-file error-file))
3512 ;; This is like exchange-point-and-mark, but doesn't
3513 ;; activate the mark. It is cleaner to avoid activation,
3514 ;; even though the command loop would deactivate the mark
3515 ;; because we inserted text.
3516 (goto-char (prog1 (mark t)
3517 (set-marker (mark-marker) (point)
3518 (current-buffer)))))
3519 ;; Output goes in a separate buffer.
3520 ;; Preserve the match data in case called from a program.
3521 ;; FIXME: It'd be ridiculous for an Elisp function to call
3522 ;; shell-command and assume that it won't mess the match-data!
3523 (save-match-data
3524 (if (string-match "[ \t]*&[ \t]*\\'" command)
3525 ;; Command ending with ampersand means asynchronous.
3526 (let* ((buffer (get-buffer-create
3527 (or output-buffer "*Async Shell Command*")))
3528 (bname (buffer-name buffer))
3529 (directory default-directory)
3530 proc)
3531 ;; Remove the ampersand.
3532 (setq command (substring command 0 (match-beginning 0)))
3533 ;; Ask the user what to do with already running process.
3534 (setq proc (get-buffer-process buffer))
3535 (when proc
3536 (cond
3537 ((eq async-shell-command-buffer 'confirm-kill-process)
3538 ;; If will kill a process, query first.
3539 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3540 (kill-process proc)
3541 (error "Shell command in progress")))
3542 ((eq async-shell-command-buffer 'confirm-new-buffer)
3543 ;; If will create a new buffer, query first.
3544 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3545 (setq buffer (generate-new-buffer bname))
3546 (error "Shell command in progress")))
3547 ((eq async-shell-command-buffer 'new-buffer)
3548 ;; It will create a new buffer.
3549 (setq buffer (generate-new-buffer bname)))
3550 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3551 ;; If will rename the buffer, query first.
3552 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3553 (progn
3554 (with-current-buffer buffer
3555 (rename-uniquely))
3556 (setq buffer (get-buffer-create bname)))
3557 (error "Shell command in progress")))
3558 ((eq async-shell-command-buffer 'rename-buffer)
3559 ;; It will rename the buffer.
3560 (with-current-buffer buffer
3561 (rename-uniquely))
3562 (setq buffer (get-buffer-create bname)))))
3563 (with-current-buffer buffer
3564 (shell-command--save-pos-or-erase)
3565 (setq default-directory directory)
3566 (setq proc (start-process "Shell" buffer shell-file-name
3567 shell-command-switch command))
3568 (setq mode-line-process '(":%s"))
3569 (require 'shell) (shell-mode)
3570 (set-process-sentinel proc 'shell-command-sentinel)
3571 ;; Use the comint filter for proper handling of
3572 ;; carriage motion (see comint-inhibit-carriage-motion).
3573 (set-process-filter proc 'comint-output-filter)
3574 (if async-shell-command-display-buffer
3575 ;; Display buffer immediately.
3576 (display-buffer buffer '(nil (allow-no-window . t)))
3577 ;; Defer displaying buffer until first process output.
3578 ;; Use disposable named advice so that the buffer is
3579 ;; displayed at most once per process lifetime.
3580 (let ((nonce (make-symbol "nonce")))
3581 (add-function :before (process-filter proc)
3582 (lambda (proc _string)
3583 (let ((buf (process-buffer proc)))
3584 (when (buffer-live-p buf)
3585 (remove-function (process-filter proc)
3586 nonce)
3587 (display-buffer buf))))
3588 `((name . ,nonce)))))))
3589 ;; Otherwise, command is executed synchronously.
3590 (shell-command-on-region (point) (point) command
3591 output-buffer nil error-buffer)))))))
3593 (defun display-message-or-buffer (message &optional buffer-name action frame)
3594 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3595 MESSAGE may be either a string or a buffer.
3597 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3598 for maximum height of the echo area, as defined by `max-mini-window-height'
3599 if `resize-mini-windows' is non-nil.
3601 Returns either the string shown in the echo area, or when a pop-up
3602 buffer is used, the window used to display it.
3604 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3605 name of the buffer used to display it in the case where a pop-up buffer
3606 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3607 string and it is displayed in the echo area, it is not specified whether
3608 the contents are inserted into the buffer anyway.
3610 Optional arguments ACTION and FRAME are as for `display-buffer',
3611 and are only used if a pop-up buffer is displayed."
3612 (cond ((and (stringp message) (not (string-match "\n" message)))
3613 ;; Trivial case where we can use the echo area
3614 (message "%s" message))
3615 ((and (stringp message)
3616 (= (string-match "\n" message) (1- (length message))))
3617 ;; Trivial case where we can just remove single trailing newline
3618 (message "%s" (substring message 0 (1- (length message)))))
3620 ;; General case
3621 (with-current-buffer
3622 (if (bufferp message)
3623 message
3624 (get-buffer-create (or buffer-name "*Message*")))
3626 (unless (bufferp message)
3627 (erase-buffer)
3628 (insert message))
3630 (let ((lines
3631 (if (= (buffer-size) 0)
3633 (count-screen-lines nil nil nil (minibuffer-window)))))
3634 (cond ((= lines 0))
3635 ((and (or (<= lines 1)
3636 (<= lines
3637 (if resize-mini-windows
3638 (cond ((floatp max-mini-window-height)
3639 (* (frame-height)
3640 max-mini-window-height))
3641 ((integerp max-mini-window-height)
3642 max-mini-window-height)
3645 1)))
3646 ;; Don't use the echo area if the output buffer is
3647 ;; already displayed in the selected frame.
3648 (not (get-buffer-window (current-buffer))))
3649 ;; Echo area
3650 (goto-char (point-max))
3651 (when (bolp)
3652 (backward-char 1))
3653 (message "%s" (buffer-substring (point-min) (point))))
3655 ;; Buffer
3656 (goto-char (point-min))
3657 (display-buffer (current-buffer) action frame))))))))
3660 ;; We have a sentinel to prevent insertion of a termination message
3661 ;; in the buffer itself, and to set the point in the buffer when
3662 ;; `shell-command-dont-erase-buffer' is non-nil.
3663 (defun shell-command-sentinel (process signal)
3664 (when (memq (process-status process) '(exit signal))
3665 (shell-command--set-point-after-cmd (process-buffer process))
3666 (message "%s: %s."
3667 (car (cdr (cdr (process-command process))))
3668 (substring signal 0 -1))))
3670 (defun shell-command-on-region (start end command
3671 &optional output-buffer replace
3672 error-buffer display-error-buffer
3673 region-noncontiguous-p)
3674 "Execute string COMMAND in inferior shell with region as input.
3675 Normally display output (if any) in temp buffer `*Shell Command Output*';
3676 Prefix arg means replace the region with it. Return the exit code of
3677 COMMAND.
3679 To specify a coding system for converting non-ASCII characters
3680 in the input and output to the shell command, use \\[universal-coding-system-argument]
3681 before this command. By default, the input (from the current buffer)
3682 is encoded using coding-system specified by `process-coding-system-alist',
3683 falling back to `default-process-coding-system' if no match for COMMAND
3684 is found in `process-coding-system-alist'.
3686 Noninteractive callers can specify coding systems by binding
3687 `coding-system-for-read' and `coding-system-for-write'.
3689 If the command generates output, the output may be displayed
3690 in the echo area or in a buffer.
3691 If the output is short enough to display in the echo area
3692 \(determined by the variable `max-mini-window-height' if
3693 `resize-mini-windows' is non-nil), it is shown there.
3694 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3695 The output is available in that buffer in both cases.
3697 If there is output and an error, a message about the error
3698 appears at the end of the output.
3700 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3701 command's output. If the value is a buffer or buffer name,
3702 erase that buffer and insert the output there; a non-nil value of
3703 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3704 If the value is nil, use the buffer `*Shell Command Output*'.
3705 Any other non-nil value means to insert the output in the
3706 current buffer after START.
3708 Optional fifth arg REPLACE, if non-nil, means to insert the
3709 output in place of text from START to END, putting point and mark
3710 around it.
3712 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3713 or buffer name to which to direct the command's standard error
3714 output. If nil, error output is mingled with regular output.
3715 When called interactively, `shell-command-default-error-buffer'
3716 is used for ERROR-BUFFER.
3718 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3719 display the error buffer if there were any errors. When called
3720 interactively, this is t."
3721 (interactive (let (string)
3722 (unless (mark)
3723 (user-error "The mark is not set now, so there is no region"))
3724 ;; Do this before calling region-beginning
3725 ;; and region-end, in case subprocess output
3726 ;; relocates them while we are in the minibuffer.
3727 (setq string (read-shell-command "Shell command on region: "))
3728 ;; call-interactively recognizes region-beginning and
3729 ;; region-end specially, leaving them in the history.
3730 (list (region-beginning) (region-end)
3731 string
3732 current-prefix-arg
3733 current-prefix-arg
3734 shell-command-default-error-buffer
3736 (region-noncontiguous-p))))
3737 (let ((error-file
3738 (if error-buffer
3739 (make-temp-file
3740 (expand-file-name "scor"
3741 (or small-temporary-file-directory
3742 temporary-file-directory)))
3743 nil))
3744 exit-status)
3745 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3746 (if region-noncontiguous-p
3747 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3748 output)
3749 (with-temp-buffer
3750 (insert input)
3751 (call-process-region (point-min) (point-max)
3752 shell-file-name t t
3753 nil shell-command-switch
3754 command)
3755 (setq output (split-string (buffer-string) "\n")))
3756 (goto-char start)
3757 (funcall region-insert-function output))
3758 (if (or replace
3759 (and output-buffer
3760 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3761 ;; Replace specified region with output from command.
3762 (let ((swap (and replace (< start end))))
3763 ;; Don't muck with mark unless REPLACE says we should.
3764 (goto-char start)
3765 (and replace (push-mark (point) 'nomsg))
3766 (setq exit-status
3767 (call-shell-region start end command replace
3768 (if error-file
3769 (list t error-file)
3770 t)))
3771 ;; It is rude to delete a buffer which the command is not using.
3772 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3773 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3774 ;; (kill-buffer shell-buffer)))
3775 ;; Don't muck with mark unless REPLACE says we should.
3776 (and replace swap (exchange-point-and-mark)))
3777 ;; No prefix argument: put the output in a temp buffer,
3778 ;; replacing its entire contents.
3779 (let ((buffer (get-buffer-create
3780 (or output-buffer "*Shell Command Output*"))))
3781 (unwind-protect
3782 (if (and (eq buffer (current-buffer))
3783 (or (not shell-command-dont-erase-buffer)
3784 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3785 (not (region-active-p)))))
3786 ;; If the input is the same buffer as the output,
3787 ;; delete everything but the specified region,
3788 ;; then replace that region with the output.
3789 (progn (setq buffer-read-only nil)
3790 (delete-region (max start end) (point-max))
3791 (delete-region (point-min) (min start end))
3792 (setq exit-status
3793 (call-process-region (point-min) (point-max)
3794 shell-file-name t
3795 (if error-file
3796 (list t error-file)
3798 nil shell-command-switch
3799 command)))
3800 ;; Clear the output buffer, then run the command with
3801 ;; output there.
3802 (let ((directory default-directory))
3803 (with-current-buffer buffer
3804 (if (not output-buffer)
3805 (setq default-directory directory))
3806 (shell-command--save-pos-or-erase)))
3807 (setq exit-status
3808 (call-shell-region start end command nil
3809 (if error-file
3810 (list buffer error-file)
3811 buffer))))
3812 ;; Report the output.
3813 (with-current-buffer buffer
3814 (setq mode-line-process
3815 (cond ((null exit-status)
3816 " - Error")
3817 ((stringp exit-status)
3818 (format " - Signal [%s]" exit-status))
3819 ((not (equal 0 exit-status))
3820 (format " - Exit [%d]" exit-status)))))
3821 (if (with-current-buffer buffer (> (point-max) (point-min)))
3822 ;; There's some output, display it
3823 (progn
3824 (display-message-or-buffer buffer)
3825 (shell-command--set-point-after-cmd buffer))
3826 ;; No output; error?
3827 (let ((output
3828 (if (and error-file
3829 (< 0 (nth 7 (file-attributes error-file))))
3830 (format "some error output%s"
3831 (if shell-command-default-error-buffer
3832 (format " to the \"%s\" buffer"
3833 shell-command-default-error-buffer)
3834 ""))
3835 "no output")))
3836 (cond ((null exit-status)
3837 (message "(Shell command failed with error)"))
3838 ((equal 0 exit-status)
3839 (message "(Shell command succeeded with %s)"
3840 output))
3841 ((stringp exit-status)
3842 (message "(Shell command killed by signal %s)"
3843 exit-status))
3845 (message "(Shell command failed with code %d and %s)"
3846 exit-status output))))
3847 ;; Don't kill: there might be useful info in the undo-log.
3848 ;; (kill-buffer buffer)
3849 )))))
3851 (when (and error-file (file-exists-p error-file))
3852 (if (< 0 (nth 7 (file-attributes error-file)))
3853 (with-current-buffer (get-buffer-create error-buffer)
3854 (let ((pos-from-end (- (point-max) (point))))
3855 (or (bobp)
3856 (insert "\f\n"))
3857 ;; Do no formatting while reading error file,
3858 ;; because that can run a shell command, and we
3859 ;; don't want that to cause an infinite recursion.
3860 (format-insert-file error-file nil)
3861 ;; Put point after the inserted errors.
3862 (goto-char (- (point-max) pos-from-end)))
3863 (and display-error-buffer
3864 (display-buffer (current-buffer)))))
3865 (delete-file error-file))
3866 exit-status))
3868 (defun shell-command-to-string (command)
3869 "Execute shell command COMMAND and return its output as a string."
3870 (with-output-to-string
3871 (with-current-buffer
3872 standard-output
3873 (shell-command command t))))
3875 (defun process-file (program &optional infile buffer display &rest args)
3876 "Process files synchronously in a separate process.
3877 Similar to `call-process', but may invoke a file handler based on
3878 `default-directory'. The current working directory of the
3879 subprocess is `default-directory'.
3881 File names in INFILE and BUFFER are handled normally, but file
3882 names in ARGS should be relative to `default-directory', as they
3883 are passed to the process verbatim. (This is a difference to
3884 `call-process' which does not support file handlers for INFILE
3885 and BUFFER.)
3887 Some file handlers might not support all variants, for example
3888 they might behave as if DISPLAY was nil, regardless of the actual
3889 value passed."
3890 (let ((fh (find-file-name-handler default-directory 'process-file))
3891 lc stderr-file)
3892 (unwind-protect
3893 (if fh (apply fh 'process-file program infile buffer display args)
3894 (when infile (setq lc (file-local-copy infile)))
3895 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3896 (make-temp-file "emacs")))
3897 (prog1
3898 (apply 'call-process program
3899 (or lc infile)
3900 (if stderr-file (list (car buffer) stderr-file) buffer)
3901 display args)
3902 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3903 (when stderr-file (delete-file stderr-file))
3904 (when lc (delete-file lc)))))
3906 (defvar process-file-side-effects t
3907 "Whether a call of `process-file' changes remote files.
3909 By default, this variable is always set to t, meaning that a
3910 call of `process-file' could potentially change any file on a
3911 remote host. When set to nil, a file handler could optimize
3912 its behavior with respect to remote file attribute caching.
3914 You should only ever change this variable with a let-binding;
3915 never with `setq'.")
3917 (defun start-file-process (name buffer program &rest program-args)
3918 "Start a program in a subprocess. Return the process object for it.
3920 Similar to `start-process', but may invoke a file handler based on
3921 `default-directory'. See Info node `(elisp)Magic File Names'.
3923 This handler ought to run PROGRAM, perhaps on the local host,
3924 perhaps on a remote host that corresponds to `default-directory'.
3925 In the latter case, the local part of `default-directory' becomes
3926 the working directory of the process.
3928 PROGRAM and PROGRAM-ARGS might be file names. They are not
3929 objects of file handler invocation. File handlers might not
3930 support pty association, if PROGRAM is nil."
3931 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3932 (if fh (apply fh 'start-file-process name buffer program program-args)
3933 (apply 'start-process name buffer program program-args))))
3935 ;;;; Process menu
3937 (defvar tabulated-list-format)
3938 (defvar tabulated-list-entries)
3939 (defvar tabulated-list-sort-key)
3940 (declare-function tabulated-list-init-header "tabulated-list" ())
3941 (declare-function tabulated-list-print "tabulated-list"
3942 (&optional remember-pos update))
3944 (defvar process-menu-query-only nil)
3946 (defvar process-menu-mode-map
3947 (let ((map (make-sparse-keymap)))
3948 (define-key map [?d] 'process-menu-delete-process)
3949 map))
3951 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3952 "Major mode for listing the processes called by Emacs."
3953 (setq tabulated-list-format [("Process" 15 t)
3954 ("PID" 7 t)
3955 ("Status" 7 t)
3956 ;; 25 is the length of the long standard buffer
3957 ;; name "*Async Shell Command*<10>" (bug#30016)
3958 ("Buffer" 25 t)
3959 ("TTY" 12 t)
3960 ("Command" 0 t)])
3961 (make-local-variable 'process-menu-query-only)
3962 (setq tabulated-list-sort-key (cons "Process" nil))
3963 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t))
3965 (defun process-menu-delete-process ()
3966 "Kill process at point in a `list-processes' buffer."
3967 (interactive)
3968 (let ((pos (point)))
3969 (delete-process (tabulated-list-get-id))
3970 (revert-buffer)
3971 (goto-char (min pos (point-max)))
3972 (if (eobp)
3973 (forward-line -1)
3974 (beginning-of-line))))
3976 (defun list-processes--refresh ()
3977 "Recompute the list of processes for the Process List buffer.
3978 Also, delete any process that is exited or signaled."
3979 (setq tabulated-list-entries nil)
3980 (dolist (p (process-list))
3981 (cond ((memq (process-status p) '(exit signal closed))
3982 (delete-process p))
3983 ((or (not process-menu-query-only)
3984 (process-query-on-exit-flag p))
3985 (let* ((buf (process-buffer p))
3986 (type (process-type p))
3987 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3988 (name (process-name p))
3989 (status (symbol-name (process-status p)))
3990 (buf-label (if (buffer-live-p buf)
3991 `(,(buffer-name buf)
3992 face link
3993 help-echo ,(format-message
3994 "Visit buffer `%s'"
3995 (buffer-name buf))
3996 follow-link t
3997 process-buffer ,buf
3998 action process-menu-visit-buffer)
3999 "--"))
4000 (tty (or (process-tty-name p) "--"))
4001 (cmd
4002 (if (memq type '(network serial))
4003 (let ((contact (process-contact p t)))
4004 (if (eq type 'network)
4005 (format "(%s %s)"
4006 (if (plist-get contact :type)
4007 "datagram"
4008 "network")
4009 (if (plist-get contact :server)
4010 (format "server on %s"
4012 (plist-get contact :host)
4013 (plist-get contact :local)))
4014 (format "connection to %s"
4015 (plist-get contact :host))))
4016 (format "(serial port %s%s)"
4017 (or (plist-get contact :port) "?")
4018 (let ((speed (plist-get contact :speed)))
4019 (if speed
4020 (format " at %s b/s" speed)
4021 "")))))
4022 (mapconcat 'identity (process-command p) " "))))
4023 (push (list p (vector name pid status buf-label tty cmd))
4024 tabulated-list-entries)))))
4025 (tabulated-list-init-header))
4027 (defun process-menu-visit-buffer (button)
4028 (display-buffer (button-get button 'process-buffer)))
4030 (defun list-processes (&optional query-only buffer)
4031 "Display a list of all processes that are Emacs sub-processes.
4032 If optional argument QUERY-ONLY is non-nil, only processes with
4033 the query-on-exit flag set are listed.
4034 Any process listed as exited or signaled is actually eliminated
4035 after the listing is made.
4036 Optional argument BUFFER specifies a buffer to use, instead of
4037 \"*Process List*\".
4038 The return value is always nil.
4040 This function lists only processes that were launched by Emacs. To
4041 see other processes running on the system, use `list-system-processes'."
4042 (interactive)
4043 (or (fboundp 'process-list)
4044 (error "Asynchronous subprocesses are not supported on this system"))
4045 (unless (bufferp buffer)
4046 (setq buffer (get-buffer-create "*Process List*")))
4047 (with-current-buffer buffer
4048 (process-menu-mode)
4049 (setq process-menu-query-only query-only)
4050 (list-processes--refresh)
4051 (tabulated-list-print))
4052 (display-buffer buffer)
4053 nil)
4055 ;;;; Prefix commands
4057 (setq prefix-command--needs-update nil)
4058 (setq prefix-command--last-echo nil)
4060 (defun internal-echo-keystrokes-prefix ()
4061 ;; BEWARE: Called directly from C code.
4062 ;; If the return value is non-nil, it means we are in the middle of
4063 ;; a command with prefix, such as a command invoked with prefix-arg.
4064 (if (not prefix-command--needs-update)
4065 prefix-command--last-echo
4066 (setq prefix-command--last-echo
4067 (let ((strs nil))
4068 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4069 (lambda (fun) (push (funcall fun) strs)))
4070 (setq strs (delq nil strs))
4071 (when strs (mapconcat #'identity strs " "))))))
4073 (defvar prefix-command-echo-keystrokes-functions nil
4074 "Abnormal hook which constructs the description of the current prefix state.
4075 Each function is called with no argument, should return a string or nil.")
4077 (defun prefix-command-update ()
4078 "Update state of prefix commands.
4079 Call it whenever you change the \"prefix command state\"."
4080 (setq prefix-command--needs-update t))
4082 (defvar prefix-command-preserve-state-hook nil
4083 "Normal hook run when a command needs to preserve the prefix.")
4085 (defun prefix-command-preserve-state ()
4086 "Pass the current prefix command state to the next command.
4087 Should be called by all prefix commands.
4088 Runs `prefix-command-preserve-state-hook'."
4089 (run-hooks 'prefix-command-preserve-state-hook)
4090 ;; If the current command is a prefix command, we don't want the next (real)
4091 ;; command to have `last-command' set to, say, `universal-argument'.
4092 (setq this-command last-command)
4093 (setq real-this-command real-last-command)
4094 (prefix-command-update))
4096 (defun reset-this-command-lengths ()
4097 (declare (obsolete prefix-command-preserve-state "25.1"))
4098 nil)
4100 ;;;;; The main prefix command.
4102 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4104 (add-hook 'prefix-command-echo-keystrokes-functions
4105 #'universal-argument--description)
4106 (defun universal-argument--description ()
4107 (when prefix-arg
4108 (concat "C-u"
4109 (pcase prefix-arg
4110 (`(-) " -")
4111 (`(,(and (pred integerp) n))
4112 (let ((str ""))
4113 (while (and (> n 4) (= (mod n 4) 0))
4114 (setq str (concat str " C-u"))
4115 (setq n (/ n 4)))
4116 (if (= n 4) str (format " %s" prefix-arg))))
4117 (_ (format " %s" prefix-arg))))))
4119 (add-hook 'prefix-command-preserve-state-hook
4120 #'universal-argument--preserve)
4121 (defun universal-argument--preserve ()
4122 (setq prefix-arg current-prefix-arg))
4124 (defvar universal-argument-map
4125 (let ((map (make-sparse-keymap))
4126 (universal-argument-minus
4127 ;; For backward compatibility, minus with no modifiers is an ordinary
4128 ;; command if digits have already been entered.
4129 `(menu-item "" negative-argument
4130 :filter ,(lambda (cmd)
4131 (if (integerp prefix-arg) nil cmd)))))
4132 (define-key map [switch-frame]
4133 (lambda (e) (interactive "e")
4134 (handle-switch-frame e) (universal-argument--mode)))
4135 (define-key map [?\C-u] 'universal-argument-more)
4136 (define-key map [?-] universal-argument-minus)
4137 (define-key map [?0] 'digit-argument)
4138 (define-key map [?1] 'digit-argument)
4139 (define-key map [?2] 'digit-argument)
4140 (define-key map [?3] 'digit-argument)
4141 (define-key map [?4] 'digit-argument)
4142 (define-key map [?5] 'digit-argument)
4143 (define-key map [?6] 'digit-argument)
4144 (define-key map [?7] 'digit-argument)
4145 (define-key map [?8] 'digit-argument)
4146 (define-key map [?9] 'digit-argument)
4147 (define-key map [kp-0] 'digit-argument)
4148 (define-key map [kp-1] 'digit-argument)
4149 (define-key map [kp-2] 'digit-argument)
4150 (define-key map [kp-3] 'digit-argument)
4151 (define-key map [kp-4] 'digit-argument)
4152 (define-key map [kp-5] 'digit-argument)
4153 (define-key map [kp-6] 'digit-argument)
4154 (define-key map [kp-7] 'digit-argument)
4155 (define-key map [kp-8] 'digit-argument)
4156 (define-key map [kp-9] 'digit-argument)
4157 (define-key map [kp-subtract] universal-argument-minus)
4158 map)
4159 "Keymap used while processing \\[universal-argument].")
4161 (defun universal-argument--mode ()
4162 (prefix-command-update)
4163 (set-transient-map universal-argument-map nil))
4165 (defun universal-argument ()
4166 "Begin a numeric argument for the following command.
4167 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4168 \\[universal-argument] following the digits or minus sign ends the argument.
4169 \\[universal-argument] without digits or minus sign provides 4 as argument.
4170 Repeating \\[universal-argument] without digits or minus sign
4171 multiplies the argument by 4 each time.
4172 For some commands, just \\[universal-argument] by itself serves as a flag
4173 which is different in effect from any particular numeric argument.
4174 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4175 (interactive)
4176 (prefix-command-preserve-state)
4177 (setq prefix-arg (list 4))
4178 (universal-argument--mode))
4180 (defun universal-argument-more (arg)
4181 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4182 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4183 (interactive "P")
4184 (prefix-command-preserve-state)
4185 (setq prefix-arg (if (consp arg)
4186 (list (* 4 (car arg)))
4187 (if (eq arg '-)
4188 (list -4)
4189 arg)))
4190 (when (consp prefix-arg) (universal-argument--mode)))
4192 (defun negative-argument (arg)
4193 "Begin a negative numeric argument for the next command.
4194 \\[universal-argument] following digits or minus sign ends the argument."
4195 (interactive "P")
4196 (prefix-command-preserve-state)
4197 (setq prefix-arg (cond ((integerp arg) (- arg))
4198 ((eq arg '-) nil)
4199 (t '-)))
4200 (universal-argument--mode))
4202 (defun digit-argument (arg)
4203 "Part of the numeric argument for the next command.
4204 \\[universal-argument] following digits or minus sign ends the argument."
4205 (interactive "P")
4206 (prefix-command-preserve-state)
4207 (let* ((char (if (integerp last-command-event)
4208 last-command-event
4209 (get last-command-event 'ascii-character)))
4210 (digit (- (logand char ?\177) ?0)))
4211 (setq prefix-arg (cond ((integerp arg)
4212 (+ (* arg 10)
4213 (if (< arg 0) (- digit) digit)))
4214 ((eq arg '-)
4215 ;; Treat -0 as just -, so that -01 will work.
4216 (if (zerop digit) '- (- digit)))
4218 digit))))
4219 (universal-argument--mode))
4222 (defvar filter-buffer-substring-functions nil
4223 "This variable is a wrapper hook around `buffer-substring--filter'.
4224 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4225 (make-obsolete-variable 'filter-buffer-substring-functions
4226 'filter-buffer-substring-function "24.4")
4228 (defvar filter-buffer-substring-function #'buffer-substring--filter
4229 "Function to perform the filtering in `filter-buffer-substring'.
4230 The function is called with the same 3 arguments (BEG END DELETE)
4231 that `filter-buffer-substring' received. It should return the
4232 buffer substring between BEG and END, after filtering. If DELETE is
4233 non-nil, it should delete the text between BEG and END from the buffer.")
4235 (defvar buffer-substring-filters nil
4236 "List of filter functions for `buffer-substring--filter'.
4237 Each function must accept a single argument, a string, and return a string.
4238 The buffer substring is passed to the first function in the list,
4239 and the return value of each function is passed to the next.
4240 As a special convention, point is set to the start of the buffer text
4241 being operated on (i.e., the first argument of `buffer-substring--filter')
4242 before these functions are called.")
4243 (make-obsolete-variable 'buffer-substring-filters
4244 'filter-buffer-substring-function "24.1")
4246 (defun filter-buffer-substring (beg end &optional delete)
4247 "Return the buffer substring between BEG and END, after filtering.
4248 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4250 This calls the function that `filter-buffer-substring-function' specifies
4251 \(passing the same three arguments that it received) to do the work,
4252 and returns whatever it does. The default function does no filtering,
4253 unless a hook has been set.
4255 Use `filter-buffer-substring' instead of `buffer-substring',
4256 `buffer-substring-no-properties', or `delete-and-extract-region' when
4257 you want to allow filtering to take place. For example, major or minor
4258 modes can use `filter-buffer-substring-function' to extract characters
4259 that are special to a buffer, and should not be copied into other buffers."
4260 (funcall filter-buffer-substring-function beg end delete))
4262 (defun buffer-substring--filter (beg end &optional delete)
4263 "Default function to use for `filter-buffer-substring-function'.
4264 Its arguments and return value are as specified for `filter-buffer-substring'.
4265 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4266 \(see `with-wrapper-hook' for details about wrapper hooks),
4267 and the abnormal hook `buffer-substring-filters'.
4268 No filtering is done unless a hook says to."
4269 (subr--with-wrapper-hook-no-warnings
4270 filter-buffer-substring-functions (beg end delete)
4271 (cond
4272 ((or delete buffer-substring-filters)
4273 (save-excursion
4274 (goto-char beg)
4275 (let ((string (if delete (delete-and-extract-region beg end)
4276 (buffer-substring beg end))))
4277 (dolist (filter buffer-substring-filters)
4278 (setq string (funcall filter string)))
4279 string)))
4281 (buffer-substring beg end)))))
4284 ;;;; Window system cut and paste hooks.
4286 (defvar interprogram-cut-function #'gui-select-text
4287 "Function to call to make a killed region available to other programs.
4288 Most window systems provide a facility for cutting and pasting
4289 text between different programs, such as the clipboard on X and
4290 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4292 This variable holds a function that Emacs calls whenever text is
4293 put in the kill ring, to make the new kill available to other
4294 programs. The function takes one argument, TEXT, which is a
4295 string containing the text which should be made available.")
4297 (defvar interprogram-paste-function #'gui-selection-value
4298 "Function to call to get text cut from other programs.
4299 Most window systems provide a facility for cutting and pasting
4300 text between different programs, such as the clipboard on X and
4301 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4303 This variable holds a function that Emacs calls to obtain text
4304 that other programs have provided for pasting. The function is
4305 called with no arguments. If no other program has provided text
4306 to paste, the function should return nil (in which case the
4307 caller, usually `current-kill', should use the top of the Emacs
4308 kill ring). If another program has provided text to paste, the
4309 function should return that text as a string (in which case the
4310 caller should put this string in the kill ring as the latest
4311 kill).
4313 The function may also return a list of strings if the window
4314 system supports multiple selections. The first string will be
4315 used as the pasted text, but the other will be placed in the kill
4316 ring for easy access via `yank-pop'.
4318 Note that the function should return a string only if a program
4319 other than Emacs has provided a string for pasting; if Emacs
4320 provided the most recent string, the function should return nil.
4321 If it is difficult to tell whether Emacs or some other program
4322 provided the current string, it is probably good enough to return
4323 nil if the string is equal (according to `string=') to the last
4324 text Emacs provided.")
4328 ;;;; The kill ring data structure.
4330 (defvar kill-ring nil
4331 "List of killed text sequences.
4332 Since the kill ring is supposed to interact nicely with cut-and-paste
4333 facilities offered by window systems, use of this variable should
4334 interact nicely with `interprogram-cut-function' and
4335 `interprogram-paste-function'. The functions `kill-new',
4336 `kill-append', and `current-kill' are supposed to implement this
4337 interaction; you may want to use them instead of manipulating the kill
4338 ring directly.")
4340 (defcustom kill-ring-max 60
4341 "Maximum length of kill ring before oldest elements are thrown away."
4342 :type 'integer
4343 :group 'killing)
4345 (defvar kill-ring-yank-pointer nil
4346 "The tail of the kill ring whose car is the last thing yanked.")
4348 (defcustom save-interprogram-paste-before-kill nil
4349 "Save existing clipboard text into kill ring before replacing it.
4350 A non-nil value ensures that Emacs kill operations do not
4351 irrevocably overwrite existing clipboard text by saving it to the
4352 `kill-ring' prior to the kill. Such text can subsequently be
4353 retrieved via \\[yank] \\[yank-pop]]."
4354 :type 'boolean
4355 :group 'killing
4356 :version "23.2")
4358 (defcustom kill-do-not-save-duplicates nil
4359 "Do not add a new string to `kill-ring' if it duplicates the last one.
4360 The comparison is done using `equal-including-properties'."
4361 :type 'boolean
4362 :group 'killing
4363 :version "23.2")
4365 (defun kill-new (string &optional replace)
4366 "Make STRING the latest kill in the kill ring.
4367 Set `kill-ring-yank-pointer' to point to it.
4368 If `interprogram-cut-function' is non-nil, apply it to STRING.
4369 Optional second argument REPLACE non-nil means that STRING will replace
4370 the front of the kill ring, rather than being added to the list.
4372 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4373 are non-nil, save the interprogram paste string(s) into `kill-ring' before
4374 STRING.
4376 When the yank handler has a non-nil PARAM element, the original STRING
4377 argument is not used by `insert-for-yank'. However, since Lisp code
4378 may access and use elements from the kill ring directly, the STRING
4379 argument should still be a \"useful\" string for such uses."
4380 (unless (and kill-do-not-save-duplicates
4381 ;; Due to text properties such as 'yank-handler that
4382 ;; can alter the contents to yank, comparison using
4383 ;; `equal' is unsafe.
4384 (equal-including-properties string (car kill-ring)))
4385 (if (fboundp 'menu-bar-update-yank-menu)
4386 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4387 (when save-interprogram-paste-before-kill
4388 (let ((interprogram-paste (and interprogram-paste-function
4389 (funcall interprogram-paste-function))))
4390 (when interprogram-paste
4391 (dolist (s (if (listp interprogram-paste)
4392 ;; Use `reverse' to avoid modifying external data.
4393 (reverse interprogram-paste)
4394 (list interprogram-paste)))
4395 (unless (and kill-do-not-save-duplicates
4396 (equal-including-properties s (car kill-ring)))
4397 (push s kill-ring))))))
4398 (unless (and kill-do-not-save-duplicates
4399 (equal-including-properties string (car kill-ring)))
4400 (if (and replace kill-ring)
4401 (setcar kill-ring string)
4402 (let ((history-delete-duplicates nil))
4403 (add-to-history 'kill-ring string kill-ring-max t))))
4404 (setq kill-ring-yank-pointer kill-ring)
4405 (if interprogram-cut-function
4406 (funcall interprogram-cut-function string)))
4408 ;; It has been argued that this should work like `self-insert-command'
4409 ;; which merges insertions in `buffer-undo-list' in groups of 20
4410 ;; (hard-coded in `undo-auto-amalgamate').
4411 (defcustom kill-append-merge-undo nil
4412 "Amalgamate appending kills with the last kill for undo.
4413 When non-nil, appending or prepending text to the last kill makes
4414 \\[undo] restore both pieces of text simultaneously."
4415 :type 'boolean
4416 :group 'killing
4417 :version "25.1")
4419 (defun kill-append (string before-p)
4420 "Append STRING to the end of the latest kill in the kill ring.
4421 If BEFORE-P is non-nil, prepend STRING to the kill instead.
4422 If `interprogram-cut-function' is non-nil, call it with the
4423 resulting kill.
4424 If `kill-append-merge-undo' is non-nil, remove the last undo
4425 boundary in the current buffer."
4426 (let* ((cur (car kill-ring)))
4427 (kill-new (if before-p (concat string cur) (concat cur string))
4428 (or (= (length cur) 0)
4429 (equal nil (get-text-property 0 'yank-handler cur))))
4430 (when (and kill-append-merge-undo (not buffer-read-only))
4431 (let ((prev buffer-undo-list)
4432 (next (cdr buffer-undo-list)))
4433 ;; find the next undo boundary
4434 (while (car next)
4435 (pop next)
4436 (pop prev))
4437 ;; remove this undo boundary
4438 (when prev
4439 (setcdr prev (cdr next)))))))
4441 (defcustom yank-pop-change-selection nil
4442 "Whether rotating the kill ring changes the window system selection.
4443 If non-nil, whenever the kill ring is rotated (usually via the
4444 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4445 to copy the new kill to the window system selection."
4446 :type 'boolean
4447 :group 'killing
4448 :version "23.1")
4450 (defun current-kill (n &optional do-not-move)
4451 "Rotate the yanking point by N places, and then return that kill.
4452 If N is zero and `interprogram-paste-function' is set to a
4453 function that returns a string or a list of strings, and if that
4454 function doesn't return nil, then that string (or list) is added
4455 to the front of the kill ring and the string (or first string in
4456 the list) is returned as the latest kill.
4458 If N is not zero, and if `yank-pop-change-selection' is
4459 non-nil, use `interprogram-cut-function' to transfer the
4460 kill at the new yank point into the window system selection.
4462 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4463 move the yanking point; just return the Nth kill forward."
4465 (let ((interprogram-paste (and (= n 0)
4466 interprogram-paste-function
4467 (funcall interprogram-paste-function))))
4468 (if interprogram-paste
4469 (progn
4470 ;; Disable the interprogram cut function when we add the new
4471 ;; text to the kill ring, so Emacs doesn't try to own the
4472 ;; selection, with identical text.
4473 ;; Also disable the interprogram paste function, so that
4474 ;; `kill-new' doesn't call it repeatedly.
4475 (let ((interprogram-cut-function nil)
4476 (interprogram-paste-function nil))
4477 (if (listp interprogram-paste)
4478 ;; Use `reverse' to avoid modifying external data.
4479 (mapc #'kill-new (reverse interprogram-paste))
4480 (kill-new interprogram-paste)))
4481 (car kill-ring))
4482 (or kill-ring (error "Kill ring is empty"))
4483 (let ((ARGth-kill-element
4484 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4485 (length kill-ring))
4486 kill-ring)))
4487 (unless do-not-move
4488 (setq kill-ring-yank-pointer ARGth-kill-element)
4489 (when (and yank-pop-change-selection
4490 (> n 0)
4491 interprogram-cut-function)
4492 (funcall interprogram-cut-function (car ARGth-kill-element))))
4493 (car ARGth-kill-element)))))
4497 ;;;; Commands for manipulating the kill ring.
4499 (defcustom kill-read-only-ok nil
4500 "Non-nil means don't signal an error for killing read-only text."
4501 :type 'boolean
4502 :group 'killing)
4504 (defun kill-region (beg end &optional region)
4505 "Kill (\"cut\") text between point and mark.
4506 This deletes the text from the buffer and saves it in the kill ring.
4507 The command \\[yank] can retrieve it from there.
4508 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4510 If you want to append the killed region to the last killed text,
4511 use \\[append-next-kill] before \\[kill-region].
4513 Any command that calls this function is a \"kill command\".
4514 If the previous command was also a kill command,
4515 the text killed this time appends to the text killed last time
4516 to make one entry in the kill ring.
4518 The killed text is filtered by `filter-buffer-substring' before it is
4519 saved in the kill ring, so the actual saved text might be different
4520 from what was killed.
4522 If the buffer is read-only, Emacs will beep and refrain from deleting
4523 the text, but put the text in the kill ring anyway. This means that
4524 you can use the killing commands to copy text from a read-only buffer.
4526 Lisp programs should use this function for killing text.
4527 (To delete text, use `delete-region'.)
4528 Supply two arguments, character positions BEG and END indicating the
4529 stretch of text to be killed. If the optional argument REGION is
4530 non-nil, the function ignores BEG and END, and kills the current
4531 region instead."
4532 ;; Pass mark first, then point, because the order matters when
4533 ;; calling `kill-append'.
4534 (interactive (list (mark) (point) 'region))
4535 (unless (and beg end)
4536 (user-error "The mark is not set now, so there is no region"))
4537 (condition-case nil
4538 (let ((string (if region
4539 (funcall region-extract-function 'delete)
4540 (filter-buffer-substring beg end 'delete))))
4541 (when string ;STRING is nil if BEG = END
4542 ;; Add that string to the kill ring, one way or another.
4543 (if (eq last-command 'kill-region)
4544 (kill-append string (< end beg))
4545 (kill-new string)))
4546 (when (or string (eq last-command 'kill-region))
4547 (setq this-command 'kill-region))
4548 (setq deactivate-mark t)
4549 nil)
4550 ((buffer-read-only text-read-only)
4551 ;; The code above failed because the buffer, or some of the characters
4552 ;; in the region, are read-only.
4553 ;; We should beep, in case the user just isn't aware of this.
4554 ;; However, there's no harm in putting
4555 ;; the region's text in the kill ring, anyway.
4556 (copy-region-as-kill beg end region)
4557 ;; Set this-command now, so it will be set even if we get an error.
4558 (setq this-command 'kill-region)
4559 ;; This should barf, if appropriate, and give us the correct error.
4560 (if kill-read-only-ok
4561 (progn (message "Read only text copied to kill ring") nil)
4562 ;; Signal an error if the buffer is read-only.
4563 (barf-if-buffer-read-only)
4564 ;; If the buffer isn't read-only, the text is.
4565 (signal 'text-read-only (list (current-buffer)))))))
4567 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4568 ;; to get two copies of the text when the user accidentally types M-w and
4569 ;; then corrects it with the intended C-w.
4570 (defun copy-region-as-kill (beg end &optional region)
4571 "Save the region as if killed, but don't kill it.
4572 In Transient Mark mode, deactivate the mark.
4573 If `interprogram-cut-function' is non-nil, also save the text for a window
4574 system cut and paste.
4576 The copied text is filtered by `filter-buffer-substring' before it is
4577 saved in the kill ring, so the actual saved text might be different
4578 from what was in the buffer.
4580 When called from Lisp, save in the kill ring the stretch of text
4581 between BEG and END, unless the optional argument REGION is
4582 non-nil, in which case ignore BEG and END, and save the current
4583 region instead.
4585 This command's old key binding has been given to `kill-ring-save'."
4586 ;; Pass mark first, then point, because the order matters when
4587 ;; calling `kill-append'.
4588 (interactive (list (mark) (point)
4589 (prefix-numeric-value current-prefix-arg)))
4590 (let ((str (if region
4591 (funcall region-extract-function nil)
4592 (filter-buffer-substring beg end))))
4593 (if (eq last-command 'kill-region)
4594 (kill-append str (< end beg))
4595 (kill-new str)))
4596 (setq deactivate-mark t)
4597 nil)
4599 (defun kill-ring-save (beg end &optional region)
4600 "Save the region as if killed, but don't kill it.
4601 In Transient Mark mode, deactivate the mark.
4602 If `interprogram-cut-function' is non-nil, also save the text for a window
4603 system cut and paste.
4605 If you want to append the killed line to the last killed text,
4606 use \\[append-next-kill] before \\[kill-ring-save].
4608 The copied text is filtered by `filter-buffer-substring' before it is
4609 saved in the kill ring, so the actual saved text might be different
4610 from what was in the buffer.
4612 When called from Lisp, save in the kill ring the stretch of text
4613 between BEG and END, unless the optional argument REGION is
4614 non-nil, in which case ignore BEG and END, and save the current
4615 region instead.
4617 This command is similar to `copy-region-as-kill', except that it gives
4618 visual feedback indicating the extent of the region being copied."
4619 ;; Pass mark first, then point, because the order matters when
4620 ;; calling `kill-append'.
4621 (interactive (list (mark) (point)
4622 (prefix-numeric-value current-prefix-arg)))
4623 (copy-region-as-kill beg end region)
4624 ;; This use of called-interactively-p is correct because the code it
4625 ;; controls just gives the user visual feedback.
4626 (if (called-interactively-p 'interactive)
4627 (indicate-copied-region)))
4629 (defun indicate-copied-region (&optional message-len)
4630 "Indicate that the region text has been copied interactively.
4631 If the mark is visible in the selected window, blink the cursor
4632 between point and mark if there is currently no active region
4633 highlighting.
4635 If the mark lies outside the selected window, display an
4636 informative message containing a sample of the copied text. The
4637 optional argument MESSAGE-LEN, if non-nil, specifies the length
4638 of this sample text; it defaults to 40."
4639 (let ((mark (mark t))
4640 (point (point))
4641 ;; Inhibit quitting so we can make a quit here
4642 ;; look like a C-g typed as a command.
4643 (inhibit-quit t))
4644 (if (pos-visible-in-window-p mark (selected-window))
4645 ;; Swap point-and-mark quickly so as to show the region that
4646 ;; was selected. Don't do it if the region is highlighted.
4647 (unless (and (region-active-p)
4648 (face-background 'region))
4649 ;; Swap point and mark.
4650 (set-marker (mark-marker) (point) (current-buffer))
4651 (goto-char mark)
4652 (sit-for blink-matching-delay)
4653 ;; Swap back.
4654 (set-marker (mark-marker) mark (current-buffer))
4655 (goto-char point)
4656 ;; If user quit, deactivate the mark
4657 ;; as C-g would as a command.
4658 (and quit-flag (region-active-p)
4659 (deactivate-mark)))
4660 (let ((len (min (abs (- mark point))
4661 (or message-len 40))))
4662 (if (< point mark)
4663 ;; Don't say "killed"; that is misleading.
4664 (message "Saved text until \"%s\""
4665 (buffer-substring-no-properties (- mark len) mark))
4666 (message "Saved text from \"%s\""
4667 (buffer-substring-no-properties mark (+ mark len))))))))
4669 (defun append-next-kill (&optional interactive)
4670 "Cause following command, if it kills, to add to previous kill.
4671 If the next command kills forward from point, the kill is
4672 appended to the previous killed text. If the command kills
4673 backward, the kill is prepended. Kill commands that act on the
4674 region, such as `kill-region', are regarded as killing forward if
4675 point is after mark, and killing backward if point is before
4676 mark.
4678 If the next command is not a kill command, `append-next-kill' has
4679 no effect.
4681 The argument is used for internal purposes; do not supply one."
4682 (interactive "p")
4683 ;; We don't use (interactive-p), since that breaks kbd macros.
4684 (if interactive
4685 (progn
4686 (setq this-command 'kill-region)
4687 (message "If the next command is a kill, it will append"))
4688 (setq last-command 'kill-region)))
4690 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4691 "Character set that matches bidirectional formatting control characters.")
4693 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4694 "Character set that matches any character except bidirectional controls.")
4696 (defun squeeze-bidi-context-1 (from to category replacement)
4697 "A subroutine of `squeeze-bidi-context'.
4698 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4699 (let ((pt (copy-marker from))
4700 (limit (copy-marker to))
4701 (old-pt 0)
4702 lim1)
4703 (setq lim1 limit)
4704 (goto-char pt)
4705 (while (< pt limit)
4706 (if (> pt old-pt)
4707 (move-marker lim1
4708 (save-excursion
4709 ;; L and R categories include embedding and
4710 ;; override controls, but we don't want to
4711 ;; replace them, because that might change
4712 ;; the visual order. Likewise with PDF and
4713 ;; isolate controls.
4714 (+ pt (skip-chars-forward
4715 bidi-directional-non-controls-chars
4716 limit)))))
4717 ;; Replace any run of non-RTL characters by a single LRM.
4718 (if (null (re-search-forward category lim1 t))
4719 ;; No more characters of CATEGORY, we are done.
4720 (setq pt limit)
4721 (replace-match replacement nil t)
4722 (move-marker pt (point)))
4723 (setq old-pt pt)
4724 ;; Skip directional controls, if any.
4725 (move-marker
4726 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4728 (defun squeeze-bidi-context (from to)
4729 "Replace characters between FROM and TO while keeping bidi context.
4731 This function replaces the region of text with as few characters
4732 as possible, while preserving the effect that region will have on
4733 bidirectional display before and after the region."
4734 (let ((start (set-marker (make-marker)
4735 (if (> from 0) from (+ (point-max) from))))
4736 (end (set-marker (make-marker) to))
4737 ;; This is for when they copy text with read-only text
4738 ;; properties.
4739 (inhibit-read-only t))
4740 (if (null (marker-position end))
4741 (setq end (point-max-marker)))
4742 ;; Replace each run of non-RTL characters with a single LRM.
4743 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4744 ;; Replace each run of non-LTR characters with a single RLM. Note
4745 ;; that the \cR category includes both the Arabic Letter (AL) and
4746 ;; R characters; here we ignore the distinction between them,
4747 ;; because that distinction only affects Arabic Number (AN)
4748 ;; characters, which are weak and don't affect the reordering.
4749 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4751 (defun line-substring-with-bidi-context (start end &optional no-properties)
4752 "Return buffer text between START and END with its bidi context.
4754 START and END are assumed to belong to the same physical line
4755 of buffer text. This function prepends and appends to the text
4756 between START and END bidi control characters that preserve the
4757 visual order of that text when it is inserted at some other place."
4758 (if (or (< start (point-min))
4759 (> end (point-max)))
4760 (signal 'args-out-of-range (list (current-buffer) start end)))
4761 (let ((buf (current-buffer))
4762 substr para-dir from to)
4763 (save-excursion
4764 (goto-char start)
4765 (setq para-dir (current-bidi-paragraph-direction))
4766 (setq from (line-beginning-position)
4767 to (line-end-position))
4768 (goto-char from)
4769 ;; If we don't have any mixed directional characters in the
4770 ;; entire line, we can just copy the substring without adding
4771 ;; any context.
4772 (if (or (looking-at-p "\\CR*$")
4773 (looking-at-p "\\CL*$"))
4774 (setq substr (if no-properties
4775 (buffer-substring-no-properties start end)
4776 (buffer-substring start end)))
4777 (setq substr
4778 (with-temp-buffer
4779 (if no-properties
4780 (insert-buffer-substring-no-properties buf from to)
4781 (insert-buffer-substring buf from to))
4782 (squeeze-bidi-context 1 (1+ (- start from)))
4783 (squeeze-bidi-context (- end to) nil)
4784 (buffer-substring 1 (point-max)))))
4786 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4787 ;; (1) force the string to have the same base embedding
4788 ;; direction as the paragraph direction at the source, no matter
4789 ;; what is the paragraph direction at destination; and (2) avoid
4790 ;; affecting the visual order of the surrounding text at
4791 ;; destination if there are characters of different
4792 ;; directionality there.
4793 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4794 substr "\x2069"))))
4796 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4797 "Return portion of current buffer between START and END with bidi context.
4799 This function works similar to `buffer-substring', but it prepends and
4800 appends to the text bidi directional control characters necessary to
4801 preserve the visual appearance of the text if it is inserted at another
4802 place. This is useful when the buffer substring includes bidirectional
4803 text and control characters that cause non-trivial reordering on display.
4804 If copied verbatim, such text can have a very different visual appearance,
4805 and can also change the visual appearance of the surrounding text at the
4806 destination of the copy.
4808 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4809 the text properties."
4810 (let (line-end substr)
4811 (if (or (< start (point-min))
4812 (> end (point-max)))
4813 (signal 'args-out-of-range (list (current-buffer) start end)))
4814 (save-excursion
4815 (goto-char start)
4816 (setq line-end (min end (line-end-position)))
4817 (while (< start end)
4818 (setq substr
4819 (concat substr
4820 (if substr "\n" "")
4821 (line-substring-with-bidi-context start line-end
4822 no-properties)))
4823 (forward-line 1)
4824 (setq start (point))
4825 (setq line-end (min end (line-end-position))))
4826 substr)))
4828 ;; Yanking.
4830 (defcustom yank-handled-properties
4831 '((font-lock-face . yank-handle-font-lock-face-property)
4832 (category . yank-handle-category-property))
4833 "List of special text property handling conditions for yanking.
4834 Each element should have the form (PROP . FUN), where PROP is a
4835 property symbol and FUN is a function. When the `yank' command
4836 inserts text into the buffer, it scans the inserted text for
4837 stretches of text that have `eq' values of the text property
4838 PROP; for each such stretch of text, FUN is called with three
4839 arguments: the property's value in that text, and the start and
4840 end positions of the text.
4842 This is done prior to removing the properties specified by
4843 `yank-excluded-properties'."
4844 :group 'killing
4845 :type '(repeat (cons (symbol :tag "property symbol")
4846 function))
4847 :version "24.3")
4849 ;; This is actually used in subr.el but defcustom does not work there.
4850 (defcustom yank-excluded-properties
4851 '(category field follow-link fontified font-lock-face help-echo
4852 intangible invisible keymap local-map mouse-face read-only
4853 yank-handler)
4854 "Text properties to discard when yanking.
4855 The value should be a list of text properties to discard or t,
4856 which means to discard all text properties.
4858 See also `yank-handled-properties'."
4859 :type '(choice (const :tag "All" t) (repeat symbol))
4860 :group 'killing
4861 :version "24.3")
4863 (defvar yank-window-start nil)
4864 (defvar yank-undo-function nil
4865 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4866 Function is called with two parameters, START and END corresponding to
4867 the value of the mark and point; it is guaranteed that START <= END.
4868 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4870 (defun yank-pop (&optional arg)
4871 "Replace just-yanked stretch of killed text with a different stretch.
4872 This command is allowed only immediately after a `yank' or a `yank-pop'.
4873 At such a time, the region contains a stretch of reinserted
4874 previously-killed text. `yank-pop' deletes that text and inserts in its
4875 place a different stretch of killed text.
4877 With no argument, the previous kill is inserted.
4878 With argument N, insert the Nth previous kill.
4879 If N is negative, this is a more recent kill.
4881 The sequence of kills wraps around, so that after the oldest one
4882 comes the newest one.
4884 This command honors the `yank-handled-properties' and
4885 `yank-excluded-properties' variables, and the `yank-handler' text
4886 property, in the way that `yank' does."
4887 (interactive "*p")
4888 (if (not (eq last-command 'yank))
4889 (user-error "Previous command was not a yank"))
4890 (setq this-command 'yank)
4891 (unless arg (setq arg 1))
4892 (let ((inhibit-read-only t)
4893 (before (< (point) (mark t))))
4894 (if before
4895 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4896 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4897 (setq yank-undo-function nil)
4898 (set-marker (mark-marker) (point) (current-buffer))
4899 (insert-for-yank (current-kill arg))
4900 ;; Set the window start back where it was in the yank command,
4901 ;; if possible.
4902 (set-window-start (selected-window) yank-window-start t)
4903 (if before
4904 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4905 ;; It is cleaner to avoid activation, even though the command
4906 ;; loop would deactivate the mark because we inserted text.
4907 (goto-char (prog1 (mark t)
4908 (set-marker (mark-marker) (point) (current-buffer))))))
4909 nil)
4911 (defun yank (&optional arg)
4912 "Reinsert (\"paste\") the last stretch of killed text.
4913 More precisely, reinsert the most recent kill, which is the
4914 stretch of killed text most recently killed OR yanked. Put point
4915 at the end, and set mark at the beginning without activating it.
4916 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4917 With argument N, reinsert the Nth most recent kill.
4919 This command honors the `yank-handled-properties' and
4920 `yank-excluded-properties' variables, and the `yank-handler' text
4921 property, as described below.
4923 Properties listed in `yank-handled-properties' are processed,
4924 then those listed in `yank-excluded-properties' are discarded.
4926 If STRING has a non-nil `yank-handler' property anywhere, the
4927 normal insert behavior is altered, and instead, for each contiguous
4928 segment of STRING that has a given value of the `yank-handler'
4929 property, that value is used as follows:
4931 The value of a `yank-handler' property must be a list of one to four
4932 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4933 FUNCTION, if non-nil, should be a function of one argument (the
4934 object to insert); FUNCTION is called instead of `insert'.
4935 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4936 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4937 PARAM may be a list of strings to insert as a rectangle). If PARAM
4938 is nil, then the current segment of STRING is used.
4939 If NOEXCLUDE is present and non-nil, the normal removal of
4940 `yank-excluded-properties' is not performed; instead FUNCTION is
4941 responsible for the removal. This may be necessary if FUNCTION
4942 adjusts point before or after inserting the object.
4943 UNDO, if present and non-nil, should be a function to be called
4944 by `yank-pop' to undo the insertion of the current PARAM. It is
4945 given two arguments, the start and end of the region. FUNCTION
4946 may set `yank-undo-function' to override UNDO.
4948 See also the command `yank-pop' (\\[yank-pop])."
4949 (interactive "*P")
4950 (setq yank-window-start (window-start))
4951 ;; If we don't get all the way thru, make last-command indicate that
4952 ;; for the following command.
4953 (setq this-command t)
4954 (push-mark)
4955 (insert-for-yank (current-kill (cond
4956 ((listp arg) 0)
4957 ((eq arg '-) -2)
4958 (t (1- arg)))))
4959 (if (consp arg)
4960 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4961 ;; It is cleaner to avoid activation, even though the command
4962 ;; loop would deactivate the mark because we inserted text.
4963 (goto-char (prog1 (mark t)
4964 (set-marker (mark-marker) (point) (current-buffer)))))
4965 ;; If we do get all the way thru, make this-command indicate that.
4966 (if (eq this-command t)
4967 (setq this-command 'yank))
4968 nil)
4970 (defun rotate-yank-pointer (arg)
4971 "Rotate the yanking point in the kill ring.
4972 With ARG, rotate that many kills forward (or backward, if negative)."
4973 (interactive "p")
4974 (current-kill arg))
4976 ;; Some kill commands.
4978 ;; Internal subroutine of delete-char
4979 (defun kill-forward-chars (arg)
4980 (if (listp arg) (setq arg (car arg)))
4981 (if (eq arg '-) (setq arg -1))
4982 (kill-region (point) (+ (point) arg)))
4984 ;; Internal subroutine of backward-delete-char
4985 (defun kill-backward-chars (arg)
4986 (if (listp arg) (setq arg (car arg)))
4987 (if (eq arg '-) (setq arg -1))
4988 (kill-region (point) (- (point) arg)))
4990 (defcustom backward-delete-char-untabify-method 'untabify
4991 "The method for untabifying when deleting backward.
4992 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4993 `hungry' -- delete all whitespace, both tabs and spaces;
4994 `all' -- delete all whitespace, including tabs, spaces and newlines;
4995 nil -- just delete one character."
4996 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4997 :version "20.3"
4998 :group 'killing)
5000 (defun backward-delete-char-untabify (arg &optional killp)
5001 "Delete characters backward, changing tabs into spaces.
5002 The exact behavior depends on `backward-delete-char-untabify-method'.
5003 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
5004 Interactively, ARG is the prefix arg (default 1)
5005 and KILLP is t if a prefix arg was specified."
5006 (interactive "*p\nP")
5007 (when (eq backward-delete-char-untabify-method 'untabify)
5008 (let ((count arg))
5009 (save-excursion
5010 (while (and (> count 0) (not (bobp)))
5011 (if (= (preceding-char) ?\t)
5012 (let ((col (current-column)))
5013 (forward-char -1)
5014 (setq col (- col (current-column)))
5015 (insert-char ?\s col)
5016 (delete-char 1)))
5017 (forward-char -1)
5018 (setq count (1- count))))))
5019 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
5020 ((eq backward-delete-char-untabify-method 'all)
5021 " \t\n\r")))
5022 (n (if skip
5023 (let* ((oldpt (point))
5024 (wh (- oldpt (save-excursion
5025 (skip-chars-backward skip)
5026 (constrain-to-field nil oldpt)))))
5027 (+ arg (if (zerop wh) 0 (1- wh))))
5028 arg)))
5029 ;; Avoid warning about delete-backward-char
5030 (with-no-warnings (delete-backward-char n killp))))
5032 (defun zap-to-char (arg char)
5033 "Kill up to and including ARGth occurrence of CHAR.
5034 Case is ignored if `case-fold-search' is non-nil in the current buffer.
5035 Goes backward if ARG is negative; error if CHAR not found."
5036 (interactive (list (prefix-numeric-value current-prefix-arg)
5037 (read-char "Zap to char: " t)))
5038 ;; Avoid "obsolete" warnings for translation-table-for-input.
5039 (with-no-warnings
5040 (if (char-table-p translation-table-for-input)
5041 (setq char (or (aref translation-table-for-input char) char))))
5042 (kill-region (point) (progn
5043 (search-forward (char-to-string char) nil nil arg)
5044 (point))))
5046 ;; kill-line and its subroutines.
5048 (defcustom kill-whole-line nil
5049 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
5050 :type 'boolean
5051 :group 'killing)
5053 (defun kill-line (&optional arg)
5054 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5055 With prefix argument ARG, kill that many lines from point.
5056 Negative arguments kill lines backward.
5057 With zero argument, kills the text before point on the current line.
5059 When calling from a program, nil means \"no arg\",
5060 a number counts as a prefix arg.
5062 To kill a whole line, when point is not at the beginning, type \
5063 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5065 If `show-trailing-whitespace' is non-nil, this command will just
5066 kill the rest of the current line, even if there are no nonblanks
5067 there.
5069 If option `kill-whole-line' is non-nil, then this command kills the whole line
5070 including its terminating newline, when used at the beginning of a line
5071 with no argument. As a consequence, you can always kill a whole line
5072 by typing \\[move-beginning-of-line] \\[kill-line].
5074 If you want to append the killed line to the last killed text,
5075 use \\[append-next-kill] before \\[kill-line].
5077 If the buffer is read-only, Emacs will beep and refrain from deleting
5078 the line, but put the line in the kill ring anyway. This means that
5079 you can use this command to copy text from a read-only buffer.
5080 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5081 even beep.)"
5082 (interactive "P")
5083 (kill-region (point)
5084 ;; It is better to move point to the other end of the kill
5085 ;; before killing. That way, in a read-only buffer, point
5086 ;; moves across the text that is copied to the kill ring.
5087 ;; The choice has no effect on undo now that undo records
5088 ;; the value of point from before the command was run.
5089 (progn
5090 (if arg
5091 (forward-visible-line (prefix-numeric-value arg))
5092 (if (eobp)
5093 (signal 'end-of-buffer nil))
5094 (let ((end
5095 (save-excursion
5096 (end-of-visible-line) (point))))
5097 (if (or (save-excursion
5098 ;; If trailing whitespace is visible,
5099 ;; don't treat it as nothing.
5100 (unless show-trailing-whitespace
5101 (skip-chars-forward " \t" end))
5102 (= (point) end))
5103 (and kill-whole-line (bolp)))
5104 (forward-visible-line 1)
5105 (goto-char end))))
5106 (point))))
5108 (defun kill-whole-line (&optional arg)
5109 "Kill current line.
5110 With prefix ARG, kill that many lines starting from the current line.
5111 If ARG is negative, kill backward. Also kill the preceding newline.
5112 \(This is meant to make \\[repeat] work well with negative arguments.)
5113 If ARG is zero, kill current line but exclude the trailing newline."
5114 (interactive "p")
5115 (or arg (setq arg 1))
5116 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5117 (signal 'end-of-buffer nil))
5118 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5119 (signal 'beginning-of-buffer nil))
5120 (unless (eq last-command 'kill-region)
5121 (kill-new "")
5122 (setq last-command 'kill-region))
5123 (cond ((zerop arg)
5124 ;; We need to kill in two steps, because the previous command
5125 ;; could have been a kill command, in which case the text
5126 ;; before point needs to be prepended to the current kill
5127 ;; ring entry and the text after point appended. Also, we
5128 ;; need to use save-excursion to avoid copying the same text
5129 ;; twice to the kill ring in read-only buffers.
5130 (save-excursion
5131 (kill-region (point) (progn (forward-visible-line 0) (point))))
5132 (kill-region (point) (progn (end-of-visible-line) (point))))
5133 ((< arg 0)
5134 (save-excursion
5135 (kill-region (point) (progn (end-of-visible-line) (point))))
5136 (kill-region (point)
5137 (progn (forward-visible-line (1+ arg))
5138 (unless (bobp) (backward-char))
5139 (point))))
5141 (save-excursion
5142 (kill-region (point) (progn (forward-visible-line 0) (point))))
5143 (kill-region (point)
5144 (progn (forward-visible-line arg) (point))))))
5146 (defun forward-visible-line (arg)
5147 "Move forward by ARG lines, ignoring currently invisible newlines only.
5148 If ARG is negative, move backward -ARG lines.
5149 If ARG is zero, move to the beginning of the current line."
5150 (condition-case nil
5151 (if (> arg 0)
5152 (progn
5153 (while (> arg 0)
5154 (or (zerop (forward-line 1))
5155 (signal 'end-of-buffer nil))
5156 ;; If the newline we just skipped is invisible,
5157 ;; don't count it.
5158 (let ((prop
5159 (get-char-property (1- (point)) 'invisible)))
5160 (if (if (eq buffer-invisibility-spec t)
5161 prop
5162 (or (memq prop buffer-invisibility-spec)
5163 (assq prop buffer-invisibility-spec)))
5164 (setq arg (1+ arg))))
5165 (setq arg (1- arg)))
5166 ;; If invisible text follows, and it is a number of complete lines,
5167 ;; skip it.
5168 (let ((opoint (point)))
5169 (while (and (not (eobp))
5170 (let ((prop
5171 (get-char-property (point) 'invisible)))
5172 (if (eq buffer-invisibility-spec t)
5173 prop
5174 (or (memq prop buffer-invisibility-spec)
5175 (assq prop buffer-invisibility-spec)))))
5176 (goto-char
5177 (if (get-text-property (point) 'invisible)
5178 (or (next-single-property-change (point) 'invisible)
5179 (point-max))
5180 (next-overlay-change (point)))))
5181 (unless (bolp)
5182 (goto-char opoint))))
5183 (let ((first t))
5184 (while (or first (<= arg 0))
5185 (if first
5186 (beginning-of-line)
5187 (or (zerop (forward-line -1))
5188 (signal 'beginning-of-buffer nil)))
5189 ;; If the newline we just moved to is invisible,
5190 ;; don't count it.
5191 (unless (bobp)
5192 (let ((prop
5193 (get-char-property (1- (point)) 'invisible)))
5194 (unless (if (eq buffer-invisibility-spec t)
5195 prop
5196 (or (memq prop buffer-invisibility-spec)
5197 (assq prop buffer-invisibility-spec)))
5198 (setq arg (1+ arg)))))
5199 (setq first nil))
5200 ;; If invisible text follows, and it is a number of complete lines,
5201 ;; skip it.
5202 (let ((opoint (point)))
5203 (while (and (not (bobp))
5204 (let ((prop
5205 (get-char-property (1- (point)) 'invisible)))
5206 (if (eq buffer-invisibility-spec t)
5207 prop
5208 (or (memq prop buffer-invisibility-spec)
5209 (assq prop buffer-invisibility-spec)))))
5210 (goto-char
5211 (if (get-text-property (1- (point)) 'invisible)
5212 (or (previous-single-property-change (point) 'invisible)
5213 (point-min))
5214 (previous-overlay-change (point)))))
5215 (unless (bolp)
5216 (goto-char opoint)))))
5217 ((beginning-of-buffer end-of-buffer)
5218 nil)))
5220 (defun end-of-visible-line ()
5221 "Move to end of current visible line."
5222 (end-of-line)
5223 ;; If the following character is currently invisible,
5224 ;; skip all characters with that same `invisible' property value,
5225 ;; then find the next newline.
5226 (while (and (not (eobp))
5227 (save-excursion
5228 (skip-chars-forward "^\n")
5229 (let ((prop
5230 (get-char-property (point) 'invisible)))
5231 (if (eq buffer-invisibility-spec t)
5232 prop
5233 (or (memq prop buffer-invisibility-spec)
5234 (assq prop buffer-invisibility-spec))))))
5235 (skip-chars-forward "^\n")
5236 (if (get-text-property (point) 'invisible)
5237 (goto-char (or (next-single-property-change (point) 'invisible)
5238 (point-max)))
5239 (goto-char (next-overlay-change (point))))
5240 (end-of-line)))
5242 (defun kill-current-buffer ()
5243 "Kill the current buffer.
5244 When called in the minibuffer, get out of the minibuffer
5245 using `abort-recursive-edit'.
5247 This is like `kill-this-buffer', but it doesn't have to be invoked
5248 via the menu bar, and pays no attention to the menu-bar's frame."
5249 (interactive)
5250 (let ((frame (selected-frame)))
5251 (if (and (frame-live-p frame)
5252 (not (window-minibuffer-p (frame-selected-window frame))))
5253 (kill-buffer (current-buffer))
5254 (abort-recursive-edit))))
5257 (defun insert-buffer (buffer)
5258 "Insert after point the contents of BUFFER.
5259 Puts mark after the inserted text.
5260 BUFFER may be a buffer or a buffer name."
5261 (declare (interactive-only insert-buffer-substring))
5262 (interactive
5263 (list
5264 (progn
5265 (barf-if-buffer-read-only)
5266 (read-buffer "Insert buffer: "
5267 (if (eq (selected-window) (next-window))
5268 (other-buffer (current-buffer))
5269 (window-buffer (next-window)))
5270 t))))
5271 (push-mark
5272 (save-excursion
5273 (insert-buffer-substring (get-buffer buffer))
5274 (point)))
5275 nil)
5277 (defun append-to-buffer (buffer start end)
5278 "Append to specified buffer the text of the region.
5279 It is inserted into that buffer before its point.
5281 When calling from a program, give three arguments:
5282 BUFFER (or buffer name), START and END.
5283 START and END specify the portion of the current buffer to be copied."
5284 (interactive
5285 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5286 (region-beginning) (region-end)))
5287 (let* ((oldbuf (current-buffer))
5288 (append-to (get-buffer-create buffer))
5289 (windows (get-buffer-window-list append-to t t))
5290 point)
5291 (save-excursion
5292 (with-current-buffer append-to
5293 (setq point (point))
5294 (barf-if-buffer-read-only)
5295 (insert-buffer-substring oldbuf start end)
5296 (dolist (window windows)
5297 (when (= (window-point window) point)
5298 (set-window-point window (point))))))))
5300 (defun prepend-to-buffer (buffer start end)
5301 "Prepend to specified buffer the text of the region.
5302 It is inserted into that buffer after its point.
5304 When calling from a program, give three arguments:
5305 BUFFER (or buffer name), START and END.
5306 START and END specify the portion of the current buffer to be copied."
5307 (interactive "BPrepend to buffer: \nr")
5308 (let ((oldbuf (current-buffer)))
5309 (with-current-buffer (get-buffer-create buffer)
5310 (barf-if-buffer-read-only)
5311 (save-excursion
5312 (insert-buffer-substring oldbuf start end)))))
5314 (defun copy-to-buffer (buffer start end)
5315 "Copy to specified buffer the text of the region.
5316 It is inserted into that buffer, replacing existing text there.
5318 When calling from a program, give three arguments:
5319 BUFFER (or buffer name), START and END.
5320 START and END specify the portion of the current buffer to be copied."
5321 (interactive "BCopy to buffer: \nr")
5322 (let ((oldbuf (current-buffer)))
5323 (with-current-buffer (get-buffer-create buffer)
5324 (barf-if-buffer-read-only)
5325 (erase-buffer)
5326 (save-excursion
5327 (insert-buffer-substring oldbuf start end)))))
5329 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5331 (defvar activate-mark-hook nil
5332 "Hook run when the mark becomes active.
5333 It is also run at the end of a command, if the mark is active and
5334 it is possible that the region may have changed.")
5336 (defvar deactivate-mark-hook nil
5337 "Hook run when the mark becomes inactive.")
5339 (defun mark (&optional force)
5340 "Return this buffer's mark value as integer, or nil if never set.
5342 In Transient Mark mode, this function signals an error if
5343 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5344 or the argument FORCE is non-nil, it disregards whether the mark
5345 is active, and returns an integer or nil in the usual way.
5347 If you are using this in an editing command, you are most likely making
5348 a mistake; see the documentation of `set-mark'."
5349 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5350 (marker-position (mark-marker))
5351 (signal 'mark-inactive nil)))
5353 ;; Behind display-selections-p.
5355 (defun deactivate-mark (&optional force)
5356 "Deactivate the mark.
5357 If Transient Mark mode is disabled, this function normally does
5358 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5360 Deactivating the mark sets `mark-active' to nil, updates the
5361 primary selection according to `select-active-regions', and runs
5362 `deactivate-mark-hook'.
5364 If Transient Mark mode was temporarily enabled, reset the value
5365 of the variable `transient-mark-mode'; if this causes Transient
5366 Mark mode to be disabled, don't change `mark-active' to nil or
5367 run `deactivate-mark-hook'."
5368 (when (or (region-active-p) force)
5369 (when (and (if (eq select-active-regions 'only)
5370 (eq (car-safe transient-mark-mode) 'only)
5371 select-active-regions)
5372 (region-active-p)
5373 (display-selections-p))
5374 ;; The var `saved-region-selection', if non-nil, is the text in
5375 ;; the region prior to the last command modifying the buffer.
5376 ;; Set the selection to that, or to the current region.
5377 (cond (saved-region-selection
5378 (if (gui-backend-selection-owner-p 'PRIMARY)
5379 (gui-set-selection 'PRIMARY saved-region-selection))
5380 (setq saved-region-selection nil))
5381 ;; If another program has acquired the selection, region
5382 ;; deactivation should not clobber it (Bug#11772).
5383 ((and (/= (region-beginning) (region-end))
5384 (or (gui-backend-selection-owner-p 'PRIMARY)
5385 (null (gui-backend-selection-exists-p 'PRIMARY))))
5386 (gui-set-selection 'PRIMARY
5387 (funcall region-extract-function nil)))))
5388 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5389 (cond
5390 ((eq (car-safe transient-mark-mode) 'only)
5391 (setq transient-mark-mode (cdr transient-mark-mode))
5392 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5393 (kill-local-variable 'transient-mark-mode)))
5394 ((eq transient-mark-mode 'lambda)
5395 (kill-local-variable 'transient-mark-mode)))
5396 (setq mark-active nil)
5397 (run-hooks 'deactivate-mark-hook)
5398 (redisplay--update-region-highlight (selected-window))))
5400 (defun activate-mark (&optional no-tmm)
5401 "Activate the mark.
5402 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5403 (when (mark t)
5404 (unless (region-active-p)
5405 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5406 (setq mark-active t)
5407 (unless (or transient-mark-mode no-tmm)
5408 (setq-local transient-mark-mode 'lambda))
5409 (run-hooks 'activate-mark-hook))))
5411 (defun set-mark (pos)
5412 "Set this buffer's mark to POS. Don't use this function!
5413 That is to say, don't use this function unless you want
5414 the user to see that the mark has moved, and you want the previous
5415 mark position to be lost.
5417 Normally, when a new mark is set, the old one should go on the stack.
5418 This is why most applications should use `push-mark', not `set-mark'.
5420 Novice Emacs Lisp programmers often try to use the mark for the wrong
5421 purposes. The mark saves a location for the user's convenience.
5422 Most editing commands should not alter the mark.
5423 To remember a location for internal use in the Lisp program,
5424 store it in a Lisp variable. Example:
5426 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5427 (if pos
5428 (progn
5429 (set-marker (mark-marker) pos (current-buffer))
5430 (activate-mark 'no-tmm))
5431 ;; Normally we never clear mark-active except in Transient Mark mode.
5432 ;; But when we actually clear out the mark value too, we must
5433 ;; clear mark-active in any mode.
5434 (deactivate-mark t)
5435 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5436 ;; it should never be nil if the mark is nil.
5437 (setq mark-active nil)
5438 (set-marker (mark-marker) nil)))
5440 (defun save-mark-and-excursion--save ()
5441 (cons
5442 (let ((mark (mark-marker)))
5443 (and (marker-position mark) (copy-marker mark)))
5444 mark-active))
5446 (defun save-mark-and-excursion--restore (saved-mark-info)
5447 (let ((saved-mark (car saved-mark-info))
5448 (omark (marker-position (mark-marker)))
5449 (nmark nil)
5450 (saved-mark-active (cdr saved-mark-info)))
5451 ;; Mark marker
5452 (if (null saved-mark)
5453 (set-marker (mark-marker) nil)
5454 (setf nmark (marker-position saved-mark))
5455 (set-marker (mark-marker) nmark)
5456 (set-marker saved-mark nil))
5457 ;; Mark active
5458 (let ((cur-mark-active mark-active))
5459 (setq mark-active saved-mark-active)
5460 ;; If mark is active now, and either was not active or was at a
5461 ;; different place, run the activate hook.
5462 (if saved-mark-active
5463 (when (or (not cur-mark-active)
5464 (not (eq omark nmark)))
5465 (run-hooks 'activate-mark-hook))
5466 ;; If mark has ceased to be active, run deactivate hook.
5467 (when cur-mark-active
5468 (run-hooks 'deactivate-mark-hook))))))
5470 (defmacro save-mark-and-excursion (&rest body)
5471 "Like `save-excursion', but also save and restore the mark state.
5472 This macro does what `save-excursion' did before Emacs 25.1."
5473 (declare (indent 0) (debug t))
5474 (let ((saved-marker-sym (make-symbol "saved-marker")))
5475 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5476 (unwind-protect
5477 (save-excursion ,@body)
5478 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5480 (defcustom use-empty-active-region nil
5481 "Whether \"region-aware\" commands should act on empty regions.
5482 If nil, region-aware commands treat the empty region as inactive.
5483 If non-nil, region-aware commands treat the region as active as
5484 long as the mark is active, even if the region is empty.
5486 Region-aware commands are those that act on the region if it is
5487 active and Transient Mark mode is enabled, and on the text near
5488 point otherwise."
5489 :type 'boolean
5490 :version "23.1"
5491 :group 'editing-basics)
5493 (defun use-region-p ()
5494 "Return t if the region is active and it is appropriate to act on it.
5495 This is used by commands that act specially on the region under
5496 Transient Mark mode.
5498 The return value is t if Transient Mark mode is enabled and the
5499 mark is active; furthermore, if `use-empty-active-region' is nil,
5500 the region must not be empty. Otherwise, the return value is nil.
5502 For some commands, it may be appropriate to ignore the value of
5503 `use-empty-active-region'; in that case, use `region-active-p'."
5504 (and (region-active-p)
5505 (or use-empty-active-region (> (region-end) (region-beginning)))))
5507 (defun region-active-p ()
5508 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5510 Some commands act specially on the region when Transient Mark
5511 mode is enabled. Usually, such commands should use
5512 `use-region-p' instead of this function, because `use-region-p'
5513 also checks the value of `use-empty-active-region'."
5514 (and transient-mark-mode mark-active
5515 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5516 ;; without the mark being set (e.g. bug#17324). We really should fix
5517 ;; that problem, but in the mean time, let's make sure we don't say the
5518 ;; region is active when there's no mark.
5519 (progn (cl-assert (mark)) t)))
5521 (defun region-bounds ()
5522 "Return the boundaries of the region as a pair of positions.
5523 Value is a list of cons cells of the form (START . END)."
5524 (funcall region-extract-function 'bounds))
5526 (defun region-noncontiguous-p ()
5527 "Return non-nil if the region contains several pieces.
5528 An example is a rectangular region handled as a list of
5529 separate contiguous regions for each line."
5530 (> (length (region-bounds)) 1))
5532 (defvar redisplay-unhighlight-region-function
5533 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5535 (defvar redisplay-highlight-region-function
5536 (lambda (start end window rol)
5537 (if (not (overlayp rol))
5538 (let ((nrol (make-overlay start end)))
5539 (funcall redisplay-unhighlight-region-function rol)
5540 (overlay-put nrol 'window window)
5541 (overlay-put nrol 'face 'region)
5542 ;; Normal priority so that a large region doesn't hide all the
5543 ;; overlays within it, but high secondary priority so that if it
5544 ;; ends/starts in the middle of a small overlay, that small overlay
5545 ;; won't hide the region's boundaries.
5546 (overlay-put nrol 'priority '(nil . 100))
5547 nrol)
5548 (unless (and (eq (overlay-buffer rol) (current-buffer))
5549 (eq (overlay-start rol) start)
5550 (eq (overlay-end rol) end))
5551 (move-overlay rol start end (current-buffer)))
5552 rol)))
5554 (defun redisplay--update-region-highlight (window)
5555 (let ((rol (window-parameter window 'internal-region-overlay)))
5556 (if (not (and (region-active-p)
5557 (or highlight-nonselected-windows
5558 (eq window (selected-window))
5559 (and (window-minibuffer-p)
5560 (eq window (minibuffer-selected-window))))))
5561 (funcall redisplay-unhighlight-region-function rol)
5562 (let* ((pt (window-point window))
5563 (mark (mark))
5564 (start (min pt mark))
5565 (end (max pt mark))
5566 (new
5567 (funcall redisplay-highlight-region-function
5568 start end window rol)))
5569 (unless (equal new rol)
5570 (set-window-parameter window 'internal-region-overlay
5571 new))))))
5573 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5574 "Hook run just before redisplay.
5575 It is called in each window that is to be redisplayed. It takes one argument,
5576 which is the window that will be redisplayed. When run, the `current-buffer'
5577 is set to the buffer displayed in that window.")
5579 (defun redisplay--pre-redisplay-functions (windows)
5580 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5581 (if (null windows)
5582 (with-current-buffer (window-buffer (selected-window))
5583 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5584 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5585 (with-current-buffer (window-buffer win)
5586 (run-hook-with-args 'pre-redisplay-functions win))))))
5588 (add-function :before pre-redisplay-function
5589 #'redisplay--pre-redisplay-functions)
5592 (defvar-local mark-ring nil
5593 "The list of former marks of the current buffer, most recent first.")
5594 (put 'mark-ring 'permanent-local t)
5596 (defcustom mark-ring-max 16
5597 "Maximum size of mark ring. Start discarding off end if gets this big."
5598 :type 'integer
5599 :group 'editing-basics)
5601 (defvar global-mark-ring nil
5602 "The list of saved global marks, most recent first.")
5604 (defcustom global-mark-ring-max 16
5605 "Maximum size of global mark ring. \
5606 Start discarding off end if gets this big."
5607 :type 'integer
5608 :group 'editing-basics)
5610 (defun pop-to-mark-command ()
5611 "Jump to mark, and pop a new position for mark off the ring.
5612 \(Does not affect global mark ring)."
5613 (interactive)
5614 (if (null (mark t))
5615 (user-error "No mark set in this buffer")
5616 (if (= (point) (mark t))
5617 (message "Mark popped"))
5618 (goto-char (mark t))
5619 (pop-mark)))
5621 (defun push-mark-command (arg &optional nomsg)
5622 "Set mark at where point is.
5623 If no prefix ARG and mark is already set there, just activate it.
5624 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5625 (interactive "P")
5626 (let ((mark (mark t)))
5627 (if (or arg (null mark) (/= mark (point)))
5628 (push-mark nil nomsg t)
5629 (activate-mark 'no-tmm)
5630 (unless nomsg
5631 (message "Mark activated")))))
5633 (defcustom set-mark-command-repeat-pop nil
5634 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5635 That means that C-u \\[set-mark-command] \\[set-mark-command]
5636 will pop the mark twice, and
5637 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5638 will pop the mark three times.
5640 A value of nil means \\[set-mark-command]'s behavior does not change
5641 after C-u \\[set-mark-command]."
5642 :type 'boolean
5643 :group 'editing-basics)
5645 (defun set-mark-command (arg)
5646 "Set the mark where point is, and activate it; or jump to the mark.
5647 Setting the mark also alters the region, which is the text
5648 between point and mark; this is the closest equivalent in
5649 Emacs to what some editors call the \"selection\".
5651 With no prefix argument, set the mark at point, and push the
5652 old mark position on local mark ring. Also push the new mark on
5653 global mark ring, if the previous mark was set in another buffer.
5655 When Transient Mark Mode is off, immediately repeating this
5656 command activates `transient-mark-mode' temporarily.
5658 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5659 jump to the mark, and set the mark from
5660 position popped off the local mark ring (this does not affect the global
5661 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5662 mark ring (see `pop-global-mark').
5664 If `set-mark-command-repeat-pop' is non-nil, repeating
5665 the \\[set-mark-command] command with no prefix argument pops the next position
5666 off the local (or global) mark ring and jumps there.
5668 With \\[universal-argument] \\[universal-argument] as prefix
5669 argument, unconditionally set mark where point is, even if
5670 `set-mark-command-repeat-pop' is non-nil.
5672 Novice Emacs Lisp programmers often try to use the mark for the wrong
5673 purposes. See the documentation of `set-mark' for more information."
5674 (interactive "P")
5675 (cond ((eq transient-mark-mode 'lambda)
5676 (kill-local-variable 'transient-mark-mode))
5677 ((eq (car-safe transient-mark-mode) 'only)
5678 (deactivate-mark)))
5679 (cond
5680 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5681 (push-mark-command nil))
5682 ((not (eq this-command 'set-mark-command))
5683 (if arg
5684 (pop-to-mark-command)
5685 (push-mark-command t)))
5686 ((and set-mark-command-repeat-pop
5687 (eq last-command 'pop-global-mark)
5688 (not arg))
5689 (setq this-command 'pop-global-mark)
5690 (pop-global-mark))
5691 ((or (and set-mark-command-repeat-pop
5692 (eq last-command 'pop-to-mark-command))
5693 arg)
5694 (setq this-command 'pop-to-mark-command)
5695 (pop-to-mark-command))
5696 ((eq last-command 'set-mark-command)
5697 (if (region-active-p)
5698 (progn
5699 (deactivate-mark)
5700 (message "Mark deactivated"))
5701 (activate-mark)
5702 (message "Mark activated")))
5704 (push-mark-command nil))))
5706 (defun push-mark (&optional location nomsg activate)
5707 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5708 If the last global mark pushed was not in the current buffer,
5709 also push LOCATION on the global mark ring.
5710 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5712 Novice Emacs Lisp programmers often try to use the mark for the wrong
5713 purposes. See the documentation of `set-mark' for more information.
5715 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5716 (unless (null (mark t))
5717 (let ((old (nth mark-ring-max mark-ring))
5718 (history-delete-duplicates nil))
5719 (add-to-history 'mark-ring (copy-marker (mark-marker)) mark-ring-max t)
5720 (when old
5721 (set-marker old nil))))
5722 (set-marker (mark-marker) (or location (point)) (current-buffer))
5723 ;; Now push the mark on the global mark ring.
5724 (if (and global-mark-ring
5725 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5726 ;; The last global mark pushed was in this same buffer.
5727 ;; Don't push another one.
5729 (let ((old (nth global-mark-ring-max global-mark-ring))
5730 (history-delete-duplicates nil))
5731 (add-to-history
5732 'global-mark-ring (copy-marker (mark-marker)) global-mark-ring-max t)
5733 (when old
5734 (set-marker old nil))))
5735 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5736 (message "Mark set"))
5737 (if (or activate (not transient-mark-mode))
5738 (set-mark (mark t)))
5739 nil)
5741 (defun pop-mark ()
5742 "Pop off mark ring into the buffer's actual mark.
5743 Does not set point. Does nothing if mark ring is empty."
5744 (when mark-ring
5745 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5746 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5747 (move-marker (car mark-ring) nil)
5748 (if (null (mark t)) (ding))
5749 (setq mark-ring (cdr mark-ring)))
5750 (deactivate-mark))
5752 (define-obsolete-function-alias
5753 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5754 (defun exchange-point-and-mark (&optional arg)
5755 "Put the mark where point is now, and point where the mark is now.
5756 This command works even when the mark is not active,
5757 and it reactivates the mark.
5759 If Transient Mark mode is on, a prefix ARG deactivates the mark
5760 if it is active, and otherwise avoids reactivating it. If
5761 Transient Mark mode is off, a prefix ARG enables Transient Mark
5762 mode temporarily."
5763 (interactive "P")
5764 (let ((omark (mark t))
5765 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5766 (if (null omark)
5767 (user-error "No mark set in this buffer"))
5768 (set-mark (point))
5769 (goto-char omark)
5770 (cond (temp-highlight
5771 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5772 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5773 (not (or arg (region-active-p))))
5774 (deactivate-mark))
5775 (t (activate-mark)))
5776 nil))
5778 (defcustom shift-select-mode t
5779 "When non-nil, shifted motion keys activate the mark momentarily.
5781 While the mark is activated in this way, any shift-translated point
5782 motion key extends the region, and if Transient Mark mode was off, it
5783 is temporarily turned on. Furthermore, the mark will be deactivated
5784 by any subsequent point motion key that was not shift-translated, or
5785 by any action that normally deactivates the mark in Transient Mark mode.
5787 See `this-command-keys-shift-translated' for the meaning of
5788 shift-translation."
5789 :type 'boolean
5790 :group 'editing-basics)
5792 (defun handle-shift-selection ()
5793 "Activate/deactivate mark depending on invocation thru shift translation.
5794 This function is called by `call-interactively' when a command
5795 with a `^' character in its `interactive' spec is invoked, before
5796 running the command itself.
5798 If `shift-select-mode' is enabled and the command was invoked
5799 through shift translation, set the mark and activate the region
5800 temporarily, unless it was already set in this way. See
5801 `this-command-keys-shift-translated' for the meaning of shift
5802 translation.
5804 Otherwise, if the region has been activated temporarily,
5805 deactivate it, and restore the variable `transient-mark-mode' to
5806 its earlier value."
5807 (cond ((and shift-select-mode this-command-keys-shift-translated)
5808 (unless (and mark-active
5809 (eq (car-safe transient-mark-mode) 'only))
5810 (setq-local transient-mark-mode
5811 (cons 'only
5812 (unless (eq transient-mark-mode 'lambda)
5813 transient-mark-mode)))
5814 (push-mark nil nil t)))
5815 ((eq (car-safe transient-mark-mode) 'only)
5816 (setq transient-mark-mode (cdr transient-mark-mode))
5817 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5818 (kill-local-variable 'transient-mark-mode))
5819 (deactivate-mark))))
5821 (define-minor-mode transient-mark-mode
5822 "Toggle Transient Mark mode.
5823 With a prefix argument ARG, enable Transient Mark mode if ARG is
5824 positive, and disable it otherwise. If called from Lisp, enable
5825 Transient Mark mode if ARG is omitted or nil.
5827 Transient Mark mode is a global minor mode. When enabled, the
5828 region is highlighted with the `region' face whenever the mark
5829 is active. The mark is \"deactivated\" by changing the buffer,
5830 and after certain other operations that set the mark but whose
5831 main purpose is something else--for example, incremental search,
5832 \\[beginning-of-buffer], and \\[end-of-buffer].
5834 You can also deactivate the mark by typing \\[keyboard-quit] or
5835 \\[keyboard-escape-quit].
5837 Many commands change their behavior when Transient Mark mode is
5838 in effect and the mark is active, by acting on the region instead
5839 of their usual default part of the buffer's text. Examples of
5840 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5841 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5842 To see the documentation of commands which are sensitive to the
5843 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5844 or \"mark.*active\" at the prompt."
5845 :global t
5846 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5847 :variable (default-value 'transient-mark-mode))
5849 (defvar widen-automatically t
5850 "Non-nil means it is ok for commands to call `widen' when they want to.
5851 Some commands will do this in order to go to positions outside
5852 the current accessible part of the buffer.
5854 If `widen-automatically' is nil, these commands will do something else
5855 as a fallback, and won't change the buffer bounds.")
5857 (defvar non-essential nil
5858 "Whether the currently executing code is performing an essential task.
5859 This variable should be non-nil only when running code which should not
5860 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5861 user for a password when we are simply scanning a set of files in the
5862 background or displaying possible completions before the user even asked
5863 for it.")
5865 (defun pop-global-mark ()
5866 "Pop off global mark ring and jump to the top location."
5867 (interactive)
5868 ;; Pop entries which refer to non-existent buffers.
5869 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5870 (setq global-mark-ring (cdr global-mark-ring)))
5871 (or global-mark-ring
5872 (error "No global mark set"))
5873 (let* ((marker (car global-mark-ring))
5874 (buffer (marker-buffer marker))
5875 (position (marker-position marker)))
5876 (setq global-mark-ring (nconc (cdr global-mark-ring)
5877 (list (car global-mark-ring))))
5878 (set-buffer buffer)
5879 (or (and (>= position (point-min))
5880 (<= position (point-max)))
5881 (if widen-automatically
5882 (widen)
5883 (error "Global mark position is outside accessible part of buffer")))
5884 (goto-char position)
5885 (switch-to-buffer buffer)))
5887 (defcustom next-line-add-newlines nil
5888 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5889 :type 'boolean
5890 :version "21.1"
5891 :group 'editing-basics)
5893 (defun next-line (&optional arg try-vscroll)
5894 "Move cursor vertically down ARG lines.
5895 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5896 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5897 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5898 function will not vscroll.
5900 ARG defaults to 1.
5902 If there is no character in the target line exactly under the current column,
5903 the cursor is positioned after the character in that line which spans this
5904 column, or at the end of the line if it is not long enough.
5905 If there is no line in the buffer after this one, behavior depends on the
5906 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5907 to create a line, and moves the cursor to that line. Otherwise it moves the
5908 cursor to the end of the buffer.
5910 If the variable `line-move-visual' is non-nil, this command moves
5911 by display lines. Otherwise, it moves by buffer lines, without
5912 taking variable-width characters or continued lines into account.
5913 See \\[next-logical-line] for a command that always moves by buffer lines.
5915 The command \\[set-goal-column] can be used to create
5916 a semipermanent goal column for this command.
5917 Then instead of trying to move exactly vertically (or as close as possible),
5918 this command moves to the specified goal column (or as close as possible).
5919 The goal column is stored in the variable `goal-column', which is nil
5920 when there is no goal column. Note that setting `goal-column'
5921 overrides `line-move-visual' and causes this command to move by buffer
5922 lines rather than by display lines."
5923 (declare (interactive-only forward-line))
5924 (interactive "^p\np")
5925 (or arg (setq arg 1))
5926 (if (and next-line-add-newlines (= arg 1))
5927 (if (save-excursion (end-of-line) (eobp))
5928 ;; When adding a newline, don't expand an abbrev.
5929 (let ((abbrev-mode nil))
5930 (end-of-line)
5931 (insert (if use-hard-newlines hard-newline "\n")))
5932 (line-move arg nil nil try-vscroll))
5933 (if (called-interactively-p 'interactive)
5934 (condition-case err
5935 (line-move arg nil nil try-vscroll)
5936 ((beginning-of-buffer end-of-buffer)
5937 (signal (car err) (cdr err))))
5938 (line-move arg nil nil try-vscroll)))
5939 nil)
5941 (defun previous-line (&optional arg try-vscroll)
5942 "Move cursor vertically up ARG lines.
5943 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5944 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5945 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5946 function will not vscroll.
5948 ARG defaults to 1.
5950 If there is no character in the target line exactly over the current column,
5951 the cursor is positioned after the character in that line which spans this
5952 column, or at the end of the line if it is not long enough.
5954 If the variable `line-move-visual' is non-nil, this command moves
5955 by display lines. Otherwise, it moves by buffer lines, without
5956 taking variable-width characters or continued lines into account.
5957 See \\[previous-logical-line] for a command that always moves by buffer lines.
5959 The command \\[set-goal-column] can be used to create
5960 a semipermanent goal column for this command.
5961 Then instead of trying to move exactly vertically (or as close as possible),
5962 this command moves to the specified goal column (or as close as possible).
5963 The goal column is stored in the variable `goal-column', which is nil
5964 when there is no goal column. Note that setting `goal-column'
5965 overrides `line-move-visual' and causes this command to move by buffer
5966 lines rather than by display lines."
5967 (declare (interactive-only
5968 "use `forward-line' with negative argument instead."))
5969 (interactive "^p\np")
5970 (or arg (setq arg 1))
5971 (if (called-interactively-p 'interactive)
5972 (condition-case err
5973 (line-move (- arg) nil nil try-vscroll)
5974 ((beginning-of-buffer end-of-buffer)
5975 (signal (car err) (cdr err))))
5976 (line-move (- arg) nil nil try-vscroll))
5977 nil)
5979 (defcustom track-eol nil
5980 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5981 This means moving to the end of each line moved onto.
5982 The beginning of a blank line does not count as the end of a line.
5983 This has no effect when the variable `line-move-visual' is non-nil."
5984 :type 'boolean
5985 :group 'editing-basics)
5987 (defcustom goal-column nil
5988 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5989 A non-nil setting overrides the variable `line-move-visual', which see."
5990 :type '(choice integer
5991 (const :tag "None" nil))
5992 :group 'editing-basics)
5993 (make-variable-buffer-local 'goal-column)
5995 (defvar temporary-goal-column 0
5996 "Current goal column for vertical motion.
5997 It is the column where point was at the start of the current run
5998 of vertical motion commands.
6000 When moving by visual lines via the function `line-move-visual', it is a cons
6001 cell (COL . HSCROLL), where COL is the x-position, in pixels,
6002 divided by the default column width, and HSCROLL is the number of
6003 columns by which window is scrolled from left margin.
6005 When the `track-eol' feature is doing its job, the value is
6006 `most-positive-fixnum'.")
6008 (defvar last--line-number-width 0
6009 "Last value of width used for displaying line numbers.
6010 Used internally by `line-move-visual'.")
6012 (defcustom line-move-ignore-invisible t
6013 "Non-nil means commands that move by lines ignore invisible newlines.
6014 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
6015 as if newlines that are invisible didn't exist, and count
6016 only visible newlines. Thus, moving across 2 newlines
6017 one of which is invisible will be counted as a one-line move.
6018 Also, a non-nil value causes invisible text to be ignored when
6019 counting columns for the purposes of keeping point in the same
6020 column by \\[next-line] and \\[previous-line].
6022 Outline mode sets this."
6023 :type 'boolean
6024 :group 'editing-basics)
6026 (defcustom line-move-visual t
6027 "When non-nil, `line-move' moves point by visual lines.
6028 This movement is based on where the cursor is displayed on the
6029 screen, instead of relying on buffer contents alone. It takes
6030 into account variable-width characters and line continuation.
6031 If nil, `line-move' moves point by logical lines.
6032 A non-nil setting of `goal-column' overrides the value of this variable
6033 and forces movement by logical lines.
6034 A window that is horizontally scrolled also forces movement by logical
6035 lines."
6036 :type 'boolean
6037 :group 'editing-basics
6038 :version "23.1")
6040 ;; Only used if display-graphic-p.
6041 (declare-function font-info "font.c" (name &optional frame))
6043 (defun default-font-height ()
6044 "Return the height in pixels of the current buffer's default face font.
6046 If the default font is remapped (see `face-remapping-alist'), the
6047 function returns the height of the remapped face."
6048 (let ((default-font (face-font 'default)))
6049 (cond
6050 ((and (display-multi-font-p)
6051 ;; Avoid calling font-info if the frame's default font was
6052 ;; not changed since the frame was created. That's because
6053 ;; font-info is expensive for some fonts, see bug #14838.
6054 (not (string= (frame-parameter nil 'font) default-font)))
6055 (aref (font-info default-font) 3))
6056 (t (frame-char-height)))))
6058 (defun default-font-width ()
6059 "Return the width in pixels of the current buffer's default face font.
6061 If the default font is remapped (see `face-remapping-alist'), the
6062 function returns the width of the remapped face."
6063 (let ((default-font (face-font 'default)))
6064 (cond
6065 ((and (display-multi-font-p)
6066 ;; Avoid calling font-info if the frame's default font was
6067 ;; not changed since the frame was created. That's because
6068 ;; font-info is expensive for some fonts, see bug #14838.
6069 (not (string= (frame-parameter nil 'font) default-font)))
6070 (let* ((info (font-info (face-font 'default)))
6071 (width (aref info 11)))
6072 (if (> width 0)
6073 width
6074 (aref info 10))))
6075 (t (frame-char-width)))))
6077 (defun default-line-height ()
6078 "Return the pixel height of current buffer's default-face text line.
6080 The value includes `line-spacing', if any, defined for the buffer
6081 or the frame."
6082 (let ((dfh (default-font-height))
6083 (lsp (if (display-graphic-p)
6084 (or line-spacing
6085 (default-value 'line-spacing)
6086 (frame-parameter nil 'line-spacing)
6088 0)))
6089 (if (floatp lsp)
6090 (setq lsp (truncate (* (frame-char-height) lsp))))
6091 (+ dfh lsp)))
6093 (defun window-screen-lines ()
6094 "Return the number of screen lines in the text area of the selected window.
6096 This is different from `window-text-height' in that this function counts
6097 lines in units of the height of the font used by the default face displayed
6098 in the window, not in units of the frame's default font, and also accounts
6099 for `line-spacing', if any, defined for the window's buffer or frame.
6101 The value is a floating-point number."
6102 (let ((edges (window-inside-pixel-edges))
6103 (dlh (default-line-height)))
6104 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
6106 ;; Returns non-nil if partial move was done.
6107 (defun line-move-partial (arg noerror &optional _to-end)
6108 (if (< arg 0)
6109 ;; Move backward (up).
6110 ;; If already vscrolled, reduce vscroll
6111 (let ((vs (window-vscroll nil t))
6112 (dlh (default-line-height)))
6113 (when (> vs dlh)
6114 (set-window-vscroll nil (- vs dlh) t)))
6116 ;; Move forward (down).
6117 (let* ((lh (window-line-height -1))
6118 (rowh (car lh))
6119 (vpos (nth 1 lh))
6120 (ypos (nth 2 lh))
6121 (rbot (nth 3 lh))
6122 (this-lh (window-line-height))
6123 (this-height (car this-lh))
6124 (this-ypos (nth 2 this-lh))
6125 (dlh (default-line-height))
6126 (wslines (window-screen-lines))
6127 (edges (window-inside-pixel-edges))
6128 (winh (- (nth 3 edges) (nth 1 edges) 1))
6129 py vs last-line)
6130 (if (> (mod wslines 1.0) 0.0)
6131 (setq wslines (round (+ wslines 0.5))))
6132 (when (or (null lh)
6133 (>= rbot dlh)
6134 (<= ypos (- dlh))
6135 (null this-lh)
6136 (<= this-ypos (- dlh)))
6137 (unless lh
6138 (let ((wend (pos-visible-in-window-p t nil t)))
6139 (setq rbot (nth 3 wend)
6140 rowh (nth 4 wend)
6141 vpos (nth 5 wend))))
6142 (unless this-lh
6143 (let ((wstart (pos-visible-in-window-p nil nil t)))
6144 (setq this-ypos (nth 2 wstart)
6145 this-height (nth 4 wstart))))
6146 (setq py
6147 (or (nth 1 this-lh)
6148 (let ((ppos (posn-at-point))
6149 col-row)
6150 (setq col-row (posn-actual-col-row ppos))
6151 (if col-row
6152 (- (cdr col-row) (window-vscroll))
6153 (cdr (posn-col-row ppos))))))
6154 ;; VPOS > 0 means the last line is only partially visible.
6155 ;; But if the part that is visible is at least as tall as the
6156 ;; default font, that means the line is actually fully
6157 ;; readable, and something like line-spacing is hidden. So in
6158 ;; that case we accept the last line in the window as still
6159 ;; visible, and consider the margin as starting one line
6160 ;; later.
6161 (if (and vpos (> vpos 0))
6162 (if (and rowh
6163 (>= rowh (default-font-height))
6164 (< rowh dlh))
6165 (setq last-line (min (- wslines scroll-margin) vpos))
6166 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6167 (cond
6168 ;; If last line of window is fully visible, and vscrolling
6169 ;; more would make this line invisible, move forward.
6170 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6171 (null this-height)
6172 (<= this-height dlh))
6173 (or (null rbot) (= rbot 0)))
6174 nil)
6175 ;; If cursor is not in the bottom scroll margin, and the
6176 ;; current line is not too tall, move forward.
6177 ((and (or (null this-height) (<= this-height winh))
6178 vpos
6179 (> vpos 0)
6180 (< py last-line))
6181 nil)
6182 ;; When already vscrolled, we vscroll some more if we can,
6183 ;; or clear vscroll and move forward at end of tall image.
6184 ((> vs 0)
6185 (when (or (and rbot (> rbot 0))
6186 (and this-height (> this-height dlh)))
6187 (set-window-vscroll nil (+ vs dlh) t)))
6188 ;; If cursor just entered the bottom scroll margin, move forward,
6189 ;; but also optionally vscroll one line so redisplay won't recenter.
6190 ((and vpos
6191 (> vpos 0)
6192 (= py last-line))
6193 ;; Don't vscroll if the partially-visible line at window
6194 ;; bottom is not too tall (a.k.a. "just one more text
6195 ;; line"): in that case, we do want redisplay to behave
6196 ;; normally, i.e. recenter or whatever.
6198 ;; Note: ROWH + RBOT from the value returned by
6199 ;; pos-visible-in-window-p give the total height of the
6200 ;; partially-visible glyph row at the end of the window. As
6201 ;; we are dealing with floats, we disregard sub-pixel
6202 ;; discrepancies between that and DLH.
6203 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6204 (set-window-vscroll nil dlh t))
6205 (line-move-1 arg noerror)
6207 ;; If there are lines above the last line, scroll-up one line.
6208 ((and vpos (> vpos 0))
6209 (scroll-up 1)
6211 ;; Finally, start vscroll.
6213 (set-window-vscroll nil dlh t)))))))
6216 ;; This is like line-move-1 except that it also performs
6217 ;; vertical scrolling of tall images if appropriate.
6218 ;; That is not really a clean thing to do, since it mixes
6219 ;; scrolling with cursor motion. But so far we don't have
6220 ;; a cleaner solution to the problem of making C-n do something
6221 ;; useful given a tall image.
6222 (defun line-move (arg &optional noerror _to-end try-vscroll)
6223 "Move forward ARG lines.
6224 If NOERROR, don't signal an error if we can't move ARG lines.
6225 TO-END is unused.
6226 TRY-VSCROLL controls whether to vscroll tall lines: if either
6227 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6228 not vscroll."
6229 (if noninteractive
6230 (line-move-1 arg noerror)
6231 (unless (and auto-window-vscroll try-vscroll
6232 ;; Only vscroll for single line moves
6233 (= (abs arg) 1)
6234 ;; Under scroll-conservatively, the display engine
6235 ;; does this better.
6236 (zerop scroll-conservatively)
6237 ;; But don't vscroll in a keyboard macro.
6238 (not defining-kbd-macro)
6239 (not executing-kbd-macro)
6240 (line-move-partial arg noerror))
6241 (set-window-vscroll nil 0 t)
6242 (if (and line-move-visual
6243 ;; Display-based column are incompatible with goal-column.
6244 (not goal-column)
6245 ;; When the text in the window is scrolled to the left,
6246 ;; display-based motion doesn't make sense (because each
6247 ;; logical line occupies exactly one screen line).
6248 (not (> (window-hscroll) 0))
6249 ;; Likewise when the text _was_ scrolled to the left
6250 ;; when the current run of vertical motion commands
6251 ;; started.
6252 (not (and (memq last-command
6253 `(next-line previous-line ,this-command))
6254 auto-hscroll-mode
6255 (numberp temporary-goal-column)
6256 (>= temporary-goal-column
6257 (- (window-width) hscroll-margin)))))
6258 (prog1 (line-move-visual arg noerror)
6259 ;; If we moved into a tall line, set vscroll to make
6260 ;; scrolling through tall images more smooth.
6261 (let ((lh (line-pixel-height))
6262 (edges (window-inside-pixel-edges))
6263 (dlh (default-line-height))
6264 winh)
6265 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6266 (if (and (< arg 0)
6267 (< (point) (window-start))
6268 (> lh winh))
6269 (set-window-vscroll
6271 (- lh dlh) t))))
6272 (line-move-1 arg noerror)))))
6274 ;; Display-based alternative to line-move-1.
6275 ;; Arg says how many lines to move. The value is t if we can move the
6276 ;; specified number of lines.
6277 (defun line-move-visual (arg &optional noerror)
6278 "Move ARG lines forward.
6279 If NOERROR, don't signal an error if we can't move that many lines."
6280 (let ((opoint (point))
6281 (hscroll (window-hscroll))
6282 (lnum-width (line-number-display-width t))
6283 target-hscroll)
6284 ;; Check if the previous command was a line-motion command, or if
6285 ;; we were called from some other command.
6286 (if (and (consp temporary-goal-column)
6287 (memq last-command `(next-line previous-line ,this-command)))
6288 ;; If so, there's no need to reset `temporary-goal-column',
6289 ;; but we may need to hscroll.
6290 (progn
6291 (if (or (/= (cdr temporary-goal-column) hscroll)
6292 (> (cdr temporary-goal-column) 0))
6293 (setq target-hscroll (cdr temporary-goal-column)))
6294 ;; Update the COLUMN part of temporary-goal-column if the
6295 ;; line-number display changed its width since the last
6296 ;; time.
6297 (setq temporary-goal-column
6298 (cons (+ (car temporary-goal-column)
6299 (/ (float (- lnum-width last--line-number-width))
6300 (frame-char-width)))
6301 (cdr temporary-goal-column)))
6302 (setq last--line-number-width lnum-width))
6303 ;; Otherwise, we should reset `temporary-goal-column'.
6304 (let ((posn (posn-at-point))
6305 x-pos)
6306 (cond
6307 ;; Handle the `overflow-newline-into-fringe' case
6308 ;; (left-fringe is for the R2L case):
6309 ((memq (nth 1 posn) '(right-fringe left-fringe))
6310 (setq temporary-goal-column (cons (window-width) hscroll)))
6311 ((car (posn-x-y posn))
6312 (setq x-pos (car (posn-x-y posn)))
6313 ;; In R2L lines, the X pixel coordinate is measured from the
6314 ;; left edge of the window, but columns are still counted
6315 ;; from the logical-order beginning of the line, i.e. from
6316 ;; the right edge in this case. We need to adjust for that.
6317 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6318 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6319 (setq temporary-goal-column
6320 (cons (/ (float x-pos)
6321 (frame-char-width))
6322 hscroll)))
6323 (executing-kbd-macro
6324 ;; When we move beyond the first/last character visible in
6325 ;; the window, posn-at-point will return nil, so we need to
6326 ;; approximate the goal column as below.
6327 (setq temporary-goal-column
6328 (mod (current-column) (window-text-width)))))))
6329 (if target-hscroll
6330 (set-window-hscroll (selected-window) target-hscroll))
6331 ;; vertical-motion can move more than it was asked to if it moves
6332 ;; across display strings with newlines. We don't want to ring
6333 ;; the bell and announce beginning/end of buffer in that case.
6334 (or (and (or (and (>= arg 0)
6335 (>= (vertical-motion
6336 (cons (or goal-column
6337 (if (consp temporary-goal-column)
6338 (car temporary-goal-column)
6339 temporary-goal-column))
6340 arg))
6341 arg))
6342 (and (< arg 0)
6343 (<= (vertical-motion
6344 (cons (or goal-column
6345 (if (consp temporary-goal-column)
6346 (car temporary-goal-column)
6347 temporary-goal-column))
6348 arg))
6349 arg)))
6350 (or (>= arg 0)
6351 (/= (point) opoint)
6352 ;; If the goal column lies on a display string,
6353 ;; `vertical-motion' advances the cursor to the end
6354 ;; of the string. For arg < 0, this can cause the
6355 ;; cursor to get stuck. (Bug#3020).
6356 (= (vertical-motion arg) arg)))
6357 (unless noerror
6358 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6359 nil)))))
6361 ;; This is the guts of next-line and previous-line.
6362 ;; Arg says how many lines to move.
6363 ;; The value is t if we can move the specified number of lines.
6364 (defun line-move-1 (arg &optional noerror _to-end)
6365 ;; Don't run any point-motion hooks, and disregard intangibility,
6366 ;; for intermediate positions.
6367 (let ((inhibit-point-motion-hooks t)
6368 (opoint (point))
6369 (orig-arg arg))
6370 (if (consp temporary-goal-column)
6371 (setq temporary-goal-column (+ (car temporary-goal-column)
6372 (cdr temporary-goal-column))))
6373 (unwind-protect
6374 (progn
6375 (if (not (memq last-command '(next-line previous-line)))
6376 (setq temporary-goal-column
6377 (if (and track-eol (eolp)
6378 ;; Don't count beg of empty line as end of line
6379 ;; unless we just did explicit end-of-line.
6380 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6381 most-positive-fixnum
6382 (current-column))))
6384 (if (not (or (integerp selective-display)
6385 line-move-ignore-invisible))
6386 ;; Use just newline characters.
6387 ;; Set ARG to 0 if we move as many lines as requested.
6388 (or (if (> arg 0)
6389 (progn (if (> arg 1) (forward-line (1- arg)))
6390 ;; This way of moving forward ARG lines
6391 ;; verifies that we have a newline after the last one.
6392 ;; It doesn't get confused by intangible text.
6393 (end-of-line)
6394 (if (zerop (forward-line 1))
6395 (setq arg 0)))
6396 (and (zerop (forward-line arg))
6397 (bolp)
6398 (setq arg 0)))
6399 (unless noerror
6400 (signal (if (< arg 0)
6401 'beginning-of-buffer
6402 'end-of-buffer)
6403 nil)))
6404 ;; Move by arg lines, but ignore invisible ones.
6405 (let (done)
6406 (while (and (> arg 0) (not done))
6407 ;; If the following character is currently invisible,
6408 ;; skip all characters with that same `invisible' property value.
6409 (while (and (not (eobp)) (invisible-p (point)))
6410 (goto-char (next-char-property-change (point))))
6411 ;; Move a line.
6412 ;; We don't use `end-of-line', since we want to escape
6413 ;; from field boundaries occurring exactly at point.
6414 (goto-char (constrain-to-field
6415 (let ((inhibit-field-text-motion t))
6416 (line-end-position))
6417 (point) t t
6418 'inhibit-line-move-field-capture))
6419 ;; If there's no invisibility here, move over the newline.
6420 (cond
6421 ((eobp)
6422 (if (not noerror)
6423 (signal 'end-of-buffer nil)
6424 (setq done t)))
6425 ((and (> arg 1) ;; Use vertical-motion for last move
6426 (not (integerp selective-display))
6427 (not (invisible-p (point))))
6428 ;; We avoid vertical-motion when possible
6429 ;; because that has to fontify.
6430 (forward-line 1))
6431 ;; Otherwise move a more sophisticated way.
6432 ((zerop (vertical-motion 1))
6433 (if (not noerror)
6434 (signal 'end-of-buffer nil)
6435 (setq done t))))
6436 (unless done
6437 (setq arg (1- arg))))
6438 ;; The logic of this is the same as the loop above,
6439 ;; it just goes in the other direction.
6440 (while (and (< arg 0) (not done))
6441 ;; For completely consistency with the forward-motion
6442 ;; case, we should call beginning-of-line here.
6443 ;; However, if point is inside a field and on a
6444 ;; continued line, the call to (vertical-motion -1)
6445 ;; below won't move us back far enough; then we return
6446 ;; to the same column in line-move-finish, and point
6447 ;; gets stuck -- cyd
6448 (forward-line 0)
6449 (cond
6450 ((bobp)
6451 (if (not noerror)
6452 (signal 'beginning-of-buffer nil)
6453 (setq done t)))
6454 ((and (< arg -1) ;; Use vertical-motion for last move
6455 (not (integerp selective-display))
6456 (not (invisible-p (1- (point)))))
6457 (forward-line -1))
6458 ((zerop (vertical-motion -1))
6459 (if (not noerror)
6460 (signal 'beginning-of-buffer nil)
6461 (setq done t))))
6462 (unless done
6463 (setq arg (1+ arg))
6464 (while (and ;; Don't move over previous invis lines
6465 ;; if our target is the middle of this line.
6466 (or (zerop (or goal-column temporary-goal-column))
6467 (< arg 0))
6468 (not (bobp)) (invisible-p (1- (point))))
6469 (goto-char (previous-char-property-change (point))))))))
6470 ;; This is the value the function returns.
6471 (= arg 0))
6473 (cond ((> arg 0)
6474 ;; If we did not move down as far as desired, at least go
6475 ;; to end of line. Be sure to call point-entered and
6476 ;; point-left-hooks.
6477 (let* ((npoint (prog1 (line-end-position)
6478 (goto-char opoint)))
6479 (inhibit-point-motion-hooks nil))
6480 (goto-char npoint)))
6481 ((< arg 0)
6482 ;; If we did not move up as far as desired,
6483 ;; at least go to beginning of line.
6484 (let* ((npoint (prog1 (line-beginning-position)
6485 (goto-char opoint)))
6486 (inhibit-point-motion-hooks nil))
6487 (goto-char npoint)))
6489 (line-move-finish (or goal-column temporary-goal-column)
6490 opoint (> orig-arg 0)))))))
6492 (defun line-move-finish (column opoint forward)
6493 (let ((repeat t))
6494 (while repeat
6495 ;; Set REPEAT to t to repeat the whole thing.
6496 (setq repeat nil)
6498 (let (new
6499 (old (point))
6500 (line-beg (line-beginning-position))
6501 (line-end
6502 ;; Compute the end of the line
6503 ;; ignoring effectively invisible newlines.
6504 (save-excursion
6505 ;; Like end-of-line but ignores fields.
6506 (skip-chars-forward "^\n")
6507 (while (and (not (eobp)) (invisible-p (point)))
6508 (goto-char (next-char-property-change (point)))
6509 (skip-chars-forward "^\n"))
6510 (point))))
6512 ;; Move to the desired column.
6513 (if (and line-move-visual
6514 (not (or truncate-lines truncate-partial-width-windows)))
6515 ;; Under line-move-visual, goal-column should be
6516 ;; interpreted in units of the frame's canonical character
6517 ;; width, which is exactly what vertical-motion does.
6518 (vertical-motion (cons column 0))
6519 (line-move-to-column (truncate column)))
6521 ;; Corner case: suppose we start out in a field boundary in
6522 ;; the middle of a continued line. When we get to
6523 ;; line-move-finish, point is at the start of a new *screen*
6524 ;; line but the same text line; then line-move-to-column would
6525 ;; move us backwards. Test using C-n with point on the "x" in
6526 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6527 (and forward
6528 (< (point) old)
6529 (goto-char old))
6531 (setq new (point))
6533 ;; Process intangibility within a line.
6534 ;; With inhibit-point-motion-hooks bound to nil, a call to
6535 ;; goto-char moves point past intangible text.
6537 ;; However, inhibit-point-motion-hooks controls both the
6538 ;; intangibility and the point-entered/point-left hooks. The
6539 ;; following hack avoids calling the point-* hooks
6540 ;; unnecessarily. Note that we move *forward* past intangible
6541 ;; text when the initial and final points are the same.
6542 (goto-char new)
6543 (let ((inhibit-point-motion-hooks nil))
6544 (goto-char new)
6546 ;; If intangibility moves us to a different (later) place
6547 ;; in the same line, use that as the destination.
6548 (if (<= (point) line-end)
6549 (setq new (point))
6550 ;; If that position is "too late",
6551 ;; try the previous allowable position.
6552 ;; See if it is ok.
6553 (backward-char)
6554 (if (if forward
6555 ;; If going forward, don't accept the previous
6556 ;; allowable position if it is before the target line.
6557 (< line-beg (point))
6558 ;; If going backward, don't accept the previous
6559 ;; allowable position if it is still after the target line.
6560 (<= (point) line-end))
6561 (setq new (point))
6562 ;; As a last resort, use the end of the line.
6563 (setq new line-end))))
6565 ;; Now move to the updated destination, processing fields
6566 ;; as well as intangibility.
6567 (goto-char opoint)
6568 (let ((inhibit-point-motion-hooks nil))
6569 (goto-char
6570 ;; Ignore field boundaries if the initial and final
6571 ;; positions have the same `field' property, even if the
6572 ;; fields are non-contiguous. This seems to be "nicer"
6573 ;; behavior in many situations.
6574 (if (eq (get-char-property new 'field)
6575 (get-char-property opoint 'field))
6577 (constrain-to-field new opoint t t
6578 'inhibit-line-move-field-capture))))
6580 ;; If all this moved us to a different line,
6581 ;; retry everything within that new line.
6582 (when (or (< (point) line-beg) (> (point) line-end))
6583 ;; Repeat the intangibility and field processing.
6584 (setq repeat t))))))
6586 (defun line-move-to-column (col)
6587 "Try to find column COL, considering invisibility.
6588 This function works only in certain cases,
6589 because what we really need is for `move-to-column'
6590 and `current-column' to be able to ignore invisible text."
6591 (if (zerop col)
6592 (beginning-of-line)
6593 (move-to-column col))
6595 (when (and line-move-ignore-invisible
6596 (not (bolp)) (invisible-p (1- (point))))
6597 (let ((normal-location (point))
6598 (normal-column (current-column)))
6599 ;; If the following character is currently invisible,
6600 ;; skip all characters with that same `invisible' property value.
6601 (while (and (not (eobp))
6602 (invisible-p (point)))
6603 (goto-char (next-char-property-change (point))))
6604 ;; Have we advanced to a larger column position?
6605 (if (> (current-column) normal-column)
6606 ;; We have made some progress towards the desired column.
6607 ;; See if we can make any further progress.
6608 (line-move-to-column (+ (current-column) (- col normal-column)))
6609 ;; Otherwise, go to the place we originally found
6610 ;; and move back over invisible text.
6611 ;; that will get us to the same place on the screen
6612 ;; but with a more reasonable buffer position.
6613 (goto-char normal-location)
6614 (let ((line-beg
6615 ;; We want the real line beginning, so it's consistent
6616 ;; with bolp below, otherwise we might infloop.
6617 (let ((inhibit-field-text-motion t))
6618 (line-beginning-position))))
6619 (while (and (not (bolp)) (invisible-p (1- (point))))
6620 (goto-char (previous-char-property-change (point) line-beg))))))))
6622 (defun move-end-of-line (arg)
6623 "Move point to end of current line as displayed.
6624 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6625 If point reaches the beginning or end of buffer, it stops there.
6627 To ignore the effects of the `intangible' text or overlay
6628 property, bind `inhibit-point-motion-hooks' to t.
6629 If there is an image in the current line, this function
6630 disregards newlines that are part of the text on which the image
6631 rests."
6632 (interactive "^p")
6633 (or arg (setq arg 1))
6634 (let (done)
6635 (while (not done)
6636 (let ((newpos
6637 (save-excursion
6638 (let ((goal-column 0)
6639 (line-move-visual nil))
6640 (and (line-move arg t)
6641 ;; With bidi reordering, we may not be at bol,
6642 ;; so make sure we are.
6643 (skip-chars-backward "^\n")
6644 (not (bobp))
6645 (progn
6646 (while (and (not (bobp)) (invisible-p (1- (point))))
6647 (goto-char (previous-single-char-property-change
6648 (point) 'invisible)))
6649 (backward-char 1)))
6650 (point)))))
6651 (goto-char newpos)
6652 (if (and (> (point) newpos)
6653 (eq (preceding-char) ?\n))
6654 (backward-char 1)
6655 (if (and (> (point) newpos) (not (eobp))
6656 (not (eq (following-char) ?\n)))
6657 ;; If we skipped something intangible and now we're not
6658 ;; really at eol, keep going.
6659 (setq arg 1)
6660 (setq done t)))))))
6662 (defun move-beginning-of-line (arg)
6663 "Move point to beginning of current line as displayed.
6664 \(If there's an image in the line, this disregards newlines
6665 which are part of the text that the image rests on.)
6667 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6668 If point reaches the beginning or end of buffer, it stops there.
6669 \(But if the buffer doesn't end in a newline, it stops at the
6670 beginning of the last line.)
6671 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6672 (interactive "^p")
6673 (or arg (setq arg 1))
6675 (let ((orig (point))
6676 first-vis first-vis-field-value)
6678 ;; Move by lines, if ARG is not 1 (the default).
6679 (if (/= arg 1)
6680 (let ((line-move-visual nil))
6681 (line-move (1- arg) t)))
6683 ;; Move to beginning-of-line, ignoring fields and invisible text.
6684 (skip-chars-backward "^\n")
6685 (while (and (not (bobp)) (invisible-p (1- (point))))
6686 (goto-char (previous-char-property-change (point)))
6687 (skip-chars-backward "^\n"))
6689 ;; Now find first visible char in the line.
6690 (while (and (< (point) orig) (invisible-p (point)))
6691 (goto-char (next-char-property-change (point) orig)))
6692 (setq first-vis (point))
6694 ;; See if fields would stop us from reaching FIRST-VIS.
6695 (setq first-vis-field-value
6696 (constrain-to-field first-vis orig (/= arg 1) t nil))
6698 (goto-char (if (/= first-vis-field-value first-vis)
6699 ;; If yes, obey them.
6700 first-vis-field-value
6701 ;; Otherwise, move to START with attention to fields.
6702 ;; (It is possible that fields never matter in this case.)
6703 (constrain-to-field (point) orig
6704 (/= arg 1) t nil)))))
6707 ;; Many people have said they rarely use this feature, and often type
6708 ;; it by accident. Maybe it shouldn't even be on a key.
6709 (put 'set-goal-column 'disabled t)
6711 (defun set-goal-column (arg)
6712 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6713 Those commands will move to this position in the line moved to
6714 rather than trying to keep the same horizontal position.
6715 With a non-nil argument ARG, clears out the goal column
6716 so that \\[next-line] and \\[previous-line] resume vertical motion.
6717 The goal column is stored in the variable `goal-column'.
6718 This is a buffer-local setting."
6719 (interactive "P")
6720 (if arg
6721 (progn
6722 (setq goal-column nil)
6723 (message "No goal column"))
6724 (setq goal-column (current-column))
6725 ;; The older method below can be erroneous if `set-goal-column' is bound
6726 ;; to a sequence containing %
6727 ;;(message (substitute-command-keys
6728 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6729 ;;goal-column)
6730 (message "%s"
6731 (concat
6732 (format "Goal column %d " goal-column)
6733 (substitute-command-keys
6734 "(use \\[set-goal-column] with an arg to unset it)")))
6737 nil)
6739 ;;; Editing based on visual lines, as opposed to logical lines.
6741 (defun end-of-visual-line (&optional n)
6742 "Move point to end of current visual line.
6743 With argument N not nil or 1, move forward N - 1 visual lines first.
6744 If point reaches the beginning or end of buffer, it stops there.
6745 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6746 (interactive "^p")
6747 (or n (setq n 1))
6748 (if (/= n 1)
6749 (let ((line-move-visual t))
6750 (line-move (1- n) t)))
6751 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6752 ;; constrain to field boundaries, so we don't either.
6753 (vertical-motion (cons (window-width) 0)))
6755 (defun beginning-of-visual-line (&optional n)
6756 "Move point to beginning of current visual line.
6757 With argument N not nil or 1, move forward N - 1 visual lines first.
6758 If point reaches the beginning or end of buffer, it stops there.
6759 \(But if the buffer doesn't end in a newline, it stops at the
6760 beginning of the last visual line.)
6761 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6762 (interactive "^p")
6763 (or n (setq n 1))
6764 (let ((opoint (point)))
6765 (if (/= n 1)
6766 (let ((line-move-visual t))
6767 (line-move (1- n) t)))
6768 (vertical-motion 0)
6769 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6770 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6772 (defun kill-visual-line (&optional arg)
6773 "Kill the rest of the visual line.
6774 With prefix argument ARG, kill that many visual lines from point.
6775 If ARG is negative, kill visual lines backward.
6776 If ARG is zero, kill the text before point on the current visual
6777 line.
6779 If you want to append the killed line to the last killed text,
6780 use \\[append-next-kill] before \\[kill-line].
6782 If the buffer is read-only, Emacs will beep and refrain from deleting
6783 the line, but put the line in the kill ring anyway. This means that
6784 you can use this command to copy text from a read-only buffer.
6785 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6786 even beep.)"
6787 (interactive "P")
6788 ;; Like in `kill-line', it's better to move point to the other end
6789 ;; of the kill before killing.
6790 (let ((opoint (point))
6791 (kill-whole-line (and kill-whole-line (bolp))))
6792 (if arg
6793 (vertical-motion (prefix-numeric-value arg))
6794 (end-of-visual-line 1)
6795 (if (= (point) opoint)
6796 (vertical-motion 1)
6797 ;; Skip any trailing whitespace at the end of the visual line.
6798 ;; We used to do this only if `show-trailing-whitespace' is
6799 ;; nil, but that's wrong; the correct thing would be to check
6800 ;; whether the trailing whitespace is highlighted. But, it's
6801 ;; OK to just do this unconditionally.
6802 (skip-chars-forward " \t")))
6803 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6804 (1+ (point))
6805 (point)))))
6807 (defun next-logical-line (&optional arg try-vscroll)
6808 "Move cursor vertically down ARG lines.
6809 This is identical to `next-line', except that it always moves
6810 by logical lines instead of visual lines, ignoring the value of
6811 the variable `line-move-visual'."
6812 (interactive "^p\np")
6813 (let ((line-move-visual nil))
6814 (with-no-warnings
6815 (next-line arg try-vscroll))))
6817 (defun previous-logical-line (&optional arg try-vscroll)
6818 "Move cursor vertically up ARG lines.
6819 This is identical to `previous-line', except that it always moves
6820 by logical lines instead of visual lines, ignoring the value of
6821 the variable `line-move-visual'."
6822 (interactive "^p\np")
6823 (let ((line-move-visual nil))
6824 (with-no-warnings
6825 (previous-line arg try-vscroll))))
6827 (defgroup visual-line nil
6828 "Editing based on visual lines."
6829 :group 'convenience
6830 :version "23.1")
6832 (defvar visual-line-mode-map
6833 (let ((map (make-sparse-keymap)))
6834 (define-key map [remap kill-line] 'kill-visual-line)
6835 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6836 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6837 ;; These keybindings interfere with xterm function keys. Are
6838 ;; there any other suitable bindings?
6839 ;; (define-key map "\M-[" 'previous-logical-line)
6840 ;; (define-key map "\M-]" 'next-logical-line)
6841 map))
6843 (defcustom visual-line-fringe-indicators '(nil nil)
6844 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6845 The value should be a list of the form (LEFT RIGHT), where LEFT
6846 and RIGHT are symbols representing the bitmaps to display, to
6847 indicate wrapped lines, in the left and right fringes respectively.
6848 See also `fringe-indicator-alist'.
6849 The default is not to display fringe indicators for wrapped lines.
6850 This variable does not affect fringe indicators displayed for
6851 other purposes."
6852 :type '(list (choice (const :tag "Hide left indicator" nil)
6853 (const :tag "Left curly arrow" left-curly-arrow)
6854 (symbol :tag "Other bitmap"))
6855 (choice (const :tag "Hide right indicator" nil)
6856 (const :tag "Right curly arrow" right-curly-arrow)
6857 (symbol :tag "Other bitmap")))
6858 :set (lambda (symbol value)
6859 (dolist (buf (buffer-list))
6860 (with-current-buffer buf
6861 (when (and (boundp 'visual-line-mode)
6862 (symbol-value 'visual-line-mode))
6863 (setq fringe-indicator-alist
6864 (cons (cons 'continuation value)
6865 (assq-delete-all
6866 'continuation
6867 (copy-tree fringe-indicator-alist)))))))
6868 (set-default symbol value)))
6870 (defvar visual-line--saved-state nil)
6872 (define-minor-mode visual-line-mode
6873 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6874 Interactively, with a prefix argument, enable
6875 Visual Line mode if the prefix argument is positive,
6876 and disable it otherwise. If called from Lisp, toggle
6877 the mode if ARG is `toggle', disable the mode if ARG is
6878 a non-positive integer, and enable the mode otherwise
6879 \(including if ARG is omitted or nil or a positive integer).
6881 When Visual Line mode is enabled, `word-wrap' is turned on in
6882 this buffer, and simple editing commands are redefined to act on
6883 visual lines, not logical lines. See Info node `Visual Line
6884 Mode' for details."
6885 :keymap visual-line-mode-map
6886 :group 'visual-line
6887 :lighter " Wrap"
6888 (if visual-line-mode
6889 (progn
6890 (set (make-local-variable 'visual-line--saved-state) nil)
6891 ;; Save the local values of some variables, to be restored if
6892 ;; visual-line-mode is turned off.
6893 (dolist (var '(line-move-visual truncate-lines
6894 truncate-partial-width-windows
6895 word-wrap fringe-indicator-alist))
6896 (if (local-variable-p var)
6897 (push (cons var (symbol-value var))
6898 visual-line--saved-state)))
6899 (set (make-local-variable 'line-move-visual) t)
6900 (set (make-local-variable 'truncate-partial-width-windows) nil)
6901 (setq truncate-lines nil
6902 word-wrap t
6903 fringe-indicator-alist
6904 (cons (cons 'continuation visual-line-fringe-indicators)
6905 fringe-indicator-alist)))
6906 (kill-local-variable 'line-move-visual)
6907 (kill-local-variable 'word-wrap)
6908 (kill-local-variable 'truncate-lines)
6909 (kill-local-variable 'truncate-partial-width-windows)
6910 (kill-local-variable 'fringe-indicator-alist)
6911 (dolist (saved visual-line--saved-state)
6912 (set (make-local-variable (car saved)) (cdr saved)))
6913 (kill-local-variable 'visual-line--saved-state)))
6915 (defun turn-on-visual-line-mode ()
6916 (visual-line-mode 1))
6918 (define-globalized-minor-mode global-visual-line-mode
6919 visual-line-mode turn-on-visual-line-mode)
6922 (defun transpose-chars (arg)
6923 "Interchange characters around point, moving forward one character.
6924 With prefix arg ARG, effect is to take character before point
6925 and drag it forward past ARG other characters (backward if ARG negative).
6926 If no argument and at end of line, the previous two chars are exchanged."
6927 (interactive "*P")
6928 (when (and (null arg) (eolp) (not (bobp))
6929 (not (get-text-property (1- (point)) 'read-only)))
6930 (forward-char -1))
6931 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6933 (defun transpose-words (arg)
6934 "Interchange words around point, leaving point at end of them.
6935 With prefix arg ARG, effect is to take word before or around point
6936 and drag it forward past ARG other words (backward if ARG negative).
6937 If ARG is zero, the words around or after point and around or after mark
6938 are interchanged."
6939 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6940 (interactive "*p")
6941 (transpose-subr 'forward-word arg))
6943 (defun transpose-sexps (arg)
6944 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6945 Unlike `transpose-words', point must be between the two sexps and not
6946 in the middle of a sexp to be transposed.
6947 With non-zero prefix arg ARG, effect is to take the sexp before point
6948 and drag it forward past ARG other sexps (backward if ARG is negative).
6949 If ARG is zero, the sexps ending at or after point and at or after mark
6950 are interchanged."
6951 (interactive "*p")
6952 (transpose-subr
6953 (lambda (arg)
6954 ;; Here we should try to simulate the behavior of
6955 ;; (cons (progn (forward-sexp x) (point))
6956 ;; (progn (forward-sexp (- x)) (point)))
6957 ;; Except that we don't want to rely on the second forward-sexp
6958 ;; putting us back to where we want to be, since forward-sexp-function
6959 ;; might do funny things like infix-precedence.
6960 (if (if (> arg 0)
6961 (looking-at "\\sw\\|\\s_")
6962 (and (not (bobp))
6963 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6964 ;; Jumping over a symbol. We might be inside it, mind you.
6965 (progn (funcall (if (> arg 0)
6966 'skip-syntax-backward 'skip-syntax-forward)
6967 "w_")
6968 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6969 ;; Otherwise, we're between sexps. Take a step back before jumping
6970 ;; to make sure we'll obey the same precedence no matter which direction
6971 ;; we're going.
6972 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6973 (cons (save-excursion (forward-sexp arg) (point))
6974 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6975 (not (zerop (funcall (if (> arg 0)
6976 'skip-syntax-forward
6977 'skip-syntax-backward)
6978 ".")))))
6979 (point)))))
6980 arg 'special))
6982 (defun transpose-lines (arg)
6983 "Exchange current line and previous line, leaving point after both.
6984 With argument ARG, takes previous line and moves it past ARG lines.
6985 With argument 0, interchanges line point is in with line mark is in."
6986 (interactive "*p")
6987 (transpose-subr (function
6988 (lambda (arg)
6989 (if (> arg 0)
6990 (progn
6991 ;; Move forward over ARG lines,
6992 ;; but create newlines if necessary.
6993 (setq arg (forward-line arg))
6994 (if (/= (preceding-char) ?\n)
6995 (setq arg (1+ arg)))
6996 (if (> arg 0)
6997 (newline arg)))
6998 (forward-line arg))))
6999 arg))
7001 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
7002 ;; which seems inconsistent with the ARG /= 0 case.
7003 ;; FIXME document SPECIAL.
7004 (defun transpose-subr (mover arg &optional special)
7005 "Subroutine to do the work of transposing objects.
7006 Works for lines, sentences, paragraphs, etc. MOVER is a function that
7007 moves forward by units of the given object (e.g. forward-sentence,
7008 forward-paragraph). If ARG is zero, exchanges the current object
7009 with the one containing mark. If ARG is an integer, moves the
7010 current object past ARG following (if ARG is positive) or
7011 preceding (if ARG is negative) objects, leaving point after the
7012 current object."
7013 (let ((aux (if special mover
7014 (lambda (x)
7015 (cons (progn (funcall mover x) (point))
7016 (progn (funcall mover (- x)) (point))))))
7017 pos1 pos2)
7018 (cond
7019 ((= arg 0)
7020 (save-excursion
7021 (setq pos1 (funcall aux 1))
7022 (goto-char (or (mark) (error "No mark set in this buffer")))
7023 (setq pos2 (funcall aux 1))
7024 (transpose-subr-1 pos1 pos2))
7025 (exchange-point-and-mark))
7026 ((> arg 0)
7027 (setq pos1 (funcall aux -1))
7028 (setq pos2 (funcall aux arg))
7029 (transpose-subr-1 pos1 pos2)
7030 (goto-char (car pos2)))
7032 (setq pos1 (funcall aux -1))
7033 (goto-char (car pos1))
7034 (setq pos2 (funcall aux arg))
7035 (transpose-subr-1 pos1 pos2)
7036 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
7038 (defun transpose-subr-1 (pos1 pos2)
7039 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
7040 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
7041 (when (> (car pos1) (car pos2))
7042 (let ((swap pos1))
7043 (setq pos1 pos2 pos2 swap)))
7044 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
7045 (atomic-change-group
7046 ;; This sequence of insertions attempts to preserve marker
7047 ;; positions at the start and end of the transposed objects.
7048 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
7049 (len1 (- (cdr pos1) (car pos1)))
7050 (len2 (length word))
7051 (boundary (make-marker)))
7052 (set-marker boundary (car pos2))
7053 (goto-char (cdr pos1))
7054 (insert-before-markers word)
7055 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
7056 (goto-char boundary)
7057 (insert word)
7058 (goto-char (+ boundary len1))
7059 (delete-region (point) (+ (point) len2))
7060 (set-marker boundary nil))))
7062 (defun backward-word (&optional arg)
7063 "Move backward until encountering the beginning of a word.
7064 With argument ARG, do this that many times.
7065 If ARG is omitted or nil, move point backward one word.
7067 The word boundaries are normally determined by the buffer's
7068 syntax table and character script (according to
7069 `char-script-table'), but `find-word-boundary-function-table',
7070 such as set up by `subword-mode', can change that. If a Lisp
7071 program needs to move by words determined strictly by the syntax
7072 table, it should use `backward-word-strictly' instead. See Info
7073 node `(elisp) Word Motion' for details."
7074 (interactive "^p")
7075 (forward-word (- (or arg 1))))
7077 (defun mark-word (&optional arg allow-extend)
7078 "Set mark ARG words away from point.
7079 The place mark goes is the same place \\[forward-word] would
7080 move to with the same argument.
7081 Interactively, if this command is repeated
7082 or (in Transient Mark mode) if the mark is active,
7083 it marks the next ARG words after the ones already marked."
7084 (interactive "P\np")
7085 (cond ((and allow-extend
7086 (or (and (eq last-command this-command) (mark t))
7087 (region-active-p)))
7088 (setq arg (if arg (prefix-numeric-value arg)
7089 (if (< (mark) (point)) -1 1)))
7090 (set-mark
7091 (save-excursion
7092 (goto-char (mark))
7093 (forward-word arg)
7094 (point))))
7096 (push-mark
7097 (save-excursion
7098 (forward-word (prefix-numeric-value arg))
7099 (point))
7100 nil t))))
7102 (defun kill-word (arg)
7103 "Kill characters forward until encountering the end of a word.
7104 With argument ARG, do this that many times."
7105 (interactive "p")
7106 (kill-region (point) (progn (forward-word arg) (point))))
7108 (defun backward-kill-word (arg)
7109 "Kill characters backward until encountering the beginning of a word.
7110 With argument ARG, do this that many times."
7111 (interactive "p")
7112 (kill-word (- arg)))
7114 (defun current-word (&optional strict really-word)
7115 "Return the word at or near point, as a string.
7116 The return value includes no text properties.
7118 If optional arg STRICT is non-nil, return nil unless point is
7119 within or adjacent to a word, otherwise look for a word within
7120 point's line. If there is no word anywhere on point's line, the
7121 value is nil regardless of STRICT.
7123 By default, this function treats as a single word any sequence of
7124 characters that have either word or symbol syntax. If optional
7125 arg REALLY-WORD is non-nil, only characters of word syntax can
7126 constitute a word."
7127 (save-excursion
7128 (let* ((oldpoint (point)) (start (point)) (end (point))
7129 (syntaxes (if really-word "w" "w_"))
7130 (not-syntaxes (concat "^" syntaxes)))
7131 (skip-syntax-backward syntaxes) (setq start (point))
7132 (goto-char oldpoint)
7133 (skip-syntax-forward syntaxes) (setq end (point))
7134 (when (and (eq start oldpoint) (eq end oldpoint)
7135 ;; Point is neither within nor adjacent to a word.
7136 (not strict))
7137 ;; Look for preceding word in same line.
7138 (skip-syntax-backward not-syntaxes (line-beginning-position))
7139 (if (bolp)
7140 ;; No preceding word in same line.
7141 ;; Look for following word in same line.
7142 (progn
7143 (skip-syntax-forward not-syntaxes (line-end-position))
7144 (setq start (point))
7145 (skip-syntax-forward syntaxes)
7146 (setq end (point)))
7147 (setq end (point))
7148 (skip-syntax-backward syntaxes)
7149 (setq start (point))))
7150 ;; If we found something nonempty, return it as a string.
7151 (unless (= start end)
7152 (buffer-substring-no-properties start end)))))
7154 (defcustom fill-prefix nil
7155 "String for filling to insert at front of new line, or nil for none."
7156 :type '(choice (const :tag "None" nil)
7157 string)
7158 :group 'fill)
7159 (make-variable-buffer-local 'fill-prefix)
7160 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7162 (defcustom auto-fill-inhibit-regexp nil
7163 "Regexp to match lines which should not be auto-filled."
7164 :type '(choice (const :tag "None" nil)
7165 regexp)
7166 :group 'fill)
7168 (defun do-auto-fill ()
7169 "The default value for `normal-auto-fill-function'.
7170 This is the default auto-fill function, some major modes use a different one.
7171 Returns t if it really did any work."
7172 (let (fc justify give-up
7173 (fill-prefix fill-prefix))
7174 (if (or (not (setq justify (current-justification)))
7175 (null (setq fc (current-fill-column)))
7176 (and (eq justify 'left)
7177 (<= (current-column) fc))
7178 (and auto-fill-inhibit-regexp
7179 (save-excursion (beginning-of-line)
7180 (looking-at auto-fill-inhibit-regexp))))
7181 nil ;; Auto-filling not required
7182 (if (memq justify '(full center right))
7183 (save-excursion (unjustify-current-line)))
7185 ;; Choose a fill-prefix automatically.
7186 (when (and adaptive-fill-mode
7187 (or (null fill-prefix) (string= fill-prefix "")))
7188 (let ((prefix
7189 (fill-context-prefix
7190 (save-excursion (fill-forward-paragraph -1) (point))
7191 (save-excursion (fill-forward-paragraph 1) (point)))))
7192 (and prefix (not (equal prefix ""))
7193 ;; Use auto-indentation rather than a guessed empty prefix.
7194 (not (and fill-indent-according-to-mode
7195 (string-match "\\`[ \t]*\\'" prefix)))
7196 (setq fill-prefix prefix))))
7198 (while (and (not give-up) (> (current-column) fc))
7199 ;; Determine where to split the line.
7200 (let ((fill-point
7201 (save-excursion
7202 (beginning-of-line)
7203 ;; Don't split earlier in the line than the length of the
7204 ;; fill prefix, since the resulting line would be longer.
7205 (when fill-prefix
7206 (move-to-column (string-width fill-prefix)))
7207 (let ((after-prefix (point)))
7208 (move-to-column (1+ fc))
7209 (fill-move-to-break-point after-prefix)
7210 (point)))))
7212 ;; See whether the place we found is any good.
7213 (if (save-excursion
7214 (goto-char fill-point)
7215 (or (bolp)
7216 ;; There is no use breaking at end of line.
7217 (save-excursion (skip-chars-forward " ") (eolp))
7218 ;; Don't split right after a comment starter
7219 ;; since we would just make another comment starter.
7220 (and comment-start-skip
7221 (let ((limit (point)))
7222 (beginning-of-line)
7223 (and (re-search-forward comment-start-skip
7224 limit t)
7225 (eq (point) limit))))))
7226 ;; No good place to break => stop trying.
7227 (setq give-up t)
7228 ;; Ok, we have a useful place to break the line. Do it.
7229 (let ((prev-column (current-column)))
7230 ;; If point is at the fill-point, do not `save-excursion'.
7231 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7232 ;; point will end up before it rather than after it.
7233 (if (save-excursion
7234 (skip-chars-backward " \t")
7235 (= (point) fill-point))
7236 (default-indent-new-line t)
7237 (save-excursion
7238 (goto-char fill-point)
7239 (default-indent-new-line t)))
7240 ;; Now do justification, if required
7241 (if (not (eq justify 'left))
7242 (save-excursion
7243 (end-of-line 0)
7244 (justify-current-line justify nil t)))
7245 ;; If making the new line didn't reduce the hpos of
7246 ;; the end of the line, then give up now;
7247 ;; trying again will not help.
7248 (if (>= (current-column) prev-column)
7249 (setq give-up t))))))
7250 ;; Justify last line.
7251 (justify-current-line justify t t)
7252 t)))
7254 (defvar comment-line-break-function 'comment-indent-new-line
7255 "Mode-specific function which line breaks and continues a comment.
7256 This function is called during auto-filling when a comment syntax
7257 is defined.
7258 The function should take a single optional argument, which is a flag
7259 indicating whether it should use soft newlines.")
7261 (defun default-indent-new-line (&optional soft)
7262 "Break line at point and indent.
7263 If a comment syntax is defined, call `comment-indent-new-line'.
7265 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7266 unless optional argument SOFT is non-nil."
7267 (interactive)
7268 (if comment-start
7269 (funcall comment-line-break-function soft)
7270 ;; Insert the newline before removing empty space so that markers
7271 ;; get preserved better.
7272 (if soft (insert-and-inherit ?\n) (newline 1))
7273 (save-excursion (forward-char -1) (delete-horizontal-space))
7274 (delete-horizontal-space)
7276 (if (and fill-prefix (not adaptive-fill-mode))
7277 ;; Blindly trust a non-adaptive fill-prefix.
7278 (progn
7279 (indent-to-left-margin)
7280 (insert-before-markers-and-inherit fill-prefix))
7282 (cond
7283 ;; If there's an adaptive prefix, use it unless we're inside
7284 ;; a comment and the prefix is not a comment starter.
7285 (fill-prefix
7286 (indent-to-left-margin)
7287 (insert-and-inherit fill-prefix))
7288 ;; If we're not inside a comment, just try to indent.
7289 (t (indent-according-to-mode))))))
7291 (defun internal-auto-fill ()
7292 "The function called by `self-insert-command' to perform auto-filling."
7293 (when (or (not comment-start)
7294 (not comment-auto-fill-only-comments)
7295 (nth 4 (syntax-ppss)))
7296 (funcall auto-fill-function)))
7298 (defvar normal-auto-fill-function 'do-auto-fill
7299 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7300 Some major modes set this.")
7302 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7303 ;; `functions' and `hooks' are usually unsafe to set, but setting
7304 ;; auto-fill-function to nil in a file-local setting is safe and
7305 ;; can be useful to prevent auto-filling.
7306 (put 'auto-fill-function 'safe-local-variable 'null)
7308 (define-minor-mode auto-fill-mode
7309 "Toggle automatic line breaking (Auto Fill mode).
7310 Interactively, with a prefix argument, enable
7311 Auto Fill mode if the prefix argument is positive,
7312 and disable it otherwise. If called from Lisp, toggle
7313 the mode if ARG is `toggle', disable the mode if ARG is
7314 a non-positive integer, and enable the mode otherwise
7315 \(including if ARG is omitted or nil or a positive integer).
7317 When Auto Fill mode is enabled, inserting a space at a column
7318 beyond `current-fill-column' automatically breaks the line at a
7319 previous space.
7321 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7322 non-nil.
7324 The value of `normal-auto-fill-function' specifies the function to use
7325 for `auto-fill-function' when turning Auto Fill mode on."
7326 :variable (auto-fill-function
7327 . (lambda (v) (setq auto-fill-function
7328 (if v normal-auto-fill-function)))))
7330 ;; This holds a document string used to document auto-fill-mode.
7331 (defun auto-fill-function ()
7332 "Automatically break line at a previous space, in insertion of text."
7333 nil)
7335 (defun turn-on-auto-fill ()
7336 "Unconditionally turn on Auto Fill mode."
7337 (auto-fill-mode 1))
7339 (defun turn-off-auto-fill ()
7340 "Unconditionally turn off Auto Fill mode."
7341 (auto-fill-mode -1))
7343 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7345 (defun set-fill-column (arg)
7346 "Set `fill-column' to specified argument.
7347 Use \\[universal-argument] followed by a number to specify a column.
7348 Just \\[universal-argument] as argument means to use the current column."
7349 (interactive
7350 (list (or current-prefix-arg
7351 ;; We used to use current-column silently, but C-x f is too easily
7352 ;; typed as a typo for C-x C-f, so we turned it into an error and
7353 ;; now an interactive prompt.
7354 (read-number "Set fill-column to: " (current-column)))))
7355 (if (consp arg)
7356 (setq arg (current-column)))
7357 (if (not (integerp arg))
7358 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7359 (error "set-fill-column requires an explicit argument")
7360 (message "Fill column set to %d (was %d)" arg fill-column)
7361 (setq fill-column arg)))
7363 (defun set-selective-display (arg)
7364 "Set `selective-display' to ARG; clear it if no arg.
7365 When the value of `selective-display' is a number > 0,
7366 lines whose indentation is >= that value are not displayed.
7367 The variable `selective-display' has a separate value for each buffer."
7368 (interactive "P")
7369 (if (eq selective-display t)
7370 (error "selective-display already in use for marked lines"))
7371 (let ((current-vpos
7372 (save-restriction
7373 (narrow-to-region (point-min) (point))
7374 (goto-char (window-start))
7375 (vertical-motion (window-height)))))
7376 (setq selective-display
7377 (and arg (prefix-numeric-value arg)))
7378 (recenter current-vpos))
7379 (set-window-start (selected-window) (window-start))
7380 (princ "selective-display set to " t)
7381 (prin1 selective-display t)
7382 (princ "." t))
7384 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7386 (defun toggle-truncate-lines (&optional arg)
7387 "Toggle truncating of long lines for the current buffer.
7388 When truncating is off, long lines are folded.
7389 With prefix argument ARG, truncate long lines if ARG is positive,
7390 otherwise fold them. Note that in side-by-side windows, this
7391 command has no effect if `truncate-partial-width-windows' is
7392 non-nil."
7393 (interactive "P")
7394 (setq truncate-lines
7395 (if (null arg)
7396 (not truncate-lines)
7397 (> (prefix-numeric-value arg) 0)))
7398 (force-mode-line-update)
7399 (unless truncate-lines
7400 (let ((buffer (current-buffer)))
7401 (walk-windows (lambda (window)
7402 (if (eq buffer (window-buffer window))
7403 (set-window-hscroll window 0)))
7404 nil t)))
7405 (message "Truncate long lines %s"
7406 (if truncate-lines "enabled" "disabled")))
7408 (defun toggle-word-wrap (&optional arg)
7409 "Toggle whether to use word-wrapping for continuation lines.
7410 With prefix argument ARG, wrap continuation lines at word boundaries
7411 if ARG is positive, otherwise wrap them at the right screen edge.
7412 This command toggles the value of `word-wrap'. It has no effect
7413 if long lines are truncated."
7414 (interactive "P")
7415 (setq word-wrap
7416 (if (null arg)
7417 (not word-wrap)
7418 (> (prefix-numeric-value arg) 0)))
7419 (force-mode-line-update)
7420 (message "Word wrapping %s"
7421 (if word-wrap "enabled" "disabled")))
7423 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7424 "The string displayed in the mode line when in overwrite mode.")
7425 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7426 "The string displayed in the mode line when in binary overwrite mode.")
7428 (define-minor-mode overwrite-mode
7429 "Toggle Overwrite mode.
7430 With a prefix argument ARG, enable Overwrite mode if ARG is
7431 positive, and disable it otherwise. If called from Lisp, enable
7432 the mode if ARG is omitted or nil.
7434 When Overwrite mode is enabled, printing characters typed in
7435 replace existing text on a one-for-one basis, rather than pushing
7436 it to the right. At the end of a line, such characters extend
7437 the line. Before a tab, such characters insert until the tab is
7438 filled in. \\[quoted-insert] still inserts characters in
7439 overwrite mode; this is supposed to make it easier to insert
7440 characters when necessary."
7441 :variable (overwrite-mode
7442 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7444 (define-minor-mode binary-overwrite-mode
7445 "Toggle Binary Overwrite mode.
7446 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7447 is positive, and disable it otherwise. If called from Lisp,
7448 enable the mode if ARG is omitted or nil.
7450 When Binary Overwrite mode is enabled, printing characters typed
7451 in replace existing text. Newlines are not treated specially, so
7452 typing at the end of a line joins the line to the next, with the
7453 typed character between them. Typing before a tab character
7454 simply replaces the tab with the character typed.
7455 \\[quoted-insert] replaces the text at the cursor, just as
7456 ordinary typing characters do.
7458 Note that Binary Overwrite mode is not its own minor mode; it is
7459 a specialization of overwrite mode, entered by setting the
7460 `overwrite-mode' variable to `overwrite-mode-binary'."
7461 :variable (overwrite-mode
7462 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7464 (define-minor-mode line-number-mode
7465 "Toggle line number display in the mode line (Line Number mode).
7466 With a prefix argument ARG, enable Line Number mode if ARG is
7467 positive, and disable it otherwise. If called from Lisp, enable
7468 the mode if ARG is omitted or nil.
7470 Line numbers do not appear for very large buffers and buffers
7471 with very long lines; see variables `line-number-display-limit'
7472 and `line-number-display-limit-width'."
7473 :init-value t :global t :group 'mode-line)
7475 (define-minor-mode column-number-mode
7476 "Toggle column number display in the mode line (Column Number mode).
7477 With a prefix argument ARG, enable Column Number mode if ARG is
7478 positive, and disable it otherwise.
7480 If called from Lisp, enable the mode if ARG is omitted or nil."
7481 :global t :group 'mode-line)
7483 (define-minor-mode size-indication-mode
7484 "Toggle buffer size display in the mode line (Size Indication mode).
7485 With a prefix argument ARG, enable Size Indication mode if ARG is
7486 positive, and disable it otherwise.
7488 If called from Lisp, enable the mode if ARG is omitted or nil."
7489 :global t :group 'mode-line)
7491 (define-minor-mode auto-save-mode
7492 "Toggle auto-saving in the current buffer (Auto Save mode).
7493 With a prefix argument ARG, enable Auto Save mode if ARG is
7494 positive, and disable it otherwise.
7496 If called from Lisp, enable the mode if ARG is omitted or nil."
7497 :variable ((and buffer-auto-save-file-name
7498 ;; If auto-save is off because buffer has shrunk,
7499 ;; then toggling should turn it on.
7500 (>= buffer-saved-size 0))
7501 . (lambda (val)
7502 (setq buffer-auto-save-file-name
7503 (cond
7504 ((null val) nil)
7505 ((and buffer-file-name auto-save-visited-file-name
7506 (not buffer-read-only))
7507 buffer-file-name)
7508 (t (make-auto-save-file-name))))))
7509 ;; If -1 was stored here, to temporarily turn off saving,
7510 ;; turn it back on.
7511 (and (< buffer-saved-size 0)
7512 (setq buffer-saved-size 0)))
7514 (defgroup paren-blinking nil
7515 "Blinking matching of parens and expressions."
7516 :prefix "blink-matching-"
7517 :group 'paren-matching)
7519 (defcustom blink-matching-paren t
7520 "Non-nil means show matching open-paren when close-paren is inserted.
7521 If t, highlight the paren. If `jump', briefly move cursor to its
7522 position. If `jump-offscreen', move cursor there even if the
7523 position is off screen. With any other non-nil value, the
7524 off-screen position of the opening paren will be shown in the
7525 echo area."
7526 :type '(choice
7527 (const :tag "Disable" nil)
7528 (const :tag "Highlight" t)
7529 (const :tag "Move cursor" jump)
7530 (const :tag "Move cursor, even if off screen" jump-offscreen))
7531 :group 'paren-blinking)
7533 (defcustom blink-matching-paren-on-screen t
7534 "Non-nil means show matching open-paren when it is on screen.
7535 If nil, don't show it (but the open-paren can still be shown
7536 in the echo area when it is off screen).
7538 This variable has no effect if `blink-matching-paren' is nil.
7539 \(In that case, the open-paren is never shown.)
7540 It is also ignored if `show-paren-mode' is enabled."
7541 :type 'boolean
7542 :group 'paren-blinking)
7544 (defcustom blink-matching-paren-distance (* 100 1024)
7545 "If non-nil, maximum distance to search backwards for matching open-paren.
7546 If nil, search stops at the beginning of the accessible portion of the buffer."
7547 :version "23.2" ; 25->100k
7548 :type '(choice (const nil) integer)
7549 :group 'paren-blinking)
7551 (defcustom blink-matching-delay 1
7552 "Time in seconds to delay after showing a matching paren."
7553 :type 'number
7554 :group 'paren-blinking)
7556 (defcustom blink-matching-paren-dont-ignore-comments nil
7557 "If nil, `blink-matching-paren' ignores comments.
7558 More precisely, when looking for the matching parenthesis,
7559 it skips the contents of comments that end before point."
7560 :type 'boolean
7561 :group 'paren-blinking)
7563 (defun blink-matching-check-mismatch (start end)
7564 "Return whether or not START...END are matching parens.
7565 END is the current point and START is the blink position.
7566 START might be nil if no matching starter was found.
7567 Returns non-nil if we find there is a mismatch."
7568 (let* ((end-syntax (syntax-after (1- end)))
7569 (matching-paren (and (consp end-syntax)
7570 (eq (syntax-class end-syntax) 5)
7571 (cdr end-syntax))))
7572 ;; For self-matched chars like " and $, we can't know when they're
7573 ;; mismatched or unmatched, so we can only do it for parens.
7574 (when matching-paren
7575 (not (and start
7577 (eq (char-after start) matching-paren)
7578 ;; The cdr might hold a new paren-class info rather than
7579 ;; a matching-char info, in which case the two CDRs
7580 ;; should match.
7581 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7583 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7584 "Function to check parentheses mismatches.
7585 The function takes two arguments (START and END) where START is the
7586 position just before the opening token and END is the position right after.
7587 START can be nil, if it was not found.
7588 The function should return non-nil if the two tokens do not match.")
7590 (defvar blink-matching--overlay
7591 (let ((ol (make-overlay (point) (point) nil t)))
7592 (overlay-put ol 'face 'show-paren-match)
7593 (delete-overlay ol)
7595 "Overlay used to highlight the matching paren.")
7597 (defun blink-matching-open ()
7598 "Momentarily highlight the beginning of the sexp before point."
7599 (interactive)
7600 (when (and (not (bobp))
7601 blink-matching-paren)
7602 (let* ((oldpos (point))
7603 (message-log-max nil) ; Don't log messages about paren matching.
7604 (blinkpos
7605 (save-excursion
7606 (save-restriction
7607 (if blink-matching-paren-distance
7608 (narrow-to-region
7609 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7610 (- (point) blink-matching-paren-distance))
7611 oldpos))
7612 (let ((parse-sexp-ignore-comments
7613 (and parse-sexp-ignore-comments
7614 (not blink-matching-paren-dont-ignore-comments))))
7615 (condition-case ()
7616 (progn
7617 (syntax-propertize (point))
7618 (forward-sexp -1)
7619 ;; backward-sexp skips backward over prefix chars,
7620 ;; so move back to the matching paren.
7621 (while (and (< (point) (1- oldpos))
7622 (let ((code (syntax-after (point))))
7623 (or (eq (syntax-class code) 6)
7624 (eq (logand 1048576 (car code))
7625 1048576))))
7626 (forward-char 1))
7627 (point))
7628 (error nil))))))
7629 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7630 (cond
7631 (mismatch
7632 (if blinkpos
7633 (if (minibufferp)
7634 (minibuffer-message "Mismatched parentheses")
7635 (message "Mismatched parentheses"))
7636 (if (minibufferp)
7637 (minibuffer-message "No matching parenthesis found")
7638 (message "No matching parenthesis found"))))
7639 ((not blinkpos) nil)
7640 ((or
7641 (eq blink-matching-paren 'jump-offscreen)
7642 (pos-visible-in-window-p blinkpos))
7643 ;; Matching open within window, temporarily move to or highlight
7644 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7645 ;; is non-nil.
7646 (and blink-matching-paren-on-screen
7647 (not show-paren-mode)
7648 (if (memq blink-matching-paren '(jump jump-offscreen))
7649 (save-excursion
7650 (goto-char blinkpos)
7651 (sit-for blink-matching-delay))
7652 (unwind-protect
7653 (progn
7654 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7655 (current-buffer))
7656 (sit-for blink-matching-delay))
7657 (delete-overlay blink-matching--overlay)))))
7659 (let ((open-paren-line-string
7660 (save-excursion
7661 (goto-char blinkpos)
7662 ;; Show what precedes the open in its line, if anything.
7663 (cond
7664 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7665 (buffer-substring (line-beginning-position)
7666 (1+ blinkpos)))
7667 ;; Show what follows the open in its line, if anything.
7668 ((save-excursion
7669 (forward-char 1)
7670 (skip-chars-forward " \t")
7671 (not (eolp)))
7672 (buffer-substring blinkpos
7673 (line-end-position)))
7674 ;; Otherwise show the previous nonblank line,
7675 ;; if there is one.
7676 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7677 (concat
7678 (buffer-substring (progn
7679 (skip-chars-backward "\n \t")
7680 (line-beginning-position))
7681 (progn (end-of-line)
7682 (skip-chars-backward " \t")
7683 (point)))
7684 ;; Replace the newline and other whitespace with `...'.
7685 "..."
7686 (buffer-substring blinkpos (1+ blinkpos))))
7687 ;; There is nothing to show except the char itself.
7688 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7689 (minibuffer-message
7690 "Matches %s"
7691 (substring-no-properties open-paren-line-string))))))))
7693 (defvar blink-paren-function 'blink-matching-open
7694 "Function called, if non-nil, whenever a close parenthesis is inserted.
7695 More precisely, a char with closeparen syntax is self-inserted.")
7697 (defun blink-paren-post-self-insert-function ()
7698 (when (and (eq (char-before) last-command-event) ; Sanity check.
7699 (memq (char-syntax last-command-event) '(?\) ?\$))
7700 blink-paren-function
7701 (not executing-kbd-macro)
7702 (not noninteractive)
7703 ;; Verify an even number of quoting characters precede the close.
7704 ;; FIXME: Also check if this parenthesis closes a comment as
7705 ;; can happen in Pascal and SML.
7706 (= 1 (logand 1 (- (point)
7707 (save-excursion
7708 (forward-char -1)
7709 (skip-syntax-backward "/\\")
7710 (point))))))
7711 (funcall blink-paren-function)))
7713 (put 'blink-paren-post-self-insert-function 'priority 100)
7715 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7716 ;; Most likely, this hook is nil, so this arg doesn't matter,
7717 ;; but I use it as a reminder that this function usually
7718 ;; likes to be run after others since it does
7719 ;; `sit-for'. That's also the reason it get a `priority' prop
7720 ;; of 100.
7721 'append)
7723 ;; This executes C-g typed while Emacs is waiting for a command.
7724 ;; Quitting out of a program does not go through here;
7725 ;; that happens in the maybe_quit function at the C code level.
7726 (defun keyboard-quit ()
7727 "Signal a `quit' condition.
7728 During execution of Lisp code, this character causes a quit directly.
7729 At top-level, as an editor command, this simply beeps."
7730 (interactive)
7731 ;; Avoid adding the region to the window selection.
7732 (setq saved-region-selection nil)
7733 (let (select-active-regions)
7734 (deactivate-mark))
7735 (if (fboundp 'kmacro-keyboard-quit)
7736 (kmacro-keyboard-quit))
7737 (when completion-in-region-mode
7738 (completion-in-region-mode -1))
7739 ;; Force the next redisplay cycle to remove the "Def" indicator from
7740 ;; all the mode lines.
7741 (if defining-kbd-macro
7742 (force-mode-line-update t))
7743 (setq defining-kbd-macro nil)
7744 (let ((debug-on-quit nil))
7745 (signal 'quit nil)))
7747 (defvar buffer-quit-function nil
7748 "Function to call to \"quit\" the current buffer, or nil if none.
7749 \\[keyboard-escape-quit] calls this function when its more local actions
7750 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7752 (defun keyboard-escape-quit ()
7753 "Exit the current \"mode\" (in a generalized sense of the word).
7754 This command can exit an interactive command such as `query-replace',
7755 can clear out a prefix argument or a region,
7756 can get out of the minibuffer or other recursive edit,
7757 cancel the use of the current buffer (for special-purpose buffers),
7758 or go back to just one window (by deleting all but the selected window)."
7759 (interactive)
7760 (cond ((eq last-command 'mode-exited) nil)
7761 ((region-active-p)
7762 (deactivate-mark))
7763 ((> (minibuffer-depth) 0)
7764 (abort-recursive-edit))
7765 (current-prefix-arg
7766 nil)
7767 ((> (recursion-depth) 0)
7768 (exit-recursive-edit))
7769 (buffer-quit-function
7770 (funcall buffer-quit-function))
7771 ((not (one-window-p t))
7772 (delete-other-windows))
7773 ((string-match "^ \\*" (buffer-name (current-buffer)))
7774 (bury-buffer))))
7776 (defun play-sound-file (file &optional volume device)
7777 "Play sound stored in FILE.
7778 VOLUME and DEVICE correspond to the keywords of the sound
7779 specification for `play-sound'."
7780 (interactive "fPlay sound file: ")
7781 (let ((sound (list :file file)))
7782 (if volume
7783 (plist-put sound :volume volume))
7784 (if device
7785 (plist-put sound :device device))
7786 (push 'sound sound)
7787 (play-sound sound)))
7790 (defcustom read-mail-command 'rmail
7791 "Your preference for a mail reading package.
7792 This is used by some keybindings which support reading mail.
7793 See also `mail-user-agent' concerning sending mail."
7794 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7795 (function-item :tag "Gnus" :format "%t\n" gnus)
7796 (function-item :tag "Emacs interface to MH"
7797 :format "%t\n" mh-rmail)
7798 (function :tag "Other"))
7799 :version "21.1"
7800 :group 'mail)
7802 (defcustom mail-user-agent 'message-user-agent
7803 "Your preference for a mail composition package.
7804 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7805 outgoing email message. This variable lets you specify which
7806 mail-sending package you prefer.
7808 Valid values include:
7810 `message-user-agent' -- use the Message package.
7811 See Info node `(message)'.
7812 `sendmail-user-agent' -- use the Mail package.
7813 See Info node `(emacs)Sending Mail'.
7814 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7815 See Info node `(mh-e)'.
7816 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7817 paraphernalia if Gnus is running, particularly
7818 the Gcc: header for archiving.
7820 Additional valid symbols may be available; check with the author of
7821 your package for details. The function should return non-nil if it
7822 succeeds.
7824 See also `read-mail-command' concerning reading mail."
7825 :type '(radio (function-item :tag "Message package"
7826 :format "%t\n"
7827 message-user-agent)
7828 (function-item :tag "Mail package"
7829 :format "%t\n"
7830 sendmail-user-agent)
7831 (function-item :tag "Emacs interface to MH"
7832 :format "%t\n"
7833 mh-e-user-agent)
7834 (function-item :tag "Message with full Gnus features"
7835 :format "%t\n"
7836 gnus-user-agent)
7837 (function :tag "Other"))
7838 :version "23.2" ; sendmail->message
7839 :group 'mail)
7841 (defcustom compose-mail-user-agent-warnings t
7842 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7843 If the value of `mail-user-agent' is the default, and the user
7844 appears to have customizations applying to the old default,
7845 `compose-mail' issues a warning."
7846 :type 'boolean
7847 :version "23.2"
7848 :group 'mail)
7850 (defun rfc822-goto-eoh ()
7851 "If the buffer starts with a mail header, move point to the header's end.
7852 Otherwise, moves to `point-min'.
7853 The end of the header is the start of the next line, if there is one,
7854 else the end of the last line. This function obeys RFC822."
7855 (goto-char (point-min))
7856 (when (re-search-forward
7857 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7858 (goto-char (match-beginning 0))))
7860 ;; Used by Rmail (e.g., rmail-forward).
7861 (defvar mail-encode-mml nil
7862 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7863 the outgoing message before sending it.")
7865 (defun compose-mail (&optional to subject other-headers continue
7866 switch-function yank-action send-actions
7867 return-action)
7868 "Start composing a mail message to send.
7869 This uses the user's chosen mail composition package
7870 as selected with the variable `mail-user-agent'.
7871 The optional arguments TO and SUBJECT specify recipients
7872 and the initial Subject field, respectively.
7874 OTHER-HEADERS is an alist specifying additional
7875 header fields. Elements look like (HEADER . VALUE) where both
7876 HEADER and VALUE are strings.
7878 CONTINUE, if non-nil, says to continue editing a message already
7879 being composed. Interactively, CONTINUE is the prefix argument.
7881 SWITCH-FUNCTION, if non-nil, is a function to use to
7882 switch to and display the buffer used for mail composition.
7884 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7885 to insert the raw text of the message being replied to.
7886 It has the form (FUNCTION . ARGS). The user agent will apply
7887 FUNCTION to ARGS, to insert the raw text of the original message.
7888 \(The user agent will also run `mail-citation-hook', *after* the
7889 original text has been inserted in this way.)
7891 SEND-ACTIONS is a list of actions to call when the message is sent.
7892 Each action has the form (FUNCTION . ARGS).
7894 RETURN-ACTION, if non-nil, is an action for returning to the
7895 caller. It has the form (FUNCTION . ARGS). The function is
7896 called after the mail has been sent or put aside, and the mail
7897 buffer buried."
7898 (interactive
7899 (list nil nil nil current-prefix-arg))
7901 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7902 ;; from sendmail-user-agent to message-user-agent. Some users may
7903 ;; encounter incompatibilities. This hack tries to detect problems
7904 ;; and warn about them.
7905 (and compose-mail-user-agent-warnings
7906 (eq mail-user-agent 'message-user-agent)
7907 (let (warn-vars)
7908 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7909 mail-citation-hook mail-archive-file-name
7910 mail-default-reply-to mail-mailing-lists
7911 mail-self-blind))
7912 (and (boundp var)
7913 (symbol-value var)
7914 (push var warn-vars)))
7915 (when warn-vars
7916 (display-warning 'mail
7917 (format-message "\
7918 The default mail mode is now Message mode.
7919 You have the following Mail mode variable%s customized:
7920 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7921 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7922 (if (> (length warn-vars) 1) "s" "")
7923 (mapconcat 'symbol-name
7924 warn-vars " "))))))
7926 (let ((function (get mail-user-agent 'composefunc)))
7927 (unless function
7928 (error "Invalid value for `mail-user-agent'"))
7929 (funcall function to subject other-headers continue switch-function
7930 yank-action send-actions return-action)))
7932 (defun compose-mail-other-window (&optional to subject other-headers continue
7933 yank-action send-actions
7934 return-action)
7935 "Like \\[compose-mail], but edit the outgoing message in another window."
7936 (interactive (list nil nil nil current-prefix-arg))
7937 (compose-mail to subject other-headers continue
7938 'switch-to-buffer-other-window yank-action send-actions
7939 return-action))
7941 (defun compose-mail-other-frame (&optional to subject other-headers continue
7942 yank-action send-actions
7943 return-action)
7944 "Like \\[compose-mail], but edit the outgoing message in another frame."
7945 (interactive (list nil nil nil current-prefix-arg))
7946 (compose-mail to subject other-headers continue
7947 'switch-to-buffer-other-frame yank-action send-actions
7948 return-action))
7951 (defvar set-variable-value-history nil
7952 "History of values entered with `set-variable'.
7954 Maximum length of the history list is determined by the value
7955 of `history-length', which see.")
7957 (defun set-variable (variable value &optional make-local)
7958 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7959 VARIABLE should be a user option variable name, a Lisp variable
7960 meant to be customized by users. You should enter VALUE in Lisp syntax,
7961 so if you want VALUE to be a string, you must surround it with doublequotes.
7962 VALUE is used literally, not evaluated.
7964 If VARIABLE has a `variable-interactive' property, that is used as if
7965 it were the arg to `interactive' (which see) to interactively read VALUE.
7967 If VARIABLE has been defined with `defcustom', then the type information
7968 in the definition is used to check that VALUE is valid.
7970 Note that this function is at heart equivalent to the basic `set' function.
7971 For a variable defined with `defcustom', it does not pay attention to
7972 any :set property that the variable might have (if you want that, use
7973 \\[customize-set-variable] instead).
7975 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7976 (interactive
7977 (let* ((default-var (variable-at-point))
7978 (var (if (custom-variable-p default-var)
7979 (read-variable (format "Set variable (default %s): " default-var)
7980 default-var)
7981 (read-variable "Set variable: ")))
7982 (minibuffer-help-form '(describe-variable var))
7983 (prop (get var 'variable-interactive))
7984 (obsolete (car (get var 'byte-obsolete-variable)))
7985 (prompt (format "Set %s %s to value: " var
7986 (cond ((local-variable-p var)
7987 "(buffer-local)")
7988 ((or current-prefix-arg
7989 (local-variable-if-set-p var))
7990 "buffer-locally")
7991 (t "globally"))))
7992 (val (progn
7993 (when obsolete
7994 (message (concat "`%S' is obsolete; "
7995 (if (symbolp obsolete) "use `%S' instead" "%s"))
7996 var obsolete)
7997 (sit-for 3))
7998 (if prop
7999 ;; Use VAR's `variable-interactive' property
8000 ;; as an interactive spec for prompting.
8001 (call-interactively `(lambda (arg)
8002 (interactive ,prop)
8003 arg))
8004 (read-from-minibuffer prompt nil
8005 read-expression-map t
8006 'set-variable-value-history
8007 (format "%S" (symbol-value var)))))))
8008 (list var val current-prefix-arg)))
8010 (and (custom-variable-p variable)
8011 (not (get variable 'custom-type))
8012 (custom-load-symbol variable))
8013 (let ((type (get variable 'custom-type)))
8014 (when type
8015 ;; Match with custom type.
8016 (require 'cus-edit)
8017 (setq type (widget-convert type))
8018 (unless (widget-apply type :match value)
8019 (user-error "Value `%S' does not match type %S of %S"
8020 value (car type) variable))))
8022 (if make-local
8023 (make-local-variable variable))
8025 (set variable value)
8027 ;; Force a thorough redisplay for the case that the variable
8028 ;; has an effect on the display, like `tab-width' has.
8029 (force-mode-line-update))
8031 ;; Define the major mode for lists of completions.
8033 (defvar completion-list-mode-map
8034 (let ((map (make-sparse-keymap)))
8035 (define-key map [mouse-2] 'choose-completion)
8036 (define-key map [follow-link] 'mouse-face)
8037 (define-key map [down-mouse-2] nil)
8038 (define-key map "\C-m" 'choose-completion)
8039 (define-key map "\e\e\e" 'delete-completion-window)
8040 (define-key map [left] 'previous-completion)
8041 (define-key map [right] 'next-completion)
8042 (define-key map [?\t] 'next-completion)
8043 (define-key map [backtab] 'previous-completion)
8044 (define-key map "q" 'quit-window)
8045 (define-key map "z" 'kill-current-buffer)
8046 map)
8047 "Local map for completion list buffers.")
8049 ;; Completion mode is suitable only for specially formatted data.
8050 (put 'completion-list-mode 'mode-class 'special)
8052 (defvar completion-reference-buffer nil
8053 "Record the buffer that was current when the completion list was requested.
8054 This is a local variable in the completion list buffer.
8055 Initial value is nil to avoid some compiler warnings.")
8057 (defvar completion-no-auto-exit nil
8058 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8059 This also applies to other functions such as `choose-completion'.")
8061 (defvar completion-base-position nil
8062 "Position of the base of the text corresponding to the shown completions.
8063 This variable is used in the *Completions* buffers.
8064 Its value is a list of the form (START END) where START is the place
8065 where the completion should be inserted and END (if non-nil) is the end
8066 of the text to replace. If END is nil, point is used instead.")
8068 (defvar completion-list-insert-choice-function #'completion--replace
8069 "Function to use to insert the text chosen in *Completions*.
8070 Called with three arguments (BEG END TEXT), it should replace the text
8071 between BEG and END with TEXT. Expected to be set buffer-locally
8072 in the *Completions* buffer.")
8074 (defvar completion-base-size nil
8075 "Number of chars before point not involved in completion.
8076 This is a local variable in the completion list buffer.
8077 It refers to the chars in the minibuffer if completing in the
8078 minibuffer, or in `completion-reference-buffer' otherwise.
8079 Only characters in the field at point are included.
8081 If nil, Emacs determines which part of the tail end of the
8082 buffer's text is involved in completion by comparing the text
8083 directly.")
8084 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8086 (defun delete-completion-window ()
8087 "Delete the completion list window.
8088 Go to the window from which completion was requested."
8089 (interactive)
8090 (let ((buf completion-reference-buffer))
8091 (if (one-window-p t)
8092 (if (window-dedicated-p) (delete-frame))
8093 (delete-window (selected-window))
8094 (if (get-buffer-window buf)
8095 (select-window (get-buffer-window buf))))))
8097 (defun previous-completion (n)
8098 "Move to the previous item in the completion list."
8099 (interactive "p")
8100 (next-completion (- n)))
8102 (defun next-completion (n)
8103 "Move to the next item in the completion list.
8104 With prefix argument N, move N items (negative N means move backward)."
8105 (interactive "p")
8106 (let ((beg (point-min)) (end (point-max)))
8107 (while (and (> n 0) (not (eobp)))
8108 ;; If in a completion, move to the end of it.
8109 (when (get-text-property (point) 'mouse-face)
8110 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8111 ;; Move to start of next one.
8112 (unless (get-text-property (point) 'mouse-face)
8113 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8114 (setq n (1- n)))
8115 (while (and (< n 0) (not (bobp)))
8116 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8117 ;; If in a completion, move to the start of it.
8118 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8119 (goto-char (previous-single-property-change
8120 (point) 'mouse-face nil beg)))
8121 ;; Move to end of the previous completion.
8122 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8123 (goto-char (previous-single-property-change
8124 (point) 'mouse-face nil beg)))
8125 ;; Move to the start of that one.
8126 (goto-char (previous-single-property-change
8127 (point) 'mouse-face nil beg))
8128 (setq n (1+ n))))))
8130 (defun choose-completion (&optional event)
8131 "Choose the completion at point.
8132 If EVENT, use EVENT's position to determine the starting position."
8133 (interactive (list last-nonmenu-event))
8134 ;; In case this is run via the mouse, give temporary modes such as
8135 ;; isearch a chance to turn off.
8136 (run-hooks 'mouse-leave-buffer-hook)
8137 (with-current-buffer (window-buffer (posn-window (event-start event)))
8138 (let ((buffer completion-reference-buffer)
8139 (base-size completion-base-size)
8140 (base-position completion-base-position)
8141 (insert-function completion-list-insert-choice-function)
8142 (choice
8143 (save-excursion
8144 (goto-char (posn-point (event-start event)))
8145 (let (beg end)
8146 (cond
8147 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8148 (setq end (point) beg (1+ (point))))
8149 ((and (not (bobp))
8150 (get-text-property (1- (point)) 'mouse-face))
8151 (setq end (1- (point)) beg (point)))
8152 (t (error "No completion here")))
8153 (setq beg (previous-single-property-change beg 'mouse-face))
8154 (setq end (or (next-single-property-change end 'mouse-face)
8155 (point-max)))
8156 (buffer-substring-no-properties beg end)))))
8158 (unless (buffer-live-p buffer)
8159 (error "Destination buffer is dead"))
8160 (quit-window nil (posn-window (event-start event)))
8162 (with-current-buffer buffer
8163 (choose-completion-string
8164 choice buffer
8165 (or base-position
8166 (when base-size
8167 ;; Someone's using old completion code that doesn't know
8168 ;; about base-position yet.
8169 (list (+ base-size (field-beginning))))
8170 ;; If all else fails, just guess.
8171 (list (choose-completion-guess-base-position choice)))
8172 insert-function)))))
8174 ;; Delete the longest partial match for STRING
8175 ;; that can be found before POINT.
8176 (defun choose-completion-guess-base-position (string)
8177 (save-excursion
8178 (let ((opoint (point))
8179 len)
8180 ;; Try moving back by the length of the string.
8181 (goto-char (max (- (point) (length string))
8182 (minibuffer-prompt-end)))
8183 ;; See how far back we were actually able to move. That is the
8184 ;; upper bound on how much we can match and delete.
8185 (setq len (- opoint (point)))
8186 (if completion-ignore-case
8187 (setq string (downcase string)))
8188 (while (and (> len 0)
8189 (let ((tail (buffer-substring (point) opoint)))
8190 (if completion-ignore-case
8191 (setq tail (downcase tail)))
8192 (not (string= tail (substring string 0 len)))))
8193 (setq len (1- len))
8194 (forward-char 1))
8195 (point))))
8197 (defun choose-completion-delete-max-match (string)
8198 (declare (obsolete choose-completion-guess-base-position "23.2"))
8199 (delete-region (choose-completion-guess-base-position string) (point)))
8201 (defvar choose-completion-string-functions nil
8202 "Functions that may override the normal insertion of a completion choice.
8203 These functions are called in order with three arguments:
8204 CHOICE - the string to insert in the buffer,
8205 BUFFER - the buffer in which the choice should be inserted,
8206 BASE-POSITION - where to insert the completion.
8208 If a function in the list returns non-nil, that function is supposed
8209 to have inserted the CHOICE in the BUFFER, and possibly exited
8210 the minibuffer; no further functions will be called.
8212 If all functions in the list return nil, that means to use
8213 the default method of inserting the completion in BUFFER.")
8215 (defun choose-completion-string (choice &optional
8216 buffer base-position insert-function)
8217 "Switch to BUFFER and insert the completion choice CHOICE.
8218 BASE-POSITION says where to insert the completion.
8219 INSERT-FUNCTION says how to insert the completion and falls
8220 back on `completion-list-insert-choice-function' when nil."
8222 ;; If BUFFER is the minibuffer, exit the minibuffer
8223 ;; unless it is reading a file name and CHOICE is a directory,
8224 ;; or completion-no-auto-exit is non-nil.
8226 ;; Some older code may call us passing `base-size' instead of
8227 ;; `base-position'. It's difficult to make any use of `base-size',
8228 ;; so we just ignore it.
8229 (unless (consp base-position)
8230 (message "Obsolete `base-size' passed to choose-completion-string")
8231 (setq base-position nil))
8233 (let* ((buffer (or buffer completion-reference-buffer))
8234 (mini-p (minibufferp buffer)))
8235 ;; If BUFFER is a minibuffer, barf unless it's the currently
8236 ;; active minibuffer.
8237 (if (and mini-p
8238 (not (and (active-minibuffer-window)
8239 (equal buffer
8240 (window-buffer (active-minibuffer-window))))))
8241 (error "Minibuffer is not active for completion")
8242 ;; Set buffer so buffer-local choose-completion-string-functions works.
8243 (set-buffer buffer)
8244 (unless (run-hook-with-args-until-success
8245 'choose-completion-string-functions
8246 ;; The fourth arg used to be `mini-p' but was useless
8247 ;; (since minibufferp can be used on the `buffer' arg)
8248 ;; and indeed unused. The last used to be `base-size', so we
8249 ;; keep it to try and avoid breaking old code.
8250 choice buffer base-position nil)
8251 ;; This remove-text-properties should be unnecessary since `choice'
8252 ;; comes from buffer-substring-no-properties.
8253 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8254 ;; Insert the completion into the buffer where it was requested.
8255 (funcall (or insert-function completion-list-insert-choice-function)
8256 (or (car base-position) (point))
8257 (or (cadr base-position) (point))
8258 choice)
8259 ;; Update point in the window that BUFFER is showing in.
8260 (let ((window (get-buffer-window buffer t)))
8261 (set-window-point window (point)))
8262 ;; If completing for the minibuffer, exit it with this choice.
8263 (and (not completion-no-auto-exit)
8264 (minibufferp buffer)
8265 minibuffer-completion-table
8266 ;; If this is reading a file name, and the file name chosen
8267 ;; is a directory, don't exit the minibuffer.
8268 (let* ((result (buffer-substring (field-beginning) (point)))
8269 (bounds
8270 (completion-boundaries result minibuffer-completion-table
8271 minibuffer-completion-predicate
8272 "")))
8273 (if (eq (car bounds) (length result))
8274 ;; The completion chosen leads to a new set of completions
8275 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8276 (let ((mini (active-minibuffer-window)))
8277 (select-window mini)
8278 (when minibuffer-auto-raise
8279 (raise-frame (window-frame mini))))
8280 (exit-minibuffer))))))))
8282 (define-derived-mode completion-list-mode nil "Completion List"
8283 "Major mode for buffers showing lists of possible completions.
8284 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8285 to select the completion near point.
8286 Or click to select one with the mouse.
8288 \\{completion-list-mode-map}"
8289 (set (make-local-variable 'completion-base-size) nil))
8291 (defun completion-list-mode-finish ()
8292 "Finish setup of the completions buffer.
8293 Called from `temp-buffer-show-hook'."
8294 (when (eq major-mode 'completion-list-mode)
8295 (setq buffer-read-only t)))
8297 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8300 ;; Variables and faces used in `completion-setup-function'.
8302 (defcustom completion-show-help t
8303 "Non-nil means show help message in *Completions* buffer."
8304 :type 'boolean
8305 :version "22.1"
8306 :group 'completion)
8308 ;; This function goes in completion-setup-hook, so that it is called
8309 ;; after the text of the completion list buffer is written.
8310 (defun completion-setup-function ()
8311 (let* ((mainbuf (current-buffer))
8312 (base-dir
8313 ;; FIXME: This is a bad hack. We try to set the default-directory
8314 ;; in the *Completions* buffer so that the relative file names
8315 ;; displayed there can be treated as valid file names, independently
8316 ;; from the completion context. But this suffers from many problems:
8317 ;; - It's not clear when the completions are file names. With some
8318 ;; completion tables (e.g. bzr revision specs), the listed
8319 ;; completions can mix file names and other things.
8320 ;; - It doesn't pay attention to possible quoting.
8321 ;; - With fancy completion styles, the code below will not always
8322 ;; find the right base directory.
8323 (if minibuffer-completing-file-name
8324 (file-name-as-directory
8325 (expand-file-name
8326 (buffer-substring (minibuffer-prompt-end)
8327 (- (point) (or completion-base-size 0))))))))
8328 (with-current-buffer standard-output
8329 (let ((base-size completion-base-size) ;Read before killing localvars.
8330 (base-position completion-base-position)
8331 (insert-fun completion-list-insert-choice-function))
8332 (completion-list-mode)
8333 (set (make-local-variable 'completion-base-size) base-size)
8334 (set (make-local-variable 'completion-base-position) base-position)
8335 (set (make-local-variable 'completion-list-insert-choice-function)
8336 insert-fun))
8337 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8338 (if base-dir (setq default-directory base-dir))
8339 ;; Maybe insert help string.
8340 (when completion-show-help
8341 (goto-char (point-min))
8342 (if (display-mouse-p)
8343 (insert "Click on a completion to select it.\n"))
8344 (insert (substitute-command-keys
8345 "In this buffer, type \\[choose-completion] to \
8346 select the completion near point.\n\n"))))))
8348 (add-hook 'completion-setup-hook 'completion-setup-function)
8350 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8351 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8353 (defun switch-to-completions ()
8354 "Select the completion list window."
8355 (interactive)
8356 (let ((window (or (get-buffer-window "*Completions*" 0)
8357 ;; Make sure we have a completions window.
8358 (progn (minibuffer-completion-help)
8359 (get-buffer-window "*Completions*" 0)))))
8360 (when window
8361 (select-window window)
8362 ;; In the new buffer, go to the first completion.
8363 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8364 (when (bobp)
8365 (next-completion 1)))))
8367 ;;; Support keyboard commands to turn on various modifiers.
8369 ;; These functions -- which are not commands -- each add one modifier
8370 ;; to the following event.
8372 (defun event-apply-alt-modifier (_ignore-prompt)
8373 "\\<function-key-map>Add the Alt modifier to the following event.
8374 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8375 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8376 (defun event-apply-super-modifier (_ignore-prompt)
8377 "\\<function-key-map>Add the Super modifier to the following event.
8378 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8379 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8380 (defun event-apply-hyper-modifier (_ignore-prompt)
8381 "\\<function-key-map>Add the Hyper modifier to the following event.
8382 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8383 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8384 (defun event-apply-shift-modifier (_ignore-prompt)
8385 "\\<function-key-map>Add the Shift modifier to the following event.
8386 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8387 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8388 (defun event-apply-control-modifier (_ignore-prompt)
8389 "\\<function-key-map>Add the Ctrl modifier to the following event.
8390 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8391 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8392 (defun event-apply-meta-modifier (_ignore-prompt)
8393 "\\<function-key-map>Add the Meta modifier to the following event.
8394 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8395 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8397 (defun event-apply-modifier (event symbol lshiftby prefix)
8398 "Apply a modifier flag to event EVENT.
8399 SYMBOL is the name of this modifier, as a symbol.
8400 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8401 PREFIX is the string that represents this modifier in an event type symbol."
8402 (if (numberp event)
8403 (cond ((eq symbol 'control)
8404 (if (and (<= (downcase event) ?z)
8405 (>= (downcase event) ?a))
8406 (- (downcase event) ?a -1)
8407 (if (and (<= (downcase event) ?Z)
8408 (>= (downcase event) ?A))
8409 (- (downcase event) ?A -1)
8410 (logior (lsh 1 lshiftby) event))))
8411 ((eq symbol 'shift)
8412 (if (and (<= (downcase event) ?z)
8413 (>= (downcase event) ?a))
8414 (upcase event)
8415 (logior (lsh 1 lshiftby) event)))
8417 (logior (lsh 1 lshiftby) event)))
8418 (if (memq symbol (event-modifiers event))
8419 event
8420 (let ((event-type (if (symbolp event) event (car event))))
8421 (setq event-type (intern (concat prefix (symbol-name event-type))))
8422 (if (symbolp event)
8423 event-type
8424 (cons event-type (cdr event)))))))
8426 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8427 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8428 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8429 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8430 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8431 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8433 ;;;; Keypad support.
8435 ;; Make the keypad keys act like ordinary typing keys. If people add
8436 ;; bindings for the function key symbols, then those bindings will
8437 ;; override these, so this shouldn't interfere with any existing
8438 ;; bindings.
8440 ;; Also tell read-char how to handle these keys.
8441 (mapc
8442 (lambda (keypad-normal)
8443 (let ((keypad (nth 0 keypad-normal))
8444 (normal (nth 1 keypad-normal)))
8445 (put keypad 'ascii-character normal)
8446 (define-key function-key-map (vector keypad) (vector normal))))
8447 ;; See also kp-keys bound in bindings.el.
8448 '((kp-space ?\s)
8449 (kp-tab ?\t)
8450 (kp-enter ?\r)
8451 (kp-separator ?,)
8452 (kp-equal ?=)
8453 ;; Do the same for various keys that are represented as symbols under
8454 ;; GUIs but naturally correspond to characters.
8455 (backspace 127)
8456 (delete 127)
8457 (tab ?\t)
8458 (linefeed ?\n)
8459 (clear ?\C-l)
8460 (return ?\C-m)
8461 (escape ?\e)
8464 ;;;;
8465 ;;;; forking a twin copy of a buffer.
8466 ;;;;
8468 (defvar clone-buffer-hook nil
8469 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8471 (defvar clone-indirect-buffer-hook nil
8472 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8474 (defun clone-process (process &optional newname)
8475 "Create a twin copy of PROCESS.
8476 If NEWNAME is nil, it defaults to PROCESS' name;
8477 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8478 If PROCESS is associated with a buffer, the new process will be associated
8479 with the current buffer instead.
8480 Returns nil if PROCESS has already terminated."
8481 (setq newname (or newname (process-name process)))
8482 (if (string-match "<[0-9]+>\\'" newname)
8483 (setq newname (substring newname 0 (match-beginning 0))))
8484 (when (memq (process-status process) '(run stop open))
8485 (let* ((process-connection-type (process-tty-name process))
8486 (new-process
8487 (if (memq (process-status process) '(open))
8488 (let ((args (process-contact process t)))
8489 (setq args (plist-put args :name newname))
8490 (setq args (plist-put args :buffer
8491 (if (process-buffer process)
8492 (current-buffer))))
8493 (apply 'make-network-process args))
8494 (apply 'start-process newname
8495 (if (process-buffer process) (current-buffer))
8496 (process-command process)))))
8497 (set-process-query-on-exit-flag
8498 new-process (process-query-on-exit-flag process))
8499 (set-process-inherit-coding-system-flag
8500 new-process (process-inherit-coding-system-flag process))
8501 (set-process-filter new-process (process-filter process))
8502 (set-process-sentinel new-process (process-sentinel process))
8503 (set-process-plist new-process (copy-sequence (process-plist process)))
8504 new-process)))
8506 ;; things to maybe add (currently partly covered by `funcall mode'):
8507 ;; - syntax-table
8508 ;; - overlays
8509 (defun clone-buffer (&optional newname display-flag)
8510 "Create and return a twin copy of the current buffer.
8511 Unlike an indirect buffer, the new buffer can be edited
8512 independently of the old one (if it is not read-only).
8513 NEWNAME is the name of the new buffer. It may be modified by
8514 adding or incrementing <N> at the end as necessary to create a
8515 unique buffer name. If nil, it defaults to the name of the
8516 current buffer, with the proper suffix. If DISPLAY-FLAG is
8517 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8518 clone a file-visiting buffer, or a buffer whose major mode symbol
8519 has a non-nil `no-clone' property, results in an error.
8521 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8522 current buffer with appropriate suffix. However, if a prefix
8523 argument is given, then the command prompts for NEWNAME in the
8524 minibuffer.
8526 This runs the normal hook `clone-buffer-hook' in the new buffer
8527 after it has been set up properly in other respects."
8528 (interactive
8529 (progn
8530 (if buffer-file-name
8531 (error "Cannot clone a file-visiting buffer"))
8532 (if (get major-mode 'no-clone)
8533 (error "Cannot clone a buffer in %s mode" mode-name))
8534 (list (if current-prefix-arg
8535 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8536 t)))
8537 (if buffer-file-name
8538 (error "Cannot clone a file-visiting buffer"))
8539 (if (get major-mode 'no-clone)
8540 (error "Cannot clone a buffer in %s mode" mode-name))
8541 (setq newname (or newname (buffer-name)))
8542 (if (string-match "<[0-9]+>\\'" newname)
8543 (setq newname (substring newname 0 (match-beginning 0))))
8544 (let ((buf (current-buffer))
8545 (ptmin (point-min))
8546 (ptmax (point-max))
8547 (pt (point))
8548 (mk (if mark-active (mark t)))
8549 (modified (buffer-modified-p))
8550 (mode major-mode)
8551 (lvars (buffer-local-variables))
8552 (process (get-buffer-process (current-buffer)))
8553 (new (generate-new-buffer (or newname (buffer-name)))))
8554 (save-restriction
8555 (widen)
8556 (with-current-buffer new
8557 (insert-buffer-substring buf)))
8558 (with-current-buffer new
8559 (narrow-to-region ptmin ptmax)
8560 (goto-char pt)
8561 (if mk (set-mark mk))
8562 (set-buffer-modified-p modified)
8564 ;; Clone the old buffer's process, if any.
8565 (when process (clone-process process))
8567 ;; Now set up the major mode.
8568 (funcall mode)
8570 ;; Set up other local variables.
8571 (mapc (lambda (v)
8572 (condition-case ()
8573 (if (symbolp v)
8574 (makunbound v)
8575 (set (make-local-variable (car v)) (cdr v)))
8576 (setting-constant nil))) ;E.g. for enable-multibyte-characters.
8577 lvars)
8579 (setq mark-ring (mapcar (lambda (mk) (copy-marker (marker-position mk)))
8580 mark-ring))
8582 ;; Run any hooks (typically set up by the major mode
8583 ;; for cloning to work properly).
8584 (run-hooks 'clone-buffer-hook))
8585 (if display-flag
8586 ;; Presumably the current buffer is shown in the selected frame, so
8587 ;; we want to display the clone elsewhere.
8588 (let ((same-window-regexps nil)
8589 (same-window-buffer-names))
8590 (pop-to-buffer new)))
8591 new))
8594 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8595 "Create an indirect buffer that is a twin copy of the current buffer.
8597 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8598 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8599 or if not called with a prefix arg, NEWNAME defaults to the current
8600 buffer's name. The name is modified by adding a `<N>' suffix to it
8601 or by incrementing the N in an existing suffix. Trying to clone a
8602 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8603 property results in an error.
8605 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8606 This is always done when called interactively.
8608 Optional third arg NORECORD non-nil means do not put this buffer at the
8609 front of the list of recently selected ones.
8611 Returns the newly created indirect buffer."
8612 (interactive
8613 (progn
8614 (if (get major-mode 'no-clone-indirect)
8615 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8616 (list (if current-prefix-arg
8617 (read-buffer "Name of indirect buffer: " (current-buffer)))
8618 t)))
8619 (if (get major-mode 'no-clone-indirect)
8620 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8621 (setq newname (or newname (buffer-name)))
8622 (if (string-match "<[0-9]+>\\'" newname)
8623 (setq newname (substring newname 0 (match-beginning 0))))
8624 (let* ((name (generate-new-buffer-name newname))
8625 (buffer (make-indirect-buffer (current-buffer) name t)))
8626 (with-current-buffer buffer
8627 (run-hooks 'clone-indirect-buffer-hook))
8628 (when display-flag
8629 (pop-to-buffer buffer nil norecord))
8630 buffer))
8633 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8634 "Like `clone-indirect-buffer' but display in another window."
8635 (interactive
8636 (progn
8637 (if (get major-mode 'no-clone-indirect)
8638 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8639 (list (if current-prefix-arg
8640 (read-buffer "Name of indirect buffer: " (current-buffer)))
8641 t)))
8642 (let ((pop-up-windows t))
8643 (clone-indirect-buffer newname display-flag norecord)))
8646 ;;; Handling of Backspace and Delete keys.
8648 (defcustom normal-erase-is-backspace 'maybe
8649 "Set the default behavior of the Delete and Backspace keys.
8651 If set to t, Delete key deletes forward and Backspace key deletes
8652 backward.
8654 If set to nil, both Delete and Backspace keys delete backward.
8656 If set to `maybe' (which is the default), Emacs automatically
8657 selects a behavior. On window systems, the behavior depends on
8658 the keyboard used. If the keyboard has both a Backspace key and
8659 a Delete key, and both are mapped to their usual meanings, the
8660 option's default value is set to t, so that Backspace can be used
8661 to delete backward, and Delete can be used to delete forward.
8663 If not running under a window system, customizing this option
8664 accomplishes a similar effect by mapping C-h, which is usually
8665 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8666 via `keyboard-translate'. The former functionality of C-h is
8667 available on the F1 key. You should probably not use this
8668 setting if you don't have both Backspace, Delete and F1 keys.
8670 Setting this variable with setq doesn't take effect. Programmatically,
8671 call `normal-erase-is-backspace-mode' (which see) instead."
8672 :type '(choice (const :tag "Off" nil)
8673 (const :tag "Maybe" maybe)
8674 (other :tag "On" t))
8675 :group 'editing-basics
8676 :version "21.1"
8677 :set (lambda (symbol value)
8678 ;; The fboundp is because of a problem with :set when
8679 ;; dumping Emacs. It doesn't really matter.
8680 (if (fboundp 'normal-erase-is-backspace-mode)
8681 (normal-erase-is-backspace-mode (or value 0))
8682 (set-default symbol value))))
8684 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8685 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8686 (unless frame (setq frame (selected-frame)))
8687 (with-selected-frame frame
8688 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8689 (normal-erase-is-backspace-mode
8690 (if (if (eq normal-erase-is-backspace 'maybe)
8691 (and (not noninteractive)
8692 (or (memq system-type '(ms-dos windows-nt))
8693 (memq window-system '(w32 ns))
8694 (and (memq window-system '(x))
8695 (fboundp 'x-backspace-delete-keys-p)
8696 (x-backspace-delete-keys-p))
8697 ;; If the terminal Emacs is running on has erase char
8698 ;; set to ^H, use the Backspace key for deleting
8699 ;; backward, and the Delete key for deleting forward.
8700 (and (null window-system)
8701 (eq tty-erase-char ?\^H))))
8702 normal-erase-is-backspace)
8703 1 0)))))
8705 (define-minor-mode normal-erase-is-backspace-mode
8706 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8707 With a prefix argument ARG, enable this feature if ARG is
8708 positive, and disable it otherwise. If called from Lisp, enable
8709 the mode if ARG is omitted or nil.
8711 On window systems, when this mode is on, Delete is mapped to C-d
8712 and Backspace is mapped to DEL; when this mode is off, both
8713 Delete and Backspace are mapped to DEL. (The remapping goes via
8714 `local-function-key-map', so binding Delete or Backspace in the
8715 global or local keymap will override that.)
8717 In addition, on window systems, the bindings of C-Delete, M-Delete,
8718 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8719 the global keymap in accordance with the functionality of Delete and
8720 Backspace. For example, if Delete is remapped to C-d, which deletes
8721 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8722 to DEL, which deletes backward, C-Delete is bound to
8723 `backward-kill-word'.
8725 If not running on a window system, a similar effect is accomplished by
8726 remapping C-h (normally produced by the Backspace key) and DEL via
8727 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8728 to C-d; if it's off, the keys are not remapped.
8730 When not running on a window system, and this mode is turned on, the
8731 former functionality of C-h is available on the F1 key. You should
8732 probably not turn on this mode on a text-only terminal if you don't
8733 have both Backspace, Delete and F1 keys.
8735 See also `normal-erase-is-backspace'."
8736 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8737 . (lambda (v)
8738 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8739 (if v 1 0))))
8740 (let ((enabled (eq 1 (terminal-parameter
8741 nil 'normal-erase-is-backspace))))
8743 (cond ((or (memq window-system '(x w32 ns pc))
8744 (memq system-type '(ms-dos windows-nt)))
8745 (let ((bindings
8746 `(([M-delete] [M-backspace])
8747 ([C-M-delete] [C-M-backspace])
8748 ([?\e C-delete] [?\e C-backspace]))))
8750 (if enabled
8751 (progn
8752 (define-key local-function-key-map [delete] [deletechar])
8753 (define-key local-function-key-map [kp-delete] [deletechar])
8754 (define-key local-function-key-map [backspace] [?\C-?])
8755 (dolist (b bindings)
8756 ;; Not sure if input-decode-map is really right, but
8757 ;; keyboard-translate-table (used below) only works
8758 ;; for integer events, and key-translation-table is
8759 ;; global (like the global-map, used earlier).
8760 (define-key input-decode-map (car b) nil)
8761 (define-key input-decode-map (cadr b) nil)))
8762 (define-key local-function-key-map [delete] [?\C-?])
8763 (define-key local-function-key-map [kp-delete] [?\C-?])
8764 (define-key local-function-key-map [backspace] [?\C-?])
8765 (dolist (b bindings)
8766 (define-key input-decode-map (car b) (cadr b))
8767 (define-key input-decode-map (cadr b) (car b))))))
8769 (if enabled
8770 (progn
8771 (keyboard-translate ?\C-h ?\C-?)
8772 (keyboard-translate ?\C-? ?\C-d))
8773 (keyboard-translate ?\C-h ?\C-h)
8774 (keyboard-translate ?\C-? ?\C-?))))
8776 (if (called-interactively-p 'interactive)
8777 (message "Delete key deletes %s"
8778 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8779 "forward" "backward")))))
8781 (defvar vis-mode-saved-buffer-invisibility-spec nil
8782 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8784 (define-minor-mode read-only-mode
8785 "Change whether the current buffer is read-only.
8786 With prefix argument ARG, make the buffer read-only if ARG is
8787 positive, otherwise make it writable. If buffer is read-only
8788 and `view-read-only' is non-nil, enter view mode.
8790 Do not call this from a Lisp program unless you really intend to
8791 do the same thing as the \\[read-only-mode] command, including
8792 possibly enabling or disabling View mode. Also, note that this
8793 command works by setting the variable `buffer-read-only', which
8794 does not affect read-only regions caused by text properties. To
8795 ignore read-only status in a Lisp program (whether due to text
8796 properties or buffer state), bind `inhibit-read-only' temporarily
8797 to a non-nil value."
8798 :variable buffer-read-only
8799 (cond
8800 ((and (not buffer-read-only) view-mode)
8801 (View-exit-and-edit)
8802 (make-local-variable 'view-read-only)
8803 (setq view-read-only t)) ; Must leave view mode.
8804 ((and buffer-read-only view-read-only
8805 ;; If view-mode is already active, `view-mode-enter' is a nop.
8806 (not view-mode)
8807 (not (eq (get major-mode 'mode-class) 'special)))
8808 (view-mode-enter))))
8810 (define-minor-mode visible-mode
8811 "Toggle making all invisible text temporarily visible (Visible mode).
8812 With a prefix argument ARG, enable Visible mode if ARG is
8813 positive, and disable it otherwise. If called from Lisp, enable
8814 the mode if ARG is omitted or nil.
8816 This mode works by saving the value of `buffer-invisibility-spec'
8817 and setting it to nil."
8818 :lighter " Vis"
8819 :group 'editing-basics
8820 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8821 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8822 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8823 (when visible-mode
8824 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8825 buffer-invisibility-spec)
8826 (setq buffer-invisibility-spec nil)))
8828 (defvar messages-buffer-mode-map
8829 (let ((map (make-sparse-keymap)))
8830 (set-keymap-parent map special-mode-map)
8831 (define-key map "g" nil) ; nothing to revert
8832 map))
8834 (define-derived-mode messages-buffer-mode special-mode "Messages"
8835 "Major mode used in the \"*Messages*\" buffer.")
8837 (defun messages-buffer ()
8838 "Return the \"*Messages*\" buffer.
8839 If it does not exist, create and it switch it to `messages-buffer-mode'."
8840 (or (get-buffer "*Messages*")
8841 (with-current-buffer (get-buffer-create "*Messages*")
8842 (messages-buffer-mode)
8843 (current-buffer))))
8846 ;; Minibuffer prompt stuff.
8848 ;;(defun minibuffer-prompt-modification (start end)
8849 ;; (error "You cannot modify the prompt"))
8852 ;;(defun minibuffer-prompt-insertion (start end)
8853 ;; (let ((inhibit-modification-hooks t))
8854 ;; (delete-region start end)
8855 ;; ;; Discard undo information for the text insertion itself
8856 ;; ;; and for the text deletion.above.
8857 ;; (when (consp buffer-undo-list)
8858 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8859 ;; (message "You cannot modify the prompt")))
8862 ;;(setq minibuffer-prompt-properties
8863 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8864 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8867 ;;;; Problematic external packages.
8869 ;; rms says this should be done by specifying symbols that define
8870 ;; versions together with bad values. This is therefore not as
8871 ;; flexible as it could be. See the thread:
8872 ;; https://lists.gnu.org/r/emacs-devel/2007-08/msg00300.html
8873 (defconst bad-packages-alist
8874 ;; Not sure exactly which semantic versions have problems.
8875 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8876 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8877 "The version of `semantic' loaded does not work in Emacs 22.
8878 It can cause constant high CPU load.
8879 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8880 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8881 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8882 ;; provided the `CUA-mode' feature. Since this is no longer true,
8883 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8884 (CUA-mode t nil
8885 "CUA-mode is now part of the standard GNU Emacs distribution,
8886 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8888 You have loaded an older version of CUA-mode which does not work
8889 correctly with this version of Emacs. You should remove the old
8890 version and use the one distributed with Emacs."))
8891 "Alist of packages known to cause problems in this version of Emacs.
8892 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8893 PACKAGE is either a regular expression to match file names, or a
8894 symbol (a feature name), like for `with-eval-after-load'.
8895 SYMBOL is either the name of a string variable, or t. Upon
8896 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8897 warning using STRING as the message.")
8899 (defun bad-package-check (package)
8900 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8901 (condition-case nil
8902 (let* ((list (assoc package bad-packages-alist))
8903 (symbol (nth 1 list)))
8904 (and list
8905 (boundp symbol)
8906 (or (eq symbol t)
8907 (and (stringp (setq symbol (eval symbol)))
8908 (string-match-p (nth 2 list) symbol)))
8909 (display-warning package (nth 3 list) :warning)))
8910 (error nil)))
8912 (dolist (elem bad-packages-alist)
8913 (let ((pkg (car elem)))
8914 (with-eval-after-load pkg
8915 (bad-package-check pkg))))
8918 ;;; Generic dispatcher commands
8920 ;; Macro `define-alternatives' is used to create generic commands.
8921 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8922 ;; that can have different alternative implementations where choosing
8923 ;; among them is exclusively a matter of user preference.
8925 ;; (define-alternatives COMMAND) creates a new interactive command
8926 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8927 ;; Typically, the user will not need to customize this variable; packages
8928 ;; wanting to add alternative implementations should use
8930 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8932 (defmacro define-alternatives (command &rest customizations)
8933 "Define the new command `COMMAND'.
8935 The argument `COMMAND' should be a symbol.
8937 Running `M-x COMMAND RET' for the first time prompts for which
8938 alternative to use and records the selected command as a custom
8939 variable.
8941 Running `C-u M-x COMMAND RET' prompts again for an alternative
8942 and overwrites the previous choice.
8944 The variable `COMMAND-alternatives' contains an alist with
8945 alternative implementations of COMMAND. `define-alternatives'
8946 does not have any effect until this variable is set.
8948 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8949 `defcustom' keywords and values to add to the declaration of
8950 `COMMAND-alternatives' (typically :group and :version)."
8951 (let* ((command-name (symbol-name command))
8952 (varalt-name (concat command-name "-alternatives"))
8953 (varalt-sym (intern varalt-name))
8954 (varimp-sym (intern (concat command-name "--implementation"))))
8955 `(progn
8957 (defcustom ,varalt-sym nil
8958 ,(format "Alist of alternative implementations for the `%s' command.
8960 Each entry must be a pair (ALTNAME . ALTFUN), where:
8961 ALTNAME - The name shown at user to describe the alternative implementation.
8962 ALTFUN - The function called to implement this alternative."
8963 command-name)
8964 :type '(alist :key-type string :value-type function)
8965 ,@customizations)
8967 (put ',varalt-sym 'definition-name ',command)
8968 (defvar ,varimp-sym nil "Internal use only.")
8970 (defun ,command (&optional arg)
8971 ,(format "Run generic command `%s'.
8972 If used for the first time, or with interactive ARG, ask the user which
8973 implementation to use for `%s'. The variable `%s'
8974 contains the list of implementations currently supported for this command."
8975 command-name command-name varalt-name)
8976 (interactive "P")
8977 (when (or arg (null ,varimp-sym))
8978 (let ((val (completing-read
8979 ,(format-message
8980 "Select implementation for command `%s': "
8981 command-name)
8982 ,varalt-sym nil t)))
8983 (unless (string-equal val "")
8984 (when (null ,varimp-sym)
8985 (message
8986 "Use C-u M-x %s RET`to select another implementation"
8987 ,command-name)
8988 (sit-for 3))
8989 (customize-save-variable ',varimp-sym
8990 (cdr (assoc-string val ,varalt-sym))))))
8991 (if ,varimp-sym
8992 (call-interactively ,varimp-sym)
8993 (message "%s" ,(format-message
8994 "No implementation selected for command `%s'"
8995 command-name)))))))
8998 ;;; Functions for changing capitalization that Do What I Mean
8999 (defun upcase-dwim (arg)
9000 "Upcase words in the region, if active; if not, upcase word at point.
9001 If the region is active, this function calls `upcase-region'.
9002 Otherwise, it calls `upcase-word', with prefix argument passed to it
9003 to upcase ARG words."
9004 (interactive "*p")
9005 (if (use-region-p)
9006 (upcase-region (region-beginning) (region-end) (region-noncontiguous-p))
9007 (upcase-word arg)))
9009 (defun downcase-dwim (arg)
9010 "Downcase words in the region, if active; if not, downcase word at point.
9011 If the region is active, this function calls `downcase-region'.
9012 Otherwise, it calls `downcase-word', with prefix argument passed to it
9013 to downcase ARG words."
9014 (interactive "*p")
9015 (if (use-region-p)
9016 (downcase-region (region-beginning) (region-end) (region-noncontiguous-p))
9017 (downcase-word arg)))
9019 (defun capitalize-dwim (arg)
9020 "Capitalize words in the region, if active; if not, capitalize word at point.
9021 If the region is active, this function calls `capitalize-region'.
9022 Otherwise, it calls `capitalize-word', with prefix argument passed to it
9023 to capitalize ARG words."
9024 (interactive "*p")
9025 (if (use-region-p)
9026 (capitalize-region (region-beginning) (region-end))
9027 (capitalize-word arg)))
9031 (provide 'simple)
9033 ;;; simple.el ends here