(gnus-blocked-images): Clarify privacy implications
[emacs.git] / lisp / simple.el
blob57e70a8d15310b7fda7e9b33371b522925c2dc5c
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 (declare-function comint-output-filter "comint" (process string))
3405 (defun shell-command (command &optional output-buffer error-buffer)
3406 "Execute string COMMAND in inferior shell; display output, if any.
3407 With prefix argument, insert the COMMAND's output at point.
3409 Interactively, prompt for COMMAND in the minibuffer.
3411 If COMMAND ends in `&', execute it asynchronously.
3412 The output appears in the buffer `*Async Shell Command*'.
3413 That buffer is in shell mode. You can also use
3414 `async-shell-command' that automatically adds `&'.
3416 Otherwise, COMMAND is executed synchronously. The output appears in
3417 the buffer `*Shell Command Output*'. If the output is short enough to
3418 display in the echo area (which is determined by the variables
3419 `resize-mini-windows' and `max-mini-window-height'), it is shown
3420 there, but it is nonetheless available in buffer `*Shell Command
3421 Output*' even though that buffer is not automatically displayed.
3423 To specify a coding system for converting non-ASCII characters
3424 in the shell command output, use \\[universal-coding-system-argument] \
3425 before this command.
3427 Noninteractive callers can specify coding systems by binding
3428 `coding-system-for-read' and `coding-system-for-write'.
3430 The optional second argument OUTPUT-BUFFER, if non-nil,
3431 says to put the output in some other buffer.
3432 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3433 and insert the output there; a non-nil value of
3434 `shell-command-dont-erase-buffer' prevents the buffer from being
3435 erased. If OUTPUT-BUFFER is not a buffer and not nil, insert the
3436 output in current buffer after point leaving mark after it. This
3437 cannot be done asynchronously.
3439 If the command terminates without error, but generates output,
3440 and you did not specify \"insert it in the current buffer\",
3441 the output can be displayed in the echo area or in its buffer.
3442 If the output is short enough to display in the echo area
3443 \(determined by the variable `max-mini-window-height' if
3444 `resize-mini-windows' is non-nil), it is shown there.
3445 Otherwise, the buffer containing the output is displayed.
3447 If there is output and an error, and you did not specify \"insert it
3448 in the current buffer\", a message about the error goes at the end
3449 of the output.
3451 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3452 or buffer name to which to direct the command's standard error output.
3453 If it is nil, error output is mingled with regular output.
3454 In an interactive call, the variable `shell-command-default-error-buffer'
3455 specifies the value of ERROR-BUFFER.
3457 In Elisp, you will often be better served by calling `call-process' or
3458 `start-process' directly, since they offer more control and do not
3459 impose the use of a shell (with its need to quote arguments)."
3461 (interactive
3462 (list
3463 (read-shell-command "Shell command: " nil nil
3464 (let ((filename
3465 (cond
3466 (buffer-file-name)
3467 ((eq major-mode 'dired-mode)
3468 (dired-get-filename nil t)))))
3469 (and filename (file-relative-name filename))))
3470 current-prefix-arg
3471 shell-command-default-error-buffer))
3472 ;; Look for a handler in case default-directory is a remote file name.
3473 (let ((handler
3474 (find-file-name-handler (directory-file-name default-directory)
3475 'shell-command)))
3476 (if handler
3477 (funcall handler 'shell-command command output-buffer error-buffer)
3478 (if (and output-buffer
3479 (not (or (bufferp output-buffer) (stringp output-buffer))))
3480 ;; Output goes in current buffer.
3481 (let ((error-file
3482 (and error-buffer
3483 (make-temp-file
3484 (expand-file-name "scor"
3485 (or small-temporary-file-directory
3486 temporary-file-directory))))))
3487 (barf-if-buffer-read-only)
3488 (push-mark nil t)
3489 ;; We do not use -f for csh; we will not support broken use of
3490 ;; .cshrcs. Even the BSD csh manual says to use
3491 ;; "if ($?prompt) exit" before things which are not useful
3492 ;; non-interactively. Besides, if someone wants their other
3493 ;; aliases for shell commands then they can still have them.
3494 (call-process-shell-command command nil (if error-file
3495 (list t error-file)
3497 (when (and error-file (file-exists-p error-file))
3498 (when (< 0 (file-attribute-size (file-attributes error-file)))
3499 (with-current-buffer (get-buffer-create error-buffer)
3500 (let ((pos-from-end (- (point-max) (point))))
3501 (or (bobp)
3502 (insert "\f\n"))
3503 ;; Do no formatting while reading error file,
3504 ;; because that can run a shell command, and we
3505 ;; don't want that to cause an infinite recursion.
3506 (format-insert-file error-file nil)
3507 ;; Put point after the inserted errors.
3508 (goto-char (- (point-max) pos-from-end)))
3509 (display-buffer (current-buffer))))
3510 (delete-file error-file))
3511 ;; This is like exchange-point-and-mark, but doesn't
3512 ;; activate the mark. It is cleaner to avoid activation,
3513 ;; even though the command loop would deactivate the mark
3514 ;; because we inserted text.
3515 (goto-char (prog1 (mark t)
3516 (set-marker (mark-marker) (point)
3517 (current-buffer)))))
3518 ;; Output goes in a separate buffer.
3519 ;; Preserve the match data in case called from a program.
3520 ;; FIXME: It'd be ridiculous for an Elisp function to call
3521 ;; shell-command and assume that it won't mess the match-data!
3522 (save-match-data
3523 (if (string-match "[ \t]*&[ \t]*\\'" command)
3524 ;; Command ending with ampersand means asynchronous.
3525 (let* ((buffer (get-buffer-create
3526 (or output-buffer "*Async Shell Command*")))
3527 (bname (buffer-name buffer))
3528 (proc (get-buffer-process buffer))
3529 (directory default-directory))
3530 ;; Remove the ampersand.
3531 (setq command (substring command 0 (match-beginning 0)))
3532 ;; Ask the user what to do with already running process.
3533 (when proc
3534 (cond
3535 ((eq async-shell-command-buffer 'confirm-kill-process)
3536 ;; If will kill a process, query first.
3537 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3538 (kill-process proc)
3539 (error "Shell command in progress")))
3540 ((eq async-shell-command-buffer 'confirm-new-buffer)
3541 ;; If will create a new buffer, query first.
3542 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3543 (setq buffer (generate-new-buffer bname))
3544 (error "Shell command in progress")))
3545 ((eq async-shell-command-buffer 'new-buffer)
3546 ;; It will create a new buffer.
3547 (setq buffer (generate-new-buffer bname)))
3548 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3549 ;; If will rename the buffer, query first.
3550 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3551 (progn
3552 (with-current-buffer buffer
3553 (rename-uniquely))
3554 (setq buffer (get-buffer-create bname)))
3555 (error "Shell command in progress")))
3556 ((eq async-shell-command-buffer 'rename-buffer)
3557 ;; It will rename the buffer.
3558 (with-current-buffer buffer
3559 (rename-uniquely))
3560 (setq buffer (get-buffer-create bname)))))
3561 (with-current-buffer buffer
3562 (shell-command--save-pos-or-erase)
3563 (setq default-directory directory)
3564 (setq proc
3565 (start-process-shell-command "Shell" buffer command))
3566 (setq mode-line-process '(":%s"))
3567 (require 'shell) (shell-mode)
3568 (set-process-sentinel proc #'shell-command-sentinel)
3569 ;; Use the comint filter for proper handling of
3570 ;; carriage motion (see comint-inhibit-carriage-motion).
3571 (set-process-filter proc #'comint-output-filter)
3572 (if async-shell-command-display-buffer
3573 ;; Display buffer immediately.
3574 (display-buffer buffer '(nil (allow-no-window . t)))
3575 ;; Defer displaying buffer until first process output.
3576 ;; Use disposable named advice so that the buffer is
3577 ;; displayed at most once per process lifetime.
3578 (let ((nonce (make-symbol "nonce")))
3579 (add-function :before (process-filter proc)
3580 (lambda (proc _string)
3581 (let ((buf (process-buffer proc)))
3582 (when (buffer-live-p buf)
3583 (remove-function (process-filter proc)
3584 nonce)
3585 (display-buffer buf))))
3586 `((name . ,nonce)))))))
3587 ;; Otherwise, command is executed synchronously.
3588 (shell-command-on-region (point) (point) command
3589 output-buffer nil error-buffer)))))))
3591 (defun display-message-or-buffer (message &optional buffer-name action frame)
3592 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3593 MESSAGE may be either a string or a buffer.
3595 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3596 for maximum height of the echo area, as defined by `max-mini-window-height'
3597 if `resize-mini-windows' is non-nil.
3599 Returns either the string shown in the echo area, or when a pop-up
3600 buffer is used, the window used to display it.
3602 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3603 name of the buffer used to display it in the case where a pop-up buffer
3604 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3605 string and it is displayed in the echo area, it is not specified whether
3606 the contents are inserted into the buffer anyway.
3608 Optional arguments ACTION and FRAME are as for `display-buffer',
3609 and are only used if a pop-up buffer is displayed."
3610 (cond ((and (stringp message) (not (string-match "\n" message)))
3611 ;; Trivial case where we can use the echo area
3612 (message "%s" message))
3613 ((and (stringp message)
3614 (= (string-match "\n" message) (1- (length message))))
3615 ;; Trivial case where we can just remove single trailing newline
3616 (message "%s" (substring message 0 (1- (length message)))))
3618 ;; General case
3619 (with-current-buffer
3620 (if (bufferp message)
3621 message
3622 (get-buffer-create (or buffer-name "*Message*")))
3624 (unless (bufferp message)
3625 (erase-buffer)
3626 (insert message))
3628 (let ((lines
3629 (if (= (buffer-size) 0)
3631 (count-screen-lines nil nil nil (minibuffer-window)))))
3632 (cond ((= lines 0))
3633 ((and (or (<= lines 1)
3634 (<= lines
3635 (if resize-mini-windows
3636 (cond ((floatp max-mini-window-height)
3637 (* (frame-height)
3638 max-mini-window-height))
3639 ((integerp max-mini-window-height)
3640 max-mini-window-height)
3643 1)))
3644 ;; Don't use the echo area if the output buffer is
3645 ;; already displayed in the selected frame.
3646 (not (get-buffer-window (current-buffer))))
3647 ;; Echo area
3648 (goto-char (point-max))
3649 (when (bolp)
3650 (backward-char 1))
3651 (message "%s" (buffer-substring (point-min) (point))))
3653 ;; Buffer
3654 (goto-char (point-min))
3655 (display-buffer (current-buffer) action frame))))))))
3658 ;; We have a sentinel to prevent insertion of a termination message
3659 ;; in the buffer itself, and to set the point in the buffer when
3660 ;; `shell-command-dont-erase-buffer' is non-nil.
3661 (defun shell-command-sentinel (process signal)
3662 (when (memq (process-status process) '(exit signal))
3663 (shell-command--set-point-after-cmd (process-buffer process))
3664 (message "%s: %s."
3665 (car (cdr (cdr (process-command process))))
3666 (substring signal 0 -1))))
3668 (defun shell-command-on-region (start end command
3669 &optional output-buffer replace
3670 error-buffer display-error-buffer
3671 region-noncontiguous-p)
3672 "Execute string COMMAND in inferior shell with region as input.
3673 Normally display output (if any) in temp buffer `*Shell Command Output*';
3674 Prefix arg means replace the region with it. Return the exit code of
3675 COMMAND.
3677 To specify a coding system for converting non-ASCII characters
3678 in the input and output to the shell command, use \\[universal-coding-system-argument]
3679 before this command. By default, the input (from the current buffer)
3680 is encoded using coding-system specified by `process-coding-system-alist',
3681 falling back to `default-process-coding-system' if no match for COMMAND
3682 is found in `process-coding-system-alist'.
3684 Noninteractive callers can specify coding systems by binding
3685 `coding-system-for-read' and `coding-system-for-write'.
3687 If the command generates output, the output may be displayed
3688 in the echo area or in a buffer.
3689 If the output is short enough to display in the echo area
3690 \(determined by the variable `max-mini-window-height' if
3691 `resize-mini-windows' is non-nil), it is shown there.
3692 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3693 The output is available in that buffer in both cases.
3695 If there is output and an error, a message about the error
3696 appears at the end of the output.
3698 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3699 command's output. If the value is a buffer or buffer name,
3700 erase that buffer and insert the output there; a non-nil value of
3701 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3702 If the value is nil, use the buffer `*Shell Command Output*'.
3703 Any other non-nil value means to insert the output in the
3704 current buffer after START.
3706 Optional fifth arg REPLACE, if non-nil, means to insert the
3707 output in place of text from START to END, putting point and mark
3708 around it.
3710 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3711 or buffer name to which to direct the command's standard error
3712 output. If nil, error output is mingled with regular output.
3713 When called interactively, `shell-command-default-error-buffer'
3714 is used for ERROR-BUFFER.
3716 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3717 display the error buffer if there were any errors. When called
3718 interactively, this is t."
3719 (interactive (let (string)
3720 (unless (mark)
3721 (user-error "The mark is not set now, so there is no region"))
3722 ;; Do this before calling region-beginning
3723 ;; and region-end, in case subprocess output
3724 ;; relocates them while we are in the minibuffer.
3725 (setq string (read-shell-command "Shell command on region: "))
3726 ;; call-interactively recognizes region-beginning and
3727 ;; region-end specially, leaving them in the history.
3728 (list (region-beginning) (region-end)
3729 string
3730 current-prefix-arg
3731 current-prefix-arg
3732 shell-command-default-error-buffer
3734 (region-noncontiguous-p))))
3735 (let ((error-file
3736 (if error-buffer
3737 (make-temp-file
3738 (expand-file-name "scor"
3739 (or small-temporary-file-directory
3740 temporary-file-directory)))
3741 nil))
3742 exit-status)
3743 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3744 (if region-noncontiguous-p
3745 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3746 output)
3747 (with-temp-buffer
3748 (insert input)
3749 (call-process-region (point-min) (point-max)
3750 shell-file-name t t
3751 nil shell-command-switch
3752 command)
3753 (setq output (split-string (buffer-string) "\n")))
3754 (goto-char start)
3755 (funcall region-insert-function output))
3756 (if (or replace
3757 (and output-buffer
3758 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3759 ;; Replace specified region with output from command.
3760 (let ((swap (and replace (< start end))))
3761 ;; Don't muck with mark unless REPLACE says we should.
3762 (goto-char start)
3763 (and replace (push-mark (point) 'nomsg))
3764 (setq exit-status
3765 (call-shell-region start end command replace
3766 (if error-file
3767 (list t error-file)
3768 t)))
3769 ;; It is rude to delete a buffer which the command is not using.
3770 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3771 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3772 ;; (kill-buffer shell-buffer)))
3773 ;; Don't muck with mark unless REPLACE says we should.
3774 (and replace swap (exchange-point-and-mark)))
3775 ;; No prefix argument: put the output in a temp buffer,
3776 ;; replacing its entire contents.
3777 (let ((buffer (get-buffer-create
3778 (or output-buffer "*Shell Command Output*"))))
3779 (unwind-protect
3780 (if (and (eq buffer (current-buffer))
3781 (or (not shell-command-dont-erase-buffer)
3782 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3783 (not (region-active-p)))))
3784 ;; If the input is the same buffer as the output,
3785 ;; delete everything but the specified region,
3786 ;; then replace that region with the output.
3787 (progn (setq buffer-read-only nil)
3788 (delete-region (max start end) (point-max))
3789 (delete-region (point-min) (min start end))
3790 (setq exit-status
3791 (call-process-region (point-min) (point-max)
3792 shell-file-name t
3793 (if error-file
3794 (list t error-file)
3796 nil shell-command-switch
3797 command)))
3798 ;; Clear the output buffer, then run the command with
3799 ;; output there.
3800 (let ((directory default-directory))
3801 (with-current-buffer buffer
3802 (if (not output-buffer)
3803 (setq default-directory directory))
3804 (shell-command--save-pos-or-erase)))
3805 (setq exit-status
3806 (call-shell-region start end command nil
3807 (if error-file
3808 (list buffer error-file)
3809 buffer))))
3810 ;; Report the output.
3811 (with-current-buffer buffer
3812 (setq mode-line-process
3813 (cond ((null exit-status)
3814 " - Error")
3815 ((stringp exit-status)
3816 (format " - Signal [%s]" exit-status))
3817 ((not (equal 0 exit-status))
3818 (format " - Exit [%d]" exit-status)))))
3819 (if (with-current-buffer buffer (> (point-max) (point-min)))
3820 ;; There's some output, display it
3821 (progn
3822 (display-message-or-buffer buffer)
3823 (shell-command--set-point-after-cmd buffer))
3824 ;; No output; error?
3825 (let ((output
3826 (if (and error-file
3827 (< 0 (nth 7 (file-attributes error-file))))
3828 (format "some error output%s"
3829 (if shell-command-default-error-buffer
3830 (format " to the \"%s\" buffer"
3831 shell-command-default-error-buffer)
3832 ""))
3833 "no output")))
3834 (cond ((null exit-status)
3835 (message "(Shell command failed with error)"))
3836 ((equal 0 exit-status)
3837 (message "(Shell command succeeded with %s)"
3838 output))
3839 ((stringp exit-status)
3840 (message "(Shell command killed by signal %s)"
3841 exit-status))
3843 (message "(Shell command failed with code %d and %s)"
3844 exit-status output))))
3845 ;; Don't kill: there might be useful info in the undo-log.
3846 ;; (kill-buffer buffer)
3847 )))))
3849 (when (and error-file (file-exists-p error-file))
3850 (if (< 0 (nth 7 (file-attributes error-file)))
3851 (with-current-buffer (get-buffer-create error-buffer)
3852 (let ((pos-from-end (- (point-max) (point))))
3853 (or (bobp)
3854 (insert "\f\n"))
3855 ;; Do no formatting while reading error file,
3856 ;; because that can run a shell command, and we
3857 ;; don't want that to cause an infinite recursion.
3858 (format-insert-file error-file nil)
3859 ;; Put point after the inserted errors.
3860 (goto-char (- (point-max) pos-from-end)))
3861 (and display-error-buffer
3862 (display-buffer (current-buffer)))))
3863 (delete-file error-file))
3864 exit-status))
3866 (defun shell-command-to-string (command)
3867 "Execute shell command COMMAND and return its output as a string."
3868 (with-output-to-string
3869 (with-current-buffer
3870 standard-output
3871 (shell-command command t))))
3873 (defun process-file (program &optional infile buffer display &rest args)
3874 "Process files synchronously in a separate process.
3875 Similar to `call-process', but may invoke a file handler based on
3876 `default-directory'. The current working directory of the
3877 subprocess is `default-directory'.
3879 File names in INFILE and BUFFER are handled normally, but file
3880 names in ARGS should be relative to `default-directory', as they
3881 are passed to the process verbatim. (This is a difference to
3882 `call-process' which does not support file handlers for INFILE
3883 and BUFFER.)
3885 Some file handlers might not support all variants, for example
3886 they might behave as if DISPLAY was nil, regardless of the actual
3887 value passed."
3888 (let ((fh (find-file-name-handler default-directory 'process-file))
3889 lc stderr-file)
3890 (unwind-protect
3891 (if fh (apply fh 'process-file program infile buffer display args)
3892 (when infile (setq lc (file-local-copy infile)))
3893 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3894 (make-temp-file "emacs")))
3895 (prog1
3896 (apply 'call-process program
3897 (or lc infile)
3898 (if stderr-file (list (car buffer) stderr-file) buffer)
3899 display args)
3900 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3901 (when stderr-file (delete-file stderr-file))
3902 (when lc (delete-file lc)))))
3904 (defvar process-file-side-effects t
3905 "Whether a call of `process-file' changes remote files.
3907 By default, this variable is always set to t, meaning that a
3908 call of `process-file' could potentially change any file on a
3909 remote host. When set to nil, a file handler could optimize
3910 its behavior with respect to remote file attribute caching.
3912 You should only ever change this variable with a let-binding;
3913 never with `setq'.")
3915 (defun start-file-process (name buffer program &rest program-args)
3916 "Start a program in a subprocess. Return the process object for it.
3918 Similar to `start-process', but may invoke a file handler based on
3919 `default-directory'. See Info node `(elisp)Magic File Names'.
3921 This handler ought to run PROGRAM, perhaps on the local host,
3922 perhaps on a remote host that corresponds to `default-directory'.
3923 In the latter case, the local part of `default-directory' becomes
3924 the working directory of the process.
3926 PROGRAM and PROGRAM-ARGS might be file names. They are not
3927 objects of file handler invocation. File handlers might not
3928 support pty association, if PROGRAM is nil."
3929 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3930 (if fh (apply fh 'start-file-process name buffer program program-args)
3931 (apply 'start-process name buffer program program-args))))
3933 ;;;; Process menu
3935 (defvar tabulated-list-format)
3936 (defvar tabulated-list-entries)
3937 (defvar tabulated-list-sort-key)
3938 (declare-function tabulated-list-init-header "tabulated-list" ())
3939 (declare-function tabulated-list-print "tabulated-list"
3940 (&optional remember-pos update))
3942 (defvar process-menu-query-only nil)
3944 (defvar process-menu-mode-map
3945 (let ((map (make-sparse-keymap)))
3946 (define-key map [?d] 'process-menu-delete-process)
3947 map))
3949 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3950 "Major mode for listing the processes called by Emacs."
3951 (setq tabulated-list-format [("Process" 15 t)
3952 ("PID" 7 t)
3953 ("Status" 7 t)
3954 ;; 25 is the length of the long standard buffer
3955 ;; name "*Async Shell Command*<10>" (bug#30016)
3956 ("Buffer" 25 t)
3957 ("TTY" 12 t)
3958 ("Command" 0 t)])
3959 (make-local-variable 'process-menu-query-only)
3960 (setq tabulated-list-sort-key (cons "Process" nil))
3961 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t))
3963 (defun process-menu-delete-process ()
3964 "Kill process at point in a `list-processes' buffer."
3965 (interactive)
3966 (let ((pos (point)))
3967 (delete-process (tabulated-list-get-id))
3968 (revert-buffer)
3969 (goto-char (min pos (point-max)))
3970 (if (eobp)
3971 (forward-line -1)
3972 (beginning-of-line))))
3974 (defun list-processes--refresh ()
3975 "Recompute the list of processes for the Process List buffer.
3976 Also, delete any process that is exited or signaled."
3977 (setq tabulated-list-entries nil)
3978 (dolist (p (process-list))
3979 (cond ((memq (process-status p) '(exit signal closed))
3980 (delete-process p))
3981 ((or (not process-menu-query-only)
3982 (process-query-on-exit-flag p))
3983 (let* ((buf (process-buffer p))
3984 (type (process-type p))
3985 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3986 (name (process-name p))
3987 (status (symbol-name (process-status p)))
3988 (buf-label (if (buffer-live-p buf)
3989 `(,(buffer-name buf)
3990 face link
3991 help-echo ,(format-message
3992 "Visit buffer `%s'"
3993 (buffer-name buf))
3994 follow-link t
3995 process-buffer ,buf
3996 action process-menu-visit-buffer)
3997 "--"))
3998 (tty (or (process-tty-name p) "--"))
3999 (cmd
4000 (if (memq type '(network serial))
4001 (let ((contact (process-contact p t)))
4002 (if (eq type 'network)
4003 (format "(%s %s)"
4004 (if (plist-get contact :type)
4005 "datagram"
4006 "network")
4007 (if (plist-get contact :server)
4008 (format "server on %s"
4010 (plist-get contact :host)
4011 (plist-get contact :local)))
4012 (format "connection to %s"
4013 (plist-get contact :host))))
4014 (format "(serial port %s%s)"
4015 (or (plist-get contact :port) "?")
4016 (let ((speed (plist-get contact :speed)))
4017 (if speed
4018 (format " at %s b/s" speed)
4019 "")))))
4020 (mapconcat 'identity (process-command p) " "))))
4021 (push (list p (vector name pid status buf-label tty cmd))
4022 tabulated-list-entries)))))
4023 (tabulated-list-init-header))
4025 (defun process-menu-visit-buffer (button)
4026 (display-buffer (button-get button 'process-buffer)))
4028 (defun list-processes (&optional query-only buffer)
4029 "Display a list of all processes that are Emacs sub-processes.
4030 If optional argument QUERY-ONLY is non-nil, only processes with
4031 the query-on-exit flag set are listed.
4032 Any process listed as exited or signaled is actually eliminated
4033 after the listing is made.
4034 Optional argument BUFFER specifies a buffer to use, instead of
4035 \"*Process List*\".
4036 The return value is always nil.
4038 This function lists only processes that were launched by Emacs. To
4039 see other processes running on the system, use `list-system-processes'."
4040 (interactive)
4041 (or (fboundp 'process-list)
4042 (error "Asynchronous subprocesses are not supported on this system"))
4043 (unless (bufferp buffer)
4044 (setq buffer (get-buffer-create "*Process List*")))
4045 (with-current-buffer buffer
4046 (process-menu-mode)
4047 (setq process-menu-query-only query-only)
4048 (list-processes--refresh)
4049 (tabulated-list-print))
4050 (display-buffer buffer)
4051 nil)
4053 ;;;; Prefix commands
4055 (setq prefix-command--needs-update nil)
4056 (setq prefix-command--last-echo nil)
4058 (defun internal-echo-keystrokes-prefix ()
4059 ;; BEWARE: Called directly from C code.
4060 ;; If the return value is non-nil, it means we are in the middle of
4061 ;; a command with prefix, such as a command invoked with prefix-arg.
4062 (if (not prefix-command--needs-update)
4063 prefix-command--last-echo
4064 (setq prefix-command--last-echo
4065 (let ((strs nil))
4066 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4067 (lambda (fun) (push (funcall fun) strs)))
4068 (setq strs (delq nil strs))
4069 (when strs (mapconcat #'identity strs " "))))))
4071 (defvar prefix-command-echo-keystrokes-functions nil
4072 "Abnormal hook which constructs the description of the current prefix state.
4073 Each function is called with no argument, should return a string or nil.")
4075 (defun prefix-command-update ()
4076 "Update state of prefix commands.
4077 Call it whenever you change the \"prefix command state\"."
4078 (setq prefix-command--needs-update t))
4080 (defvar prefix-command-preserve-state-hook nil
4081 "Normal hook run when a command needs to preserve the prefix.")
4083 (defun prefix-command-preserve-state ()
4084 "Pass the current prefix command state to the next command.
4085 Should be called by all prefix commands.
4086 Runs `prefix-command-preserve-state-hook'."
4087 (run-hooks 'prefix-command-preserve-state-hook)
4088 ;; If the current command is a prefix command, we don't want the next (real)
4089 ;; command to have `last-command' set to, say, `universal-argument'.
4090 (setq this-command last-command)
4091 (setq real-this-command real-last-command)
4092 (prefix-command-update))
4094 (defun reset-this-command-lengths ()
4095 (declare (obsolete prefix-command-preserve-state "25.1"))
4096 nil)
4098 ;;;;; The main prefix command.
4100 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4102 (add-hook 'prefix-command-echo-keystrokes-functions
4103 #'universal-argument--description)
4104 (defun universal-argument--description ()
4105 (when prefix-arg
4106 (concat "C-u"
4107 (pcase prefix-arg
4108 (`(-) " -")
4109 (`(,(and (pred integerp) n))
4110 (let ((str ""))
4111 (while (and (> n 4) (= (mod n 4) 0))
4112 (setq str (concat str " C-u"))
4113 (setq n (/ n 4)))
4114 (if (= n 4) str (format " %s" prefix-arg))))
4115 (_ (format " %s" prefix-arg))))))
4117 (add-hook 'prefix-command-preserve-state-hook
4118 #'universal-argument--preserve)
4119 (defun universal-argument--preserve ()
4120 (setq prefix-arg current-prefix-arg))
4122 (defvar universal-argument-map
4123 (let ((map (make-sparse-keymap))
4124 (universal-argument-minus
4125 ;; For backward compatibility, minus with no modifiers is an ordinary
4126 ;; command if digits have already been entered.
4127 `(menu-item "" negative-argument
4128 :filter ,(lambda (cmd)
4129 (if (integerp prefix-arg) nil cmd)))))
4130 (define-key map [switch-frame]
4131 (lambda (e) (interactive "e")
4132 (handle-switch-frame e) (universal-argument--mode)))
4133 (define-key map [?\C-u] 'universal-argument-more)
4134 (define-key map [?-] universal-argument-minus)
4135 (define-key map [?0] 'digit-argument)
4136 (define-key map [?1] 'digit-argument)
4137 (define-key map [?2] 'digit-argument)
4138 (define-key map [?3] 'digit-argument)
4139 (define-key map [?4] 'digit-argument)
4140 (define-key map [?5] 'digit-argument)
4141 (define-key map [?6] 'digit-argument)
4142 (define-key map [?7] 'digit-argument)
4143 (define-key map [?8] 'digit-argument)
4144 (define-key map [?9] 'digit-argument)
4145 (define-key map [kp-0] 'digit-argument)
4146 (define-key map [kp-1] 'digit-argument)
4147 (define-key map [kp-2] 'digit-argument)
4148 (define-key map [kp-3] 'digit-argument)
4149 (define-key map [kp-4] 'digit-argument)
4150 (define-key map [kp-5] 'digit-argument)
4151 (define-key map [kp-6] 'digit-argument)
4152 (define-key map [kp-7] 'digit-argument)
4153 (define-key map [kp-8] 'digit-argument)
4154 (define-key map [kp-9] 'digit-argument)
4155 (define-key map [kp-subtract] universal-argument-minus)
4156 map)
4157 "Keymap used while processing \\[universal-argument].")
4159 (defun universal-argument--mode ()
4160 (prefix-command-update)
4161 (set-transient-map universal-argument-map nil))
4163 (defun universal-argument ()
4164 "Begin a numeric argument for the following command.
4165 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4166 \\[universal-argument] following the digits or minus sign ends the argument.
4167 \\[universal-argument] without digits or minus sign provides 4 as argument.
4168 Repeating \\[universal-argument] without digits or minus sign
4169 multiplies the argument by 4 each time.
4170 For some commands, just \\[universal-argument] by itself serves as a flag
4171 which is different in effect from any particular numeric argument.
4172 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4173 (interactive)
4174 (prefix-command-preserve-state)
4175 (setq prefix-arg (list 4))
4176 (universal-argument--mode))
4178 (defun universal-argument-more (arg)
4179 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4180 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4181 (interactive "P")
4182 (prefix-command-preserve-state)
4183 (setq prefix-arg (if (consp arg)
4184 (list (* 4 (car arg)))
4185 (if (eq arg '-)
4186 (list -4)
4187 arg)))
4188 (when (consp prefix-arg) (universal-argument--mode)))
4190 (defun negative-argument (arg)
4191 "Begin a negative numeric argument for the next command.
4192 \\[universal-argument] following digits or minus sign ends the argument."
4193 (interactive "P")
4194 (prefix-command-preserve-state)
4195 (setq prefix-arg (cond ((integerp arg) (- arg))
4196 ((eq arg '-) nil)
4197 (t '-)))
4198 (universal-argument--mode))
4200 (defun digit-argument (arg)
4201 "Part of the numeric argument for the next command.
4202 \\[universal-argument] following digits or minus sign ends the argument."
4203 (interactive "P")
4204 (prefix-command-preserve-state)
4205 (let* ((char (if (integerp last-command-event)
4206 last-command-event
4207 (get last-command-event 'ascii-character)))
4208 (digit (- (logand char ?\177) ?0)))
4209 (setq prefix-arg (cond ((integerp arg)
4210 (+ (* arg 10)
4211 (if (< arg 0) (- digit) digit)))
4212 ((eq arg '-)
4213 ;; Treat -0 as just -, so that -01 will work.
4214 (if (zerop digit) '- (- digit)))
4216 digit))))
4217 (universal-argument--mode))
4220 (defvar filter-buffer-substring-functions nil
4221 "This variable is a wrapper hook around `buffer-substring--filter'.
4222 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4223 (make-obsolete-variable 'filter-buffer-substring-functions
4224 'filter-buffer-substring-function "24.4")
4226 (defvar filter-buffer-substring-function #'buffer-substring--filter
4227 "Function to perform the filtering in `filter-buffer-substring'.
4228 The function is called with the same 3 arguments (BEG END DELETE)
4229 that `filter-buffer-substring' received. It should return the
4230 buffer substring between BEG and END, after filtering. If DELETE is
4231 non-nil, it should delete the text between BEG and END from the buffer.")
4233 (defvar buffer-substring-filters nil
4234 "List of filter functions for `buffer-substring--filter'.
4235 Each function must accept a single argument, a string, and return a string.
4236 The buffer substring is passed to the first function in the list,
4237 and the return value of each function is passed to the next.
4238 As a special convention, point is set to the start of the buffer text
4239 being operated on (i.e., the first argument of `buffer-substring--filter')
4240 before these functions are called.")
4241 (make-obsolete-variable 'buffer-substring-filters
4242 'filter-buffer-substring-function "24.1")
4244 (defun filter-buffer-substring (beg end &optional delete)
4245 "Return the buffer substring between BEG and END, after filtering.
4246 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4248 This calls the function that `filter-buffer-substring-function' specifies
4249 \(passing the same three arguments that it received) to do the work,
4250 and returns whatever it does. The default function does no filtering,
4251 unless a hook has been set.
4253 Use `filter-buffer-substring' instead of `buffer-substring',
4254 `buffer-substring-no-properties', or `delete-and-extract-region' when
4255 you want to allow filtering to take place. For example, major or minor
4256 modes can use `filter-buffer-substring-function' to extract characters
4257 that are special to a buffer, and should not be copied into other buffers."
4258 (funcall filter-buffer-substring-function beg end delete))
4260 (defun buffer-substring--filter (beg end &optional delete)
4261 "Default function to use for `filter-buffer-substring-function'.
4262 Its arguments and return value are as specified for `filter-buffer-substring'.
4263 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4264 \(see `with-wrapper-hook' for details about wrapper hooks),
4265 and the abnormal hook `buffer-substring-filters'.
4266 No filtering is done unless a hook says to."
4267 (subr--with-wrapper-hook-no-warnings
4268 filter-buffer-substring-functions (beg end delete)
4269 (cond
4270 ((or delete buffer-substring-filters)
4271 (save-excursion
4272 (goto-char beg)
4273 (let ((string (if delete (delete-and-extract-region beg end)
4274 (buffer-substring beg end))))
4275 (dolist (filter buffer-substring-filters)
4276 (setq string (funcall filter string)))
4277 string)))
4279 (buffer-substring beg end)))))
4282 ;;;; Window system cut and paste hooks.
4284 (defvar interprogram-cut-function #'gui-select-text
4285 "Function to call to make a killed region available to other programs.
4286 Most window systems provide a facility for cutting and pasting
4287 text between different programs, such as the clipboard on X and
4288 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4290 This variable holds a function that Emacs calls whenever text is
4291 put in the kill ring, to make the new kill available to other
4292 programs. The function takes one argument, TEXT, which is a
4293 string containing the text which should be made available.")
4295 (defvar interprogram-paste-function #'gui-selection-value
4296 "Function to call to get text cut from other programs.
4297 Most window systems provide a facility for cutting and pasting
4298 text between different programs, such as the clipboard on X and
4299 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4301 This variable holds a function that Emacs calls to obtain text
4302 that other programs have provided for pasting. The function is
4303 called with no arguments. If no other program has provided text
4304 to paste, the function should return nil (in which case the
4305 caller, usually `current-kill', should use the top of the Emacs
4306 kill ring). If another program has provided text to paste, the
4307 function should return that text as a string (in which case the
4308 caller should put this string in the kill ring as the latest
4309 kill).
4311 The function may also return a list of strings if the window
4312 system supports multiple selections. The first string will be
4313 used as the pasted text, but the other will be placed in the kill
4314 ring for easy access via `yank-pop'.
4316 Note that the function should return a string only if a program
4317 other than Emacs has provided a string for pasting; if Emacs
4318 provided the most recent string, the function should return nil.
4319 If it is difficult to tell whether Emacs or some other program
4320 provided the current string, it is probably good enough to return
4321 nil if the string is equal (according to `string=') to the last
4322 text Emacs provided.")
4326 ;;;; The kill ring data structure.
4328 (defvar kill-ring nil
4329 "List of killed text sequences.
4330 Since the kill ring is supposed to interact nicely with cut-and-paste
4331 facilities offered by window systems, use of this variable should
4332 interact nicely with `interprogram-cut-function' and
4333 `interprogram-paste-function'. The functions `kill-new',
4334 `kill-append', and `current-kill' are supposed to implement this
4335 interaction; you may want to use them instead of manipulating the kill
4336 ring directly.")
4338 (defcustom kill-ring-max 60
4339 "Maximum length of kill ring before oldest elements are thrown away."
4340 :type 'integer
4341 :group 'killing)
4343 (defvar kill-ring-yank-pointer nil
4344 "The tail of the kill ring whose car is the last thing yanked.")
4346 (defcustom save-interprogram-paste-before-kill nil
4347 "Save existing clipboard text into kill ring before replacing it.
4348 A non-nil value ensures that Emacs kill operations do not
4349 irrevocably overwrite existing clipboard text by saving it to the
4350 `kill-ring' prior to the kill. Such text can subsequently be
4351 retrieved via \\[yank] \\[yank-pop]]."
4352 :type 'boolean
4353 :group 'killing
4354 :version "23.2")
4356 (defcustom kill-do-not-save-duplicates nil
4357 "Do not add a new string to `kill-ring' if it duplicates the last one.
4358 The comparison is done using `equal-including-properties'."
4359 :type 'boolean
4360 :group 'killing
4361 :version "23.2")
4363 (defun kill-new (string &optional replace)
4364 "Make STRING the latest kill in the kill ring.
4365 Set `kill-ring-yank-pointer' to point to it.
4366 If `interprogram-cut-function' is non-nil, apply it to STRING.
4367 Optional second argument REPLACE non-nil means that STRING will replace
4368 the front of the kill ring, rather than being added to the list.
4370 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4371 are non-nil, save the interprogram paste string(s) into `kill-ring' before
4372 STRING.
4374 When the yank handler has a non-nil PARAM element, the original STRING
4375 argument is not used by `insert-for-yank'. However, since Lisp code
4376 may access and use elements from the kill ring directly, the STRING
4377 argument should still be a \"useful\" string for such uses."
4378 (unless (and kill-do-not-save-duplicates
4379 ;; Due to text properties such as 'yank-handler that
4380 ;; can alter the contents to yank, comparison using
4381 ;; `equal' is unsafe.
4382 (equal-including-properties string (car kill-ring)))
4383 (if (fboundp 'menu-bar-update-yank-menu)
4384 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4385 (when save-interprogram-paste-before-kill
4386 (let ((interprogram-paste (and interprogram-paste-function
4387 (funcall interprogram-paste-function))))
4388 (when interprogram-paste
4389 (dolist (s (if (listp interprogram-paste)
4390 ;; Use `reverse' to avoid modifying external data.
4391 (reverse interprogram-paste)
4392 (list interprogram-paste)))
4393 (unless (and kill-do-not-save-duplicates
4394 (equal-including-properties s (car kill-ring)))
4395 (push s kill-ring))))))
4396 (unless (and kill-do-not-save-duplicates
4397 (equal-including-properties string (car kill-ring)))
4398 (if (and replace kill-ring)
4399 (setcar kill-ring string)
4400 (let ((history-delete-duplicates nil))
4401 (add-to-history 'kill-ring string kill-ring-max t))))
4402 (setq kill-ring-yank-pointer kill-ring)
4403 (if interprogram-cut-function
4404 (funcall interprogram-cut-function string)))
4406 ;; It has been argued that this should work like `self-insert-command'
4407 ;; which merges insertions in `buffer-undo-list' in groups of 20
4408 ;; (hard-coded in `undo-auto-amalgamate').
4409 (defcustom kill-append-merge-undo nil
4410 "Amalgamate appending kills with the last kill for undo.
4411 When non-nil, appending or prepending text to the last kill makes
4412 \\[undo] restore both pieces of text simultaneously."
4413 :type 'boolean
4414 :group 'killing
4415 :version "25.1")
4417 (defun kill-append (string before-p)
4418 "Append STRING to the end of the latest kill in the kill ring.
4419 If BEFORE-P is non-nil, prepend STRING to the kill instead.
4420 If `interprogram-cut-function' is non-nil, call it with the
4421 resulting kill.
4422 If `kill-append-merge-undo' is non-nil, remove the last undo
4423 boundary in the current buffer."
4424 (let ((cur (car kill-ring)))
4425 (kill-new (if before-p (concat string cur) (concat cur string))
4426 (or (string= cur "")
4427 (null (get-text-property 0 'yank-handler cur)))))
4428 (when (and kill-append-merge-undo (not buffer-read-only))
4429 (let ((prev buffer-undo-list)
4430 (next (cdr buffer-undo-list)))
4431 ;; Find the next undo boundary.
4432 (while (car next)
4433 (pop next)
4434 (pop prev))
4435 ;; Remove this undo boundary.
4436 (when prev
4437 (setcdr prev (cdr next))))))
4439 (defcustom yank-pop-change-selection nil
4440 "Whether rotating the kill ring changes the window system selection.
4441 If non-nil, whenever the kill ring is rotated (usually via the
4442 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4443 to copy the new kill to the window system selection."
4444 :type 'boolean
4445 :group 'killing
4446 :version "23.1")
4448 (defun current-kill (n &optional do-not-move)
4449 "Rotate the yanking point by N places, and then return that kill.
4450 If N is zero and `interprogram-paste-function' is set to a
4451 function that returns a string or a list of strings, and if that
4452 function doesn't return nil, then that string (or list) is added
4453 to the front of the kill ring and the string (or first string in
4454 the list) is returned as the latest kill.
4456 If N is not zero, and if `yank-pop-change-selection' is
4457 non-nil, use `interprogram-cut-function' to transfer the
4458 kill at the new yank point into the window system selection.
4460 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4461 move the yanking point; just return the Nth kill forward."
4463 (let ((interprogram-paste (and (= n 0)
4464 interprogram-paste-function
4465 (funcall interprogram-paste-function))))
4466 (if interprogram-paste
4467 (progn
4468 ;; Disable the interprogram cut function when we add the new
4469 ;; text to the kill ring, so Emacs doesn't try to own the
4470 ;; selection, with identical text.
4471 ;; Also disable the interprogram paste function, so that
4472 ;; `kill-new' doesn't call it repeatedly.
4473 (let ((interprogram-cut-function nil)
4474 (interprogram-paste-function nil))
4475 (if (listp interprogram-paste)
4476 ;; Use `reverse' to avoid modifying external data.
4477 (mapc #'kill-new (reverse interprogram-paste))
4478 (kill-new interprogram-paste)))
4479 (car kill-ring))
4480 (or kill-ring (error "Kill ring is empty"))
4481 (let ((ARGth-kill-element
4482 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4483 (length kill-ring))
4484 kill-ring)))
4485 (unless do-not-move
4486 (setq kill-ring-yank-pointer ARGth-kill-element)
4487 (when (and yank-pop-change-selection
4488 (> n 0)
4489 interprogram-cut-function)
4490 (funcall interprogram-cut-function (car ARGth-kill-element))))
4491 (car ARGth-kill-element)))))
4495 ;;;; Commands for manipulating the kill ring.
4497 (defcustom kill-read-only-ok nil
4498 "Non-nil means don't signal an error for killing read-only text."
4499 :type 'boolean
4500 :group 'killing)
4502 (defun kill-region (beg end &optional region)
4503 "Kill (\"cut\") text between point and mark.
4504 This deletes the text from the buffer and saves it in the kill ring.
4505 The command \\[yank] can retrieve it from there.
4506 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4508 If you want to append the killed region to the last killed text,
4509 use \\[append-next-kill] before \\[kill-region].
4511 Any command that calls this function is a \"kill command\".
4512 If the previous command was also a kill command,
4513 the text killed this time appends to the text killed last time
4514 to make one entry in the kill ring.
4516 The killed text is filtered by `filter-buffer-substring' before it is
4517 saved in the kill ring, so the actual saved text might be different
4518 from what was killed.
4520 If the buffer is read-only, Emacs will beep and refrain from deleting
4521 the text, but put the text in the kill ring anyway. This means that
4522 you can use the killing commands to copy text from a read-only buffer.
4524 Lisp programs should use this function for killing text.
4525 (To delete text, use `delete-region'.)
4526 Supply two arguments, character positions BEG and END indicating the
4527 stretch of text to be killed. If the optional argument REGION is
4528 non-nil, the function ignores BEG and END, and kills the current
4529 region instead."
4530 ;; Pass mark first, then point, because the order matters when
4531 ;; calling `kill-append'.
4532 (interactive (list (mark) (point) 'region))
4533 (unless (and beg end)
4534 (user-error "The mark is not set now, so there is no region"))
4535 (condition-case nil
4536 (let ((string (if region
4537 (funcall region-extract-function 'delete)
4538 (filter-buffer-substring beg end 'delete))))
4539 (when string ;STRING is nil if BEG = END
4540 ;; Add that string to the kill ring, one way or another.
4541 (if (eq last-command 'kill-region)
4542 (kill-append string (< end beg))
4543 (kill-new string)))
4544 (when (or string (eq last-command 'kill-region))
4545 (setq this-command 'kill-region))
4546 (setq deactivate-mark t)
4547 nil)
4548 ((buffer-read-only text-read-only)
4549 ;; The code above failed because the buffer, or some of the characters
4550 ;; in the region, are read-only.
4551 ;; We should beep, in case the user just isn't aware of this.
4552 ;; However, there's no harm in putting
4553 ;; the region's text in the kill ring, anyway.
4554 (copy-region-as-kill beg end region)
4555 ;; Set this-command now, so it will be set even if we get an error.
4556 (setq this-command 'kill-region)
4557 ;; This should barf, if appropriate, and give us the correct error.
4558 (if kill-read-only-ok
4559 (progn (message "Read only text copied to kill ring") nil)
4560 ;; Signal an error if the buffer is read-only.
4561 (barf-if-buffer-read-only)
4562 ;; If the buffer isn't read-only, the text is.
4563 (signal 'text-read-only (list (current-buffer)))))))
4565 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4566 ;; to get two copies of the text when the user accidentally types M-w and
4567 ;; then corrects it with the intended C-w.
4568 (defun copy-region-as-kill (beg end &optional region)
4569 "Save the region as if killed, but don't kill it.
4570 In Transient Mark mode, deactivate the mark.
4571 If `interprogram-cut-function' is non-nil, also save the text for a window
4572 system cut and paste.
4574 The copied text is filtered by `filter-buffer-substring' before it is
4575 saved in the kill ring, so the actual saved text might be different
4576 from what was in the buffer.
4578 When called from Lisp, save in the kill ring the stretch of text
4579 between BEG and END, unless the optional argument REGION is
4580 non-nil, in which case ignore BEG and END, and save the current
4581 region instead.
4583 This command's old key binding has been given to `kill-ring-save'."
4584 ;; Pass mark first, then point, because the order matters when
4585 ;; calling `kill-append'.
4586 (interactive (list (mark) (point)
4587 (prefix-numeric-value current-prefix-arg)))
4588 (let ((str (if region
4589 (funcall region-extract-function nil)
4590 (filter-buffer-substring beg end))))
4591 (if (eq last-command 'kill-region)
4592 (kill-append str (< end beg))
4593 (kill-new str)))
4594 (setq deactivate-mark t)
4595 nil)
4597 (defun kill-ring-save (beg end &optional region)
4598 "Save the region as if killed, but don't kill it.
4599 In Transient Mark mode, deactivate the mark.
4600 If `interprogram-cut-function' is non-nil, also save the text for a window
4601 system cut and paste.
4603 If you want to append the killed line to the last killed text,
4604 use \\[append-next-kill] before \\[kill-ring-save].
4606 The copied text is filtered by `filter-buffer-substring' before it is
4607 saved in the kill ring, so the actual saved text might be different
4608 from what was in the buffer.
4610 When called from Lisp, save in the kill ring the stretch of text
4611 between BEG and END, unless the optional argument REGION is
4612 non-nil, in which case ignore BEG and END, and save the current
4613 region instead.
4615 This command is similar to `copy-region-as-kill', except that it gives
4616 visual feedback indicating the extent of the region being copied."
4617 ;; Pass mark first, then point, because the order matters when
4618 ;; calling `kill-append'.
4619 (interactive (list (mark) (point)
4620 (prefix-numeric-value current-prefix-arg)))
4621 (copy-region-as-kill beg end region)
4622 ;; This use of called-interactively-p is correct because the code it
4623 ;; controls just gives the user visual feedback.
4624 (if (called-interactively-p 'interactive)
4625 (indicate-copied-region)))
4627 (defun indicate-copied-region (&optional message-len)
4628 "Indicate that the region text has been copied interactively.
4629 If the mark is visible in the selected window, blink the cursor
4630 between point and mark if there is currently no active region
4631 highlighting.
4633 If the mark lies outside the selected window, display an
4634 informative message containing a sample of the copied text. The
4635 optional argument MESSAGE-LEN, if non-nil, specifies the length
4636 of this sample text; it defaults to 40."
4637 (let ((mark (mark t))
4638 (point (point))
4639 ;; Inhibit quitting so we can make a quit here
4640 ;; look like a C-g typed as a command.
4641 (inhibit-quit t))
4642 (if (pos-visible-in-window-p mark (selected-window))
4643 ;; Swap point-and-mark quickly so as to show the region that
4644 ;; was selected. Don't do it if the region is highlighted.
4645 (unless (and (region-active-p)
4646 (face-background 'region))
4647 ;; Swap point and mark.
4648 (set-marker (mark-marker) (point) (current-buffer))
4649 (goto-char mark)
4650 (sit-for blink-matching-delay)
4651 ;; Swap back.
4652 (set-marker (mark-marker) mark (current-buffer))
4653 (goto-char point)
4654 ;; If user quit, deactivate the mark
4655 ;; as C-g would as a command.
4656 (and quit-flag (region-active-p)
4657 (deactivate-mark)))
4658 (let ((len (min (abs (- mark point))
4659 (or message-len 40))))
4660 (if (< point mark)
4661 ;; Don't say "killed"; that is misleading.
4662 (message "Saved text until \"%s\""
4663 (buffer-substring-no-properties (- mark len) mark))
4664 (message "Saved text from \"%s\""
4665 (buffer-substring-no-properties mark (+ mark len))))))))
4667 (defun append-next-kill (&optional interactive)
4668 "Cause following command, if it kills, to add to previous kill.
4669 If the next command kills forward from point, the kill is
4670 appended to the previous killed text. If the command kills
4671 backward, the kill is prepended. Kill commands that act on the
4672 region, such as `kill-region', are regarded as killing forward if
4673 point is after mark, and killing backward if point is before
4674 mark.
4676 If the next command is not a kill command, `append-next-kill' has
4677 no effect.
4679 The argument is used for internal purposes; do not supply one."
4680 (interactive "p")
4681 ;; We don't use (interactive-p), since that breaks kbd macros.
4682 (if interactive
4683 (progn
4684 (setq this-command 'kill-region)
4685 (message "If the next command is a kill, it will append"))
4686 (setq last-command 'kill-region)))
4688 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4689 "Character set that matches bidirectional formatting control characters.")
4691 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4692 "Character set that matches any character except bidirectional controls.")
4694 (defun squeeze-bidi-context-1 (from to category replacement)
4695 "A subroutine of `squeeze-bidi-context'.
4696 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4697 (let ((pt (copy-marker from))
4698 (limit (copy-marker to))
4699 (old-pt 0)
4700 lim1)
4701 (setq lim1 limit)
4702 (goto-char pt)
4703 (while (< pt limit)
4704 (if (> pt old-pt)
4705 (move-marker lim1
4706 (save-excursion
4707 ;; L and R categories include embedding and
4708 ;; override controls, but we don't want to
4709 ;; replace them, because that might change
4710 ;; the visual order. Likewise with PDF and
4711 ;; isolate controls.
4712 (+ pt (skip-chars-forward
4713 bidi-directional-non-controls-chars
4714 limit)))))
4715 ;; Replace any run of non-RTL characters by a single LRM.
4716 (if (null (re-search-forward category lim1 t))
4717 ;; No more characters of CATEGORY, we are done.
4718 (setq pt limit)
4719 (replace-match replacement nil t)
4720 (move-marker pt (point)))
4721 (setq old-pt pt)
4722 ;; Skip directional controls, if any.
4723 (move-marker
4724 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4726 (defun squeeze-bidi-context (from to)
4727 "Replace characters between FROM and TO while keeping bidi context.
4729 This function replaces the region of text with as few characters
4730 as possible, while preserving the effect that region will have on
4731 bidirectional display before and after the region."
4732 (let ((start (set-marker (make-marker)
4733 (if (> from 0) from (+ (point-max) from))))
4734 (end (set-marker (make-marker) to))
4735 ;; This is for when they copy text with read-only text
4736 ;; properties.
4737 (inhibit-read-only t))
4738 (if (null (marker-position end))
4739 (setq end (point-max-marker)))
4740 ;; Replace each run of non-RTL characters with a single LRM.
4741 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4742 ;; Replace each run of non-LTR characters with a single RLM. Note
4743 ;; that the \cR category includes both the Arabic Letter (AL) and
4744 ;; R characters; here we ignore the distinction between them,
4745 ;; because that distinction only affects Arabic Number (AN)
4746 ;; characters, which are weak and don't affect the reordering.
4747 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4749 (defun line-substring-with-bidi-context (start end &optional no-properties)
4750 "Return buffer text between START and END with its bidi context.
4752 START and END are assumed to belong to the same physical line
4753 of buffer text. This function prepends and appends to the text
4754 between START and END bidi control characters that preserve the
4755 visual order of that text when it is inserted at some other place."
4756 (if (or (< start (point-min))
4757 (> end (point-max)))
4758 (signal 'args-out-of-range (list (current-buffer) start end)))
4759 (let ((buf (current-buffer))
4760 substr para-dir from to)
4761 (save-excursion
4762 (goto-char start)
4763 (setq para-dir (current-bidi-paragraph-direction))
4764 (setq from (line-beginning-position)
4765 to (line-end-position))
4766 (goto-char from)
4767 ;; If we don't have any mixed directional characters in the
4768 ;; entire line, we can just copy the substring without adding
4769 ;; any context.
4770 (if (or (looking-at-p "\\CR*$")
4771 (looking-at-p "\\CL*$"))
4772 (setq substr (if no-properties
4773 (buffer-substring-no-properties start end)
4774 (buffer-substring start end)))
4775 (setq substr
4776 (with-temp-buffer
4777 (if no-properties
4778 (insert-buffer-substring-no-properties buf from to)
4779 (insert-buffer-substring buf from to))
4780 (squeeze-bidi-context 1 (1+ (- start from)))
4781 (squeeze-bidi-context (- end to) nil)
4782 (buffer-substring 1 (point-max)))))
4784 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4785 ;; (1) force the string to have the same base embedding
4786 ;; direction as the paragraph direction at the source, no matter
4787 ;; what is the paragraph direction at destination; and (2) avoid
4788 ;; affecting the visual order of the surrounding text at
4789 ;; destination if there are characters of different
4790 ;; directionality there.
4791 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4792 substr "\x2069"))))
4794 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4795 "Return portion of current buffer between START and END with bidi context.
4797 This function works similar to `buffer-substring', but it prepends and
4798 appends to the text bidi directional control characters necessary to
4799 preserve the visual appearance of the text if it is inserted at another
4800 place. This is useful when the buffer substring includes bidirectional
4801 text and control characters that cause non-trivial reordering on display.
4802 If copied verbatim, such text can have a very different visual appearance,
4803 and can also change the visual appearance of the surrounding text at the
4804 destination of the copy.
4806 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4807 the text properties."
4808 (let (line-end substr)
4809 (if (or (< start (point-min))
4810 (> end (point-max)))
4811 (signal 'args-out-of-range (list (current-buffer) start end)))
4812 (save-excursion
4813 (goto-char start)
4814 (setq line-end (min end (line-end-position)))
4815 (while (< start end)
4816 (setq substr
4817 (concat substr
4818 (if substr "\n" "")
4819 (line-substring-with-bidi-context start line-end
4820 no-properties)))
4821 (forward-line 1)
4822 (setq start (point))
4823 (setq line-end (min end (line-end-position))))
4824 substr)))
4826 ;; Yanking.
4828 (defcustom yank-handled-properties
4829 '((font-lock-face . yank-handle-font-lock-face-property)
4830 (category . yank-handle-category-property))
4831 "List of special text property handling conditions for yanking.
4832 Each element should have the form (PROP . FUN), where PROP is a
4833 property symbol and FUN is a function. When the `yank' command
4834 inserts text into the buffer, it scans the inserted text for
4835 stretches of text that have `eq' values of the text property
4836 PROP; for each such stretch of text, FUN is called with three
4837 arguments: the property's value in that text, and the start and
4838 end positions of the text.
4840 This is done prior to removing the properties specified by
4841 `yank-excluded-properties'."
4842 :group 'killing
4843 :type '(repeat (cons (symbol :tag "property symbol")
4844 function))
4845 :version "24.3")
4847 ;; This is actually used in subr.el but defcustom does not work there.
4848 (defcustom yank-excluded-properties
4849 '(category field follow-link fontified font-lock-face help-echo
4850 intangible invisible keymap local-map mouse-face read-only
4851 yank-handler)
4852 "Text properties to discard when yanking.
4853 The value should be a list of text properties to discard or t,
4854 which means to discard all text properties.
4856 See also `yank-handled-properties'."
4857 :type '(choice (const :tag "All" t) (repeat symbol))
4858 :group 'killing
4859 :version "24.3")
4861 (defvar yank-window-start nil)
4862 (defvar yank-undo-function nil
4863 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4864 Function is called with two parameters, START and END corresponding to
4865 the value of the mark and point; it is guaranteed that START <= END.
4866 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4868 (defun yank-pop (&optional arg)
4869 "Replace just-yanked stretch of killed text with a different stretch.
4870 This command is allowed only immediately after a `yank' or a `yank-pop'.
4871 At such a time, the region contains a stretch of reinserted
4872 previously-killed text. `yank-pop' deletes that text and inserts in its
4873 place a different stretch of killed text.
4875 With no argument, the previous kill is inserted.
4876 With argument N, insert the Nth previous kill.
4877 If N is negative, this is a more recent kill.
4879 The sequence of kills wraps around, so that after the oldest one
4880 comes the newest one.
4882 This command honors the `yank-handled-properties' and
4883 `yank-excluded-properties' variables, and the `yank-handler' text
4884 property, in the way that `yank' does."
4885 (interactive "*p")
4886 (if (not (eq last-command 'yank))
4887 (user-error "Previous command was not a yank"))
4888 (setq this-command 'yank)
4889 (unless arg (setq arg 1))
4890 (let ((inhibit-read-only t)
4891 (before (< (point) (mark t))))
4892 (if before
4893 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4894 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4895 (setq yank-undo-function nil)
4896 (set-marker (mark-marker) (point) (current-buffer))
4897 (insert-for-yank (current-kill arg))
4898 ;; Set the window start back where it was in the yank command,
4899 ;; if possible.
4900 (set-window-start (selected-window) yank-window-start t)
4901 (if before
4902 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4903 ;; It is cleaner to avoid activation, even though the command
4904 ;; loop would deactivate the mark because we inserted text.
4905 (goto-char (prog1 (mark t)
4906 (set-marker (mark-marker) (point) (current-buffer))))))
4907 nil)
4909 (defun yank (&optional arg)
4910 "Reinsert (\"paste\") the last stretch of killed text.
4911 More precisely, reinsert the most recent kill, which is the
4912 stretch of killed text most recently killed OR yanked. Put point
4913 at the end, and set mark at the beginning without activating it.
4914 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4915 With argument N, reinsert the Nth most recent kill.
4917 This command honors the `yank-handled-properties' and
4918 `yank-excluded-properties' variables, and the `yank-handler' text
4919 property, as described below.
4921 Properties listed in `yank-handled-properties' are processed,
4922 then those listed in `yank-excluded-properties' are discarded.
4924 If STRING has a non-nil `yank-handler' property anywhere, the
4925 normal insert behavior is altered, and instead, for each contiguous
4926 segment of STRING that has a given value of the `yank-handler'
4927 property, that value is used as follows:
4929 The value of a `yank-handler' property must be a list of one to four
4930 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4931 FUNCTION, if non-nil, should be a function of one argument (the
4932 object to insert); FUNCTION is called instead of `insert'.
4933 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4934 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4935 PARAM may be a list of strings to insert as a rectangle). If PARAM
4936 is nil, then the current segment of STRING is used.
4937 If NOEXCLUDE is present and non-nil, the normal removal of
4938 `yank-excluded-properties' is not performed; instead FUNCTION is
4939 responsible for the removal. This may be necessary if FUNCTION
4940 adjusts point before or after inserting the object.
4941 UNDO, if present and non-nil, should be a function to be called
4942 by `yank-pop' to undo the insertion of the current PARAM. It is
4943 given two arguments, the start and end of the region. FUNCTION
4944 may set `yank-undo-function' to override UNDO.
4946 See also the command `yank-pop' (\\[yank-pop])."
4947 (interactive "*P")
4948 (setq yank-window-start (window-start))
4949 ;; If we don't get all the way thru, make last-command indicate that
4950 ;; for the following command.
4951 (setq this-command t)
4952 (push-mark)
4953 (insert-for-yank (current-kill (cond
4954 ((listp arg) 0)
4955 ((eq arg '-) -2)
4956 (t (1- arg)))))
4957 (if (consp arg)
4958 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4959 ;; It is cleaner to avoid activation, even though the command
4960 ;; loop would deactivate the mark because we inserted text.
4961 (goto-char (prog1 (mark t)
4962 (set-marker (mark-marker) (point) (current-buffer)))))
4963 ;; If we do get all the way thru, make this-command indicate that.
4964 (if (eq this-command t)
4965 (setq this-command 'yank))
4966 nil)
4968 (defun rotate-yank-pointer (arg)
4969 "Rotate the yanking point in the kill ring.
4970 With ARG, rotate that many kills forward (or backward, if negative)."
4971 (interactive "p")
4972 (current-kill arg))
4974 ;; Some kill commands.
4976 ;; Internal subroutine of delete-char
4977 (defun kill-forward-chars (arg)
4978 (if (listp arg) (setq arg (car arg)))
4979 (if (eq arg '-) (setq arg -1))
4980 (kill-region (point) (+ (point) arg)))
4982 ;; Internal subroutine of backward-delete-char
4983 (defun kill-backward-chars (arg)
4984 (if (listp arg) (setq arg (car arg)))
4985 (if (eq arg '-) (setq arg -1))
4986 (kill-region (point) (- (point) arg)))
4988 (defcustom backward-delete-char-untabify-method 'untabify
4989 "The method for untabifying when deleting backward.
4990 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4991 `hungry' -- delete all whitespace, both tabs and spaces;
4992 `all' -- delete all whitespace, including tabs, spaces and newlines;
4993 nil -- just delete one character."
4994 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4995 :version "20.3"
4996 :group 'killing)
4998 (defun backward-delete-char-untabify (arg &optional killp)
4999 "Delete characters backward, changing tabs into spaces.
5000 The exact behavior depends on `backward-delete-char-untabify-method'.
5001 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
5002 Interactively, ARG is the prefix arg (default 1)
5003 and KILLP is t if a prefix arg was specified."
5004 (interactive "*p\nP")
5005 (when (eq backward-delete-char-untabify-method 'untabify)
5006 (let ((count arg))
5007 (save-excursion
5008 (while (and (> count 0) (not (bobp)))
5009 (if (= (preceding-char) ?\t)
5010 (let ((col (current-column)))
5011 (forward-char -1)
5012 (setq col (- col (current-column)))
5013 (insert-char ?\s col)
5014 (delete-char 1)))
5015 (forward-char -1)
5016 (setq count (1- count))))))
5017 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
5018 ((eq backward-delete-char-untabify-method 'all)
5019 " \t\n\r")))
5020 (n (if skip
5021 (let* ((oldpt (point))
5022 (wh (- oldpt (save-excursion
5023 (skip-chars-backward skip)
5024 (constrain-to-field nil oldpt)))))
5025 (+ arg (if (zerop wh) 0 (1- wh))))
5026 arg)))
5027 ;; Avoid warning about delete-backward-char
5028 (with-no-warnings (delete-backward-char n killp))))
5030 (defun zap-to-char (arg char)
5031 "Kill up to and including ARGth occurrence of CHAR.
5032 Case is ignored if `case-fold-search' is non-nil in the current buffer.
5033 Goes backward if ARG is negative; error if CHAR not found."
5034 (interactive (list (prefix-numeric-value current-prefix-arg)
5035 (read-char "Zap to char: " t)))
5036 ;; Avoid "obsolete" warnings for translation-table-for-input.
5037 (with-no-warnings
5038 (if (char-table-p translation-table-for-input)
5039 (setq char (or (aref translation-table-for-input char) char))))
5040 (kill-region (point) (progn
5041 (search-forward (char-to-string char) nil nil arg)
5042 (point))))
5044 ;; kill-line and its subroutines.
5046 (defcustom kill-whole-line nil
5047 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
5048 :type 'boolean
5049 :group 'killing)
5051 (defun kill-line (&optional arg)
5052 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5053 With prefix argument ARG, kill that many lines from point.
5054 Negative arguments kill lines backward.
5055 With zero argument, kills the text before point on the current line.
5057 When calling from a program, nil means \"no arg\",
5058 a number counts as a prefix arg.
5060 To kill a whole line, when point is not at the beginning, type \
5061 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5063 If `show-trailing-whitespace' is non-nil, this command will just
5064 kill the rest of the current line, even if there are no nonblanks
5065 there.
5067 If option `kill-whole-line' is non-nil, then this command kills the whole line
5068 including its terminating newline, when used at the beginning of a line
5069 with no argument. As a consequence, you can always kill a whole line
5070 by typing \\[move-beginning-of-line] \\[kill-line].
5072 If you want to append the killed line to the last killed text,
5073 use \\[append-next-kill] before \\[kill-line].
5075 If the buffer is read-only, Emacs will beep and refrain from deleting
5076 the line, but put the line in the kill ring anyway. This means that
5077 you can use this command to copy text from a read-only buffer.
5078 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5079 even beep.)"
5080 (interactive "P")
5081 (kill-region (point)
5082 ;; It is better to move point to the other end of the kill
5083 ;; before killing. That way, in a read-only buffer, point
5084 ;; moves across the text that is copied to the kill ring.
5085 ;; The choice has no effect on undo now that undo records
5086 ;; the value of point from before the command was run.
5087 (progn
5088 (if arg
5089 (forward-visible-line (prefix-numeric-value arg))
5090 (if (eobp)
5091 (signal 'end-of-buffer nil))
5092 (let ((end
5093 (save-excursion
5094 (end-of-visible-line) (point))))
5095 (if (or (save-excursion
5096 ;; If trailing whitespace is visible,
5097 ;; don't treat it as nothing.
5098 (unless show-trailing-whitespace
5099 (skip-chars-forward " \t" end))
5100 (= (point) end))
5101 (and kill-whole-line (bolp)))
5102 (forward-visible-line 1)
5103 (goto-char end))))
5104 (point))))
5106 (defun kill-whole-line (&optional arg)
5107 "Kill current line.
5108 With prefix ARG, kill that many lines starting from the current line.
5109 If ARG is negative, kill backward. Also kill the preceding newline.
5110 \(This is meant to make \\[repeat] work well with negative arguments.)
5111 If ARG is zero, kill current line but exclude the trailing newline."
5112 (interactive "p")
5113 (or arg (setq arg 1))
5114 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5115 (signal 'end-of-buffer nil))
5116 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5117 (signal 'beginning-of-buffer nil))
5118 (unless (eq last-command 'kill-region)
5119 (kill-new "")
5120 (setq last-command 'kill-region))
5121 (cond ((zerop arg)
5122 ;; We need to kill in two steps, because the previous command
5123 ;; could have been a kill command, in which case the text
5124 ;; before point needs to be prepended to the current kill
5125 ;; ring entry and the text after point appended. Also, we
5126 ;; need to use save-excursion to avoid copying the same text
5127 ;; twice to the kill ring in read-only buffers.
5128 (save-excursion
5129 (kill-region (point) (progn (forward-visible-line 0) (point))))
5130 (kill-region (point) (progn (end-of-visible-line) (point))))
5131 ((< arg 0)
5132 (save-excursion
5133 (kill-region (point) (progn (end-of-visible-line) (point))))
5134 (kill-region (point)
5135 (progn (forward-visible-line (1+ arg))
5136 (unless (bobp) (backward-char))
5137 (point))))
5139 (save-excursion
5140 (kill-region (point) (progn (forward-visible-line 0) (point))))
5141 (kill-region (point)
5142 (progn (forward-visible-line arg) (point))))))
5144 (defun forward-visible-line (arg)
5145 "Move forward by ARG lines, ignoring currently invisible newlines only.
5146 If ARG is negative, move backward -ARG lines.
5147 If ARG is zero, move to the beginning of the current line."
5148 (condition-case nil
5149 (if (> arg 0)
5150 (progn
5151 (while (> arg 0)
5152 (or (zerop (forward-line 1))
5153 (signal 'end-of-buffer nil))
5154 ;; If the newline we just skipped is invisible,
5155 ;; don't count it.
5156 (let ((prop
5157 (get-char-property (1- (point)) 'invisible)))
5158 (if (if (eq buffer-invisibility-spec t)
5159 prop
5160 (or (memq prop buffer-invisibility-spec)
5161 (assq prop buffer-invisibility-spec)))
5162 (setq arg (1+ arg))))
5163 (setq arg (1- arg)))
5164 ;; If invisible text follows, and it is a number of complete lines,
5165 ;; skip it.
5166 (let ((opoint (point)))
5167 (while (and (not (eobp))
5168 (let ((prop
5169 (get-char-property (point) 'invisible)))
5170 (if (eq buffer-invisibility-spec t)
5171 prop
5172 (or (memq prop buffer-invisibility-spec)
5173 (assq prop buffer-invisibility-spec)))))
5174 (goto-char
5175 (if (get-text-property (point) 'invisible)
5176 (or (next-single-property-change (point) 'invisible)
5177 (point-max))
5178 (next-overlay-change (point)))))
5179 (unless (bolp)
5180 (goto-char opoint))))
5181 (let ((first t))
5182 (while (or first (<= arg 0))
5183 (if first
5184 (beginning-of-line)
5185 (or (zerop (forward-line -1))
5186 (signal 'beginning-of-buffer nil)))
5187 ;; If the newline we just moved to is invisible,
5188 ;; don't count it.
5189 (unless (bobp)
5190 (let ((prop
5191 (get-char-property (1- (point)) 'invisible)))
5192 (unless (if (eq buffer-invisibility-spec t)
5193 prop
5194 (or (memq prop buffer-invisibility-spec)
5195 (assq prop buffer-invisibility-spec)))
5196 (setq arg (1+ arg)))))
5197 (setq first nil))
5198 ;; If invisible text follows, and it is a number of complete lines,
5199 ;; skip it.
5200 (let ((opoint (point)))
5201 (while (and (not (bobp))
5202 (let ((prop
5203 (get-char-property (1- (point)) 'invisible)))
5204 (if (eq buffer-invisibility-spec t)
5205 prop
5206 (or (memq prop buffer-invisibility-spec)
5207 (assq prop buffer-invisibility-spec)))))
5208 (goto-char
5209 (if (get-text-property (1- (point)) 'invisible)
5210 (or (previous-single-property-change (point) 'invisible)
5211 (point-min))
5212 (previous-overlay-change (point)))))
5213 (unless (bolp)
5214 (goto-char opoint)))))
5215 ((beginning-of-buffer end-of-buffer)
5216 nil)))
5218 (defun end-of-visible-line ()
5219 "Move to end of current visible line."
5220 (end-of-line)
5221 ;; If the following character is currently invisible,
5222 ;; skip all characters with that same `invisible' property value,
5223 ;; then find the next newline.
5224 (while (and (not (eobp))
5225 (save-excursion
5226 (skip-chars-forward "^\n")
5227 (let ((prop
5228 (get-char-property (point) 'invisible)))
5229 (if (eq buffer-invisibility-spec t)
5230 prop
5231 (or (memq prop buffer-invisibility-spec)
5232 (assq prop buffer-invisibility-spec))))))
5233 (skip-chars-forward "^\n")
5234 (if (get-text-property (point) 'invisible)
5235 (goto-char (or (next-single-property-change (point) 'invisible)
5236 (point-max)))
5237 (goto-char (next-overlay-change (point))))
5238 (end-of-line)))
5240 (defun kill-current-buffer ()
5241 "Kill the current buffer.
5242 When called in the minibuffer, get out of the minibuffer
5243 using `abort-recursive-edit'.
5245 This is like `kill-this-buffer', but it doesn't have to be invoked
5246 via the menu bar, and pays no attention to the menu-bar's frame."
5247 (interactive)
5248 (let ((frame (selected-frame)))
5249 (if (and (frame-live-p frame)
5250 (not (window-minibuffer-p (frame-selected-window frame))))
5251 (kill-buffer (current-buffer))
5252 (abort-recursive-edit))))
5255 (defun insert-buffer (buffer)
5256 "Insert after point the contents of BUFFER.
5257 Puts mark after the inserted text.
5258 BUFFER may be a buffer or a buffer name."
5259 (declare (interactive-only insert-buffer-substring))
5260 (interactive
5261 (list
5262 (progn
5263 (barf-if-buffer-read-only)
5264 (read-buffer "Insert buffer: "
5265 (if (eq (selected-window) (next-window))
5266 (other-buffer (current-buffer))
5267 (window-buffer (next-window)))
5268 t))))
5269 (push-mark
5270 (save-excursion
5271 (insert-buffer-substring (get-buffer buffer))
5272 (point)))
5273 nil)
5275 (defun append-to-buffer (buffer start end)
5276 "Append to specified buffer the text of the region.
5277 It is inserted into that buffer before its point.
5279 When calling from a program, give three arguments:
5280 BUFFER (or buffer name), START and END.
5281 START and END specify the portion of the current buffer to be copied."
5282 (interactive
5283 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5284 (region-beginning) (region-end)))
5285 (let* ((oldbuf (current-buffer))
5286 (append-to (get-buffer-create buffer))
5287 (windows (get-buffer-window-list append-to t t))
5288 point)
5289 (save-excursion
5290 (with-current-buffer append-to
5291 (setq point (point))
5292 (barf-if-buffer-read-only)
5293 (insert-buffer-substring oldbuf start end)
5294 (dolist (window windows)
5295 (when (= (window-point window) point)
5296 (set-window-point window (point))))))))
5298 (defun prepend-to-buffer (buffer start end)
5299 "Prepend to specified buffer the text of the region.
5300 It is inserted into that buffer after its point.
5302 When calling from a program, give three arguments:
5303 BUFFER (or buffer name), START and END.
5304 START and END specify the portion of the current buffer to be copied."
5305 (interactive "BPrepend to buffer: \nr")
5306 (let ((oldbuf (current-buffer)))
5307 (with-current-buffer (get-buffer-create buffer)
5308 (barf-if-buffer-read-only)
5309 (save-excursion
5310 (insert-buffer-substring oldbuf start end)))))
5312 (defun copy-to-buffer (buffer start end)
5313 "Copy to specified buffer the text of the region.
5314 It is inserted into that buffer, replacing existing text there.
5316 When calling from a program, give three arguments:
5317 BUFFER (or buffer name), START and END.
5318 START and END specify the portion of the current buffer to be copied."
5319 (interactive "BCopy to buffer: \nr")
5320 (let ((oldbuf (current-buffer)))
5321 (with-current-buffer (get-buffer-create buffer)
5322 (barf-if-buffer-read-only)
5323 (erase-buffer)
5324 (save-excursion
5325 (insert-buffer-substring oldbuf start end)))))
5327 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5329 (defvar activate-mark-hook nil
5330 "Hook run when the mark becomes active.
5331 It is also run at the end of a command, if the mark is active and
5332 it is possible that the region may have changed.")
5334 (defvar deactivate-mark-hook nil
5335 "Hook run when the mark becomes inactive.")
5337 (defun mark (&optional force)
5338 "Return this buffer's mark value as integer, or nil if never set.
5340 In Transient Mark mode, this function signals an error if
5341 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5342 or the argument FORCE is non-nil, it disregards whether the mark
5343 is active, and returns an integer or nil in the usual way.
5345 If you are using this in an editing command, you are most likely making
5346 a mistake; see the documentation of `set-mark'."
5347 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5348 (marker-position (mark-marker))
5349 (signal 'mark-inactive nil)))
5351 ;; Behind display-selections-p.
5353 (defun deactivate-mark (&optional force)
5354 "Deactivate the mark.
5355 If Transient Mark mode is disabled, this function normally does
5356 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5358 Deactivating the mark sets `mark-active' to nil, updates the
5359 primary selection according to `select-active-regions', and runs
5360 `deactivate-mark-hook'.
5362 If Transient Mark mode was temporarily enabled, reset the value
5363 of the variable `transient-mark-mode'; if this causes Transient
5364 Mark mode to be disabled, don't change `mark-active' to nil or
5365 run `deactivate-mark-hook'."
5366 (when (or (region-active-p) force)
5367 (when (and (if (eq select-active-regions 'only)
5368 (eq (car-safe transient-mark-mode) 'only)
5369 select-active-regions)
5370 (region-active-p)
5371 (display-selections-p))
5372 ;; The var `saved-region-selection', if non-nil, is the text in
5373 ;; the region prior to the last command modifying the buffer.
5374 ;; Set the selection to that, or to the current region.
5375 (cond (saved-region-selection
5376 (if (gui-backend-selection-owner-p 'PRIMARY)
5377 (gui-set-selection 'PRIMARY saved-region-selection))
5378 (setq saved-region-selection nil))
5379 ;; If another program has acquired the selection, region
5380 ;; deactivation should not clobber it (Bug#11772).
5381 ((and (/= (region-beginning) (region-end))
5382 (or (gui-backend-selection-owner-p 'PRIMARY)
5383 (null (gui-backend-selection-exists-p 'PRIMARY))))
5384 (gui-set-selection 'PRIMARY
5385 (funcall region-extract-function nil)))))
5386 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5387 (cond
5388 ((eq (car-safe transient-mark-mode) 'only)
5389 (setq transient-mark-mode (cdr transient-mark-mode))
5390 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5391 (kill-local-variable 'transient-mark-mode)))
5392 ((eq transient-mark-mode 'lambda)
5393 (kill-local-variable 'transient-mark-mode)))
5394 (setq mark-active nil)
5395 (run-hooks 'deactivate-mark-hook)
5396 (redisplay--update-region-highlight (selected-window))))
5398 (defun activate-mark (&optional no-tmm)
5399 "Activate the mark.
5400 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5401 (when (mark t)
5402 (unless (region-active-p)
5403 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5404 (setq mark-active t)
5405 (unless (or transient-mark-mode no-tmm)
5406 (setq-local transient-mark-mode 'lambda))
5407 (run-hooks 'activate-mark-hook))))
5409 (defun set-mark (pos)
5410 "Set this buffer's mark to POS. Don't use this function!
5411 That is to say, don't use this function unless you want
5412 the user to see that the mark has moved, and you want the previous
5413 mark position to be lost.
5415 Normally, when a new mark is set, the old one should go on the stack.
5416 This is why most applications should use `push-mark', not `set-mark'.
5418 Novice Emacs Lisp programmers often try to use the mark for the wrong
5419 purposes. The mark saves a location for the user's convenience.
5420 Most editing commands should not alter the mark.
5421 To remember a location for internal use in the Lisp program,
5422 store it in a Lisp variable. Example:
5424 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5425 (if pos
5426 (progn
5427 (set-marker (mark-marker) pos (current-buffer))
5428 (activate-mark 'no-tmm))
5429 ;; Normally we never clear mark-active except in Transient Mark mode.
5430 ;; But when we actually clear out the mark value too, we must
5431 ;; clear mark-active in any mode.
5432 (deactivate-mark t)
5433 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5434 ;; it should never be nil if the mark is nil.
5435 (setq mark-active nil)
5436 (set-marker (mark-marker) nil)))
5438 (defun save-mark-and-excursion--save ()
5439 (cons
5440 (let ((mark (mark-marker)))
5441 (and (marker-position mark) (copy-marker mark)))
5442 mark-active))
5444 (defun save-mark-and-excursion--restore (saved-mark-info)
5445 (let ((saved-mark (car saved-mark-info))
5446 (omark (marker-position (mark-marker)))
5447 (nmark nil)
5448 (saved-mark-active (cdr saved-mark-info)))
5449 ;; Mark marker
5450 (if (null saved-mark)
5451 (set-marker (mark-marker) nil)
5452 (setf nmark (marker-position saved-mark))
5453 (set-marker (mark-marker) nmark)
5454 (set-marker saved-mark nil))
5455 ;; Mark active
5456 (let ((cur-mark-active mark-active))
5457 (setq mark-active saved-mark-active)
5458 ;; If mark is active now, and either was not active or was at a
5459 ;; different place, run the activate hook.
5460 (if saved-mark-active
5461 (when (or (not cur-mark-active)
5462 (not (eq omark nmark)))
5463 (run-hooks 'activate-mark-hook))
5464 ;; If mark has ceased to be active, run deactivate hook.
5465 (when cur-mark-active
5466 (run-hooks 'deactivate-mark-hook))))))
5468 (defmacro save-mark-and-excursion (&rest body)
5469 "Like `save-excursion', but also save and restore the mark state.
5470 This macro does what `save-excursion' did before Emacs 25.1."
5471 (declare (indent 0) (debug t))
5472 (let ((saved-marker-sym (make-symbol "saved-marker")))
5473 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5474 (unwind-protect
5475 (save-excursion ,@body)
5476 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5478 (defcustom use-empty-active-region nil
5479 "Whether \"region-aware\" commands should act on empty regions.
5480 If nil, region-aware commands treat the empty region as inactive.
5481 If non-nil, region-aware commands treat the region as active as
5482 long as the mark is active, even if the region is empty.
5484 Region-aware commands are those that act on the region if it is
5485 active and Transient Mark mode is enabled, and on the text near
5486 point otherwise."
5487 :type 'boolean
5488 :version "23.1"
5489 :group 'editing-basics)
5491 (defun use-region-p ()
5492 "Return t if the region is active and it is appropriate to act on it.
5493 This is used by commands that act specially on the region under
5494 Transient Mark mode.
5496 The return value is t if Transient Mark mode is enabled and the
5497 mark is active; furthermore, if `use-empty-active-region' is nil,
5498 the region must not be empty. Otherwise, the return value is nil.
5500 For some commands, it may be appropriate to ignore the value of
5501 `use-empty-active-region'; in that case, use `region-active-p'."
5502 (and (region-active-p)
5503 (or use-empty-active-region (> (region-end) (region-beginning)))))
5505 (defun region-active-p ()
5506 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5508 Some commands act specially on the region when Transient Mark
5509 mode is enabled. Usually, such commands should use
5510 `use-region-p' instead of this function, because `use-region-p'
5511 also checks the value of `use-empty-active-region'."
5512 (and transient-mark-mode mark-active
5513 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5514 ;; without the mark being set (e.g. bug#17324). We really should fix
5515 ;; that problem, but in the mean time, let's make sure we don't say the
5516 ;; region is active when there's no mark.
5517 (progn (cl-assert (mark)) t)))
5519 (defun region-bounds ()
5520 "Return the boundaries of the region as a pair of positions.
5521 Value is a list of cons cells of the form (START . END)."
5522 (funcall region-extract-function 'bounds))
5524 (defun region-noncontiguous-p ()
5525 "Return non-nil if the region contains several pieces.
5526 An example is a rectangular region handled as a list of
5527 separate contiguous regions for each line."
5528 (> (length (region-bounds)) 1))
5530 (defvar redisplay-unhighlight-region-function
5531 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5533 (defvar redisplay-highlight-region-function
5534 (lambda (start end window rol)
5535 (if (not (overlayp rol))
5536 (let ((nrol (make-overlay start end)))
5537 (funcall redisplay-unhighlight-region-function rol)
5538 (overlay-put nrol 'window window)
5539 (overlay-put nrol 'face 'region)
5540 ;; Normal priority so that a large region doesn't hide all the
5541 ;; overlays within it, but high secondary priority so that if it
5542 ;; ends/starts in the middle of a small overlay, that small overlay
5543 ;; won't hide the region's boundaries.
5544 (overlay-put nrol 'priority '(nil . 100))
5545 nrol)
5546 (unless (and (eq (overlay-buffer rol) (current-buffer))
5547 (eq (overlay-start rol) start)
5548 (eq (overlay-end rol) end))
5549 (move-overlay rol start end (current-buffer)))
5550 rol)))
5552 (defun redisplay--update-region-highlight (window)
5553 (let ((rol (window-parameter window 'internal-region-overlay)))
5554 (if (not (and (region-active-p)
5555 (or highlight-nonselected-windows
5556 (eq window (selected-window))
5557 (and (window-minibuffer-p)
5558 (eq window (minibuffer-selected-window))))))
5559 (funcall redisplay-unhighlight-region-function rol)
5560 (let* ((pt (window-point window))
5561 (mark (mark))
5562 (start (min pt mark))
5563 (end (max pt mark))
5564 (new
5565 (funcall redisplay-highlight-region-function
5566 start end window rol)))
5567 (unless (equal new rol)
5568 (set-window-parameter window 'internal-region-overlay
5569 new))))))
5571 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5572 "Hook run just before redisplay.
5573 It is called in each window that is to be redisplayed. It takes one argument,
5574 which is the window that will be redisplayed. When run, the `current-buffer'
5575 is set to the buffer displayed in that window.")
5577 (defun redisplay--pre-redisplay-functions (windows)
5578 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5579 (if (null windows)
5580 (with-current-buffer (window-buffer (selected-window))
5581 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5582 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5583 (with-current-buffer (window-buffer win)
5584 (run-hook-with-args 'pre-redisplay-functions win))))))
5586 (add-function :before pre-redisplay-function
5587 #'redisplay--pre-redisplay-functions)
5590 (defvar-local mark-ring nil
5591 "The list of former marks of the current buffer, most recent first.")
5592 (put 'mark-ring 'permanent-local t)
5594 (defcustom mark-ring-max 16
5595 "Maximum size of mark ring. Start discarding off end if gets this big."
5596 :type 'integer
5597 :group 'editing-basics)
5599 (defvar global-mark-ring nil
5600 "The list of saved global marks, most recent first.")
5602 (defcustom global-mark-ring-max 16
5603 "Maximum size of global mark ring. \
5604 Start discarding off end if gets this big."
5605 :type 'integer
5606 :group 'editing-basics)
5608 (defun pop-to-mark-command ()
5609 "Jump to mark, and pop a new position for mark off the ring.
5610 \(Does not affect global mark ring)."
5611 (interactive)
5612 (if (null (mark t))
5613 (user-error "No mark set in this buffer")
5614 (if (= (point) (mark t))
5615 (message "Mark popped"))
5616 (goto-char (mark t))
5617 (pop-mark)))
5619 (defun push-mark-command (arg &optional nomsg)
5620 "Set mark at where point is.
5621 If no prefix ARG and mark is already set there, just activate it.
5622 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5623 (interactive "P")
5624 (let ((mark (mark t)))
5625 (if (or arg (null mark) (/= mark (point)))
5626 (push-mark nil nomsg t)
5627 (activate-mark 'no-tmm)
5628 (unless nomsg
5629 (message "Mark activated")))))
5631 (defcustom set-mark-command-repeat-pop nil
5632 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5633 That means that C-u \\[set-mark-command] \\[set-mark-command]
5634 will pop the mark twice, and
5635 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5636 will pop the mark three times.
5638 A value of nil means \\[set-mark-command]'s behavior does not change
5639 after C-u \\[set-mark-command]."
5640 :type 'boolean
5641 :group 'editing-basics)
5643 (defun set-mark-command (arg)
5644 "Set the mark where point is, and activate it; or jump to the mark.
5645 Setting the mark also alters the region, which is the text
5646 between point and mark; this is the closest equivalent in
5647 Emacs to what some editors call the \"selection\".
5649 With no prefix argument, set the mark at point, and push the
5650 old mark position on local mark ring. Also push the new mark on
5651 global mark ring, if the previous mark was set in another buffer.
5653 When Transient Mark Mode is off, immediately repeating this
5654 command activates `transient-mark-mode' temporarily.
5656 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5657 jump to the mark, and set the mark from
5658 position popped off the local mark ring (this does not affect the global
5659 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5660 mark ring (see `pop-global-mark').
5662 If `set-mark-command-repeat-pop' is non-nil, repeating
5663 the \\[set-mark-command] command with no prefix argument pops the next position
5664 off the local (or global) mark ring and jumps there.
5666 With \\[universal-argument] \\[universal-argument] as prefix
5667 argument, unconditionally set mark where point is, even if
5668 `set-mark-command-repeat-pop' is non-nil.
5670 Novice Emacs Lisp programmers often try to use the mark for the wrong
5671 purposes. See the documentation of `set-mark' for more information."
5672 (interactive "P")
5673 (cond ((eq transient-mark-mode 'lambda)
5674 (kill-local-variable 'transient-mark-mode))
5675 ((eq (car-safe transient-mark-mode) 'only)
5676 (deactivate-mark)))
5677 (cond
5678 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5679 (push-mark-command nil))
5680 ((not (eq this-command 'set-mark-command))
5681 (if arg
5682 (pop-to-mark-command)
5683 (push-mark-command t)))
5684 ((and set-mark-command-repeat-pop
5685 (eq last-command 'pop-global-mark)
5686 (not arg))
5687 (setq this-command 'pop-global-mark)
5688 (pop-global-mark))
5689 ((or (and set-mark-command-repeat-pop
5690 (eq last-command 'pop-to-mark-command))
5691 arg)
5692 (setq this-command 'pop-to-mark-command)
5693 (pop-to-mark-command))
5694 ((eq last-command 'set-mark-command)
5695 (if (region-active-p)
5696 (progn
5697 (deactivate-mark)
5698 (message "Mark deactivated"))
5699 (activate-mark)
5700 (message "Mark activated")))
5702 (push-mark-command nil))))
5704 (defun push-mark (&optional location nomsg activate)
5705 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5706 If the last global mark pushed was not in the current buffer,
5707 also push LOCATION on the global mark ring.
5708 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5710 Novice Emacs Lisp programmers often try to use the mark for the wrong
5711 purposes. See the documentation of `set-mark' for more information.
5713 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5714 (when (mark t)
5715 (let ((old (nth mark-ring-max mark-ring))
5716 (history-delete-duplicates nil))
5717 (add-to-history 'mark-ring (copy-marker (mark-marker)) mark-ring-max t)
5718 (when old
5719 (set-marker old nil))))
5720 (set-marker (mark-marker) (or location (point)) (current-buffer))
5721 ;; Don't push the mark on the global mark ring if the last global
5722 ;; mark pushed was in this same buffer.
5723 (unless (and global-mark-ring
5724 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5725 (let ((old (nth global-mark-ring-max global-mark-ring))
5726 (history-delete-duplicates nil))
5727 (add-to-history
5728 'global-mark-ring (copy-marker (mark-marker)) global-mark-ring-max t)
5729 (when old
5730 (set-marker old nil))))
5731 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5732 (message "Mark set"))
5733 (if (or activate (not transient-mark-mode))
5734 (set-mark (mark t)))
5735 nil)
5737 (defun pop-mark ()
5738 "Pop off mark ring into the buffer's actual mark.
5739 Does not set point. Does nothing if mark ring is empty."
5740 (when mark-ring
5741 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5742 (set-marker (mark-marker) (car mark-ring))
5743 (set-marker (car mark-ring) nil)
5744 (unless (mark t) (ding))
5745 (pop mark-ring))
5746 (deactivate-mark))
5748 (define-obsolete-function-alias
5749 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5750 (defun exchange-point-and-mark (&optional arg)
5751 "Put the mark where point is now, and point where the mark is now.
5752 This command works even when the mark is not active,
5753 and it reactivates the mark.
5755 If Transient Mark mode is on, a prefix ARG deactivates the mark
5756 if it is active, and otherwise avoids reactivating it. If
5757 Transient Mark mode is off, a prefix ARG enables Transient Mark
5758 mode temporarily."
5759 (interactive "P")
5760 (let ((omark (mark t))
5761 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5762 (if (null omark)
5763 (user-error "No mark set in this buffer"))
5764 (set-mark (point))
5765 (goto-char omark)
5766 (cond (temp-highlight
5767 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5768 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5769 (not (or arg (region-active-p))))
5770 (deactivate-mark))
5771 (t (activate-mark)))
5772 nil))
5774 (defcustom shift-select-mode t
5775 "When non-nil, shifted motion keys activate the mark momentarily.
5777 While the mark is activated in this way, any shift-translated point
5778 motion key extends the region, and if Transient Mark mode was off, it
5779 is temporarily turned on. Furthermore, the mark will be deactivated
5780 by any subsequent point motion key that was not shift-translated, or
5781 by any action that normally deactivates the mark in Transient Mark mode.
5783 See `this-command-keys-shift-translated' for the meaning of
5784 shift-translation."
5785 :type 'boolean
5786 :group 'editing-basics)
5788 (defun handle-shift-selection ()
5789 "Activate/deactivate mark depending on invocation thru shift translation.
5790 This function is called by `call-interactively' when a command
5791 with a `^' character in its `interactive' spec is invoked, before
5792 running the command itself.
5794 If `shift-select-mode' is enabled and the command was invoked
5795 through shift translation, set the mark and activate the region
5796 temporarily, unless it was already set in this way. See
5797 `this-command-keys-shift-translated' for the meaning of shift
5798 translation.
5800 Otherwise, if the region has been activated temporarily,
5801 deactivate it, and restore the variable `transient-mark-mode' to
5802 its earlier value."
5803 (cond ((and shift-select-mode this-command-keys-shift-translated)
5804 (unless (and mark-active
5805 (eq (car-safe transient-mark-mode) 'only))
5806 (setq-local transient-mark-mode
5807 (cons 'only
5808 (unless (eq transient-mark-mode 'lambda)
5809 transient-mark-mode)))
5810 (push-mark nil nil t)))
5811 ((eq (car-safe transient-mark-mode) 'only)
5812 (setq transient-mark-mode (cdr transient-mark-mode))
5813 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5814 (kill-local-variable 'transient-mark-mode))
5815 (deactivate-mark))))
5817 (define-minor-mode transient-mark-mode
5818 "Toggle Transient Mark mode.
5819 With a prefix argument ARG, enable Transient Mark mode if ARG is
5820 positive, and disable it otherwise. If called from Lisp, enable
5821 Transient Mark mode if ARG is omitted or nil.
5823 Transient Mark mode is a global minor mode. When enabled, the
5824 region is highlighted with the `region' face whenever the mark
5825 is active. The mark is \"deactivated\" by changing the buffer,
5826 and after certain other operations that set the mark but whose
5827 main purpose is something else--for example, incremental search,
5828 \\[beginning-of-buffer], and \\[end-of-buffer].
5830 You can also deactivate the mark by typing \\[keyboard-quit] or
5831 \\[keyboard-escape-quit].
5833 Many commands change their behavior when Transient Mark mode is
5834 in effect and the mark is active, by acting on the region instead
5835 of their usual default part of the buffer's text. Examples of
5836 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5837 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5838 To see the documentation of commands which are sensitive to the
5839 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5840 or \"mark.*active\" at the prompt."
5841 :global t
5842 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5843 :variable (default-value 'transient-mark-mode))
5845 (defvar widen-automatically t
5846 "Non-nil means it is ok for commands to call `widen' when they want to.
5847 Some commands will do this in order to go to positions outside
5848 the current accessible part of the buffer.
5850 If `widen-automatically' is nil, these commands will do something else
5851 as a fallback, and won't change the buffer bounds.")
5853 (defvar non-essential nil
5854 "Whether the currently executing code is performing an essential task.
5855 This variable should be non-nil only when running code which should not
5856 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5857 user for a password when we are simply scanning a set of files in the
5858 background or displaying possible completions before the user even asked
5859 for it.")
5861 (defun pop-global-mark ()
5862 "Pop off global mark ring and jump to the top location."
5863 (interactive)
5864 ;; Pop entries which refer to non-existent buffers.
5865 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5866 (setq global-mark-ring (cdr global-mark-ring)))
5867 (or global-mark-ring
5868 (error "No global mark set"))
5869 (let* ((marker (car global-mark-ring))
5870 (buffer (marker-buffer marker))
5871 (position (marker-position marker)))
5872 (setq global-mark-ring (nconc (cdr global-mark-ring)
5873 (list (car global-mark-ring))))
5874 (set-buffer buffer)
5875 (or (and (>= position (point-min))
5876 (<= position (point-max)))
5877 (if widen-automatically
5878 (widen)
5879 (error "Global mark position is outside accessible part of buffer")))
5880 (goto-char position)
5881 (switch-to-buffer buffer)))
5883 (defcustom next-line-add-newlines nil
5884 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5885 :type 'boolean
5886 :version "21.1"
5887 :group 'editing-basics)
5889 (defun next-line (&optional arg try-vscroll)
5890 "Move cursor vertically down ARG lines.
5891 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5892 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5893 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5894 function will not vscroll.
5896 ARG defaults to 1.
5898 If there is no character in the target line exactly under the current column,
5899 the cursor is positioned after the character in that line which spans this
5900 column, or at the end of the line if it is not long enough.
5901 If there is no line in the buffer after this one, behavior depends on the
5902 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5903 to create a line, and moves the cursor to that line. Otherwise it moves the
5904 cursor to the end of the buffer.
5906 If the variable `line-move-visual' is non-nil, this command moves
5907 by display lines. Otherwise, it moves by buffer lines, without
5908 taking variable-width characters or continued lines into account.
5909 See \\[next-logical-line] for a command that always moves by buffer lines.
5911 The command \\[set-goal-column] can be used to create
5912 a semipermanent goal column for this command.
5913 Then instead of trying to move exactly vertically (or as close as possible),
5914 this command moves to the specified goal column (or as close as possible).
5915 The goal column is stored in the variable `goal-column', which is nil
5916 when there is no goal column. Note that setting `goal-column'
5917 overrides `line-move-visual' and causes this command to move by buffer
5918 lines rather than by display lines."
5919 (declare (interactive-only forward-line))
5920 (interactive "^p\np")
5921 (or arg (setq arg 1))
5922 (if (and next-line-add-newlines (= arg 1))
5923 (if (save-excursion (end-of-line) (eobp))
5924 ;; When adding a newline, don't expand an abbrev.
5925 (let ((abbrev-mode nil))
5926 (end-of-line)
5927 (insert (if use-hard-newlines hard-newline "\n")))
5928 (line-move arg nil nil try-vscroll))
5929 (if (called-interactively-p 'interactive)
5930 (condition-case err
5931 (line-move arg nil nil try-vscroll)
5932 ((beginning-of-buffer end-of-buffer)
5933 (signal (car err) (cdr err))))
5934 (line-move arg nil nil try-vscroll)))
5935 nil)
5937 (defun previous-line (&optional arg try-vscroll)
5938 "Move cursor vertically up ARG lines.
5939 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5940 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5941 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5942 function will not vscroll.
5944 ARG defaults to 1.
5946 If there is no character in the target line exactly over the current column,
5947 the cursor is positioned after the character in that line which spans this
5948 column, or at the end of the line if it is not long enough.
5950 If the variable `line-move-visual' is non-nil, this command moves
5951 by display lines. Otherwise, it moves by buffer lines, without
5952 taking variable-width characters or continued lines into account.
5953 See \\[previous-logical-line] for a command that always moves by buffer lines.
5955 The command \\[set-goal-column] can be used to create
5956 a semipermanent goal column for this command.
5957 Then instead of trying to move exactly vertically (or as close as possible),
5958 this command moves to the specified goal column (or as close as possible).
5959 The goal column is stored in the variable `goal-column', which is nil
5960 when there is no goal column. Note that setting `goal-column'
5961 overrides `line-move-visual' and causes this command to move by buffer
5962 lines rather than by display lines."
5963 (declare (interactive-only
5964 "use `forward-line' with negative argument instead."))
5965 (interactive "^p\np")
5966 (or arg (setq arg 1))
5967 (if (called-interactively-p 'interactive)
5968 (condition-case err
5969 (line-move (- arg) nil nil try-vscroll)
5970 ((beginning-of-buffer end-of-buffer)
5971 (signal (car err) (cdr err))))
5972 (line-move (- arg) nil nil try-vscroll))
5973 nil)
5975 (defcustom track-eol nil
5976 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5977 This means moving to the end of each line moved onto.
5978 The beginning of a blank line does not count as the end of a line.
5979 This has no effect when the variable `line-move-visual' is non-nil."
5980 :type 'boolean
5981 :group 'editing-basics)
5983 (defcustom goal-column nil
5984 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5985 A non-nil setting overrides the variable `line-move-visual', which see."
5986 :type '(choice integer
5987 (const :tag "None" nil))
5988 :group 'editing-basics)
5989 (make-variable-buffer-local 'goal-column)
5991 (defvar temporary-goal-column 0
5992 "Current goal column for vertical motion.
5993 It is the column where point was at the start of the current run
5994 of vertical motion commands.
5996 When moving by visual lines via the function `line-move-visual', it is a cons
5997 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5998 divided by the default column width, and HSCROLL is the number of
5999 columns by which window is scrolled from left margin.
6001 When the `track-eol' feature is doing its job, the value is
6002 `most-positive-fixnum'.")
6004 (defvar last--line-number-width 0
6005 "Last value of width used for displaying line numbers.
6006 Used internally by `line-move-visual'.")
6008 (defcustom line-move-ignore-invisible t
6009 "Non-nil means commands that move by lines ignore invisible newlines.
6010 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
6011 as if newlines that are invisible didn't exist, and count
6012 only visible newlines. Thus, moving across 2 newlines
6013 one of which is invisible will be counted as a one-line move.
6014 Also, a non-nil value causes invisible text to be ignored when
6015 counting columns for the purposes of keeping point in the same
6016 column by \\[next-line] and \\[previous-line].
6018 Outline mode sets this."
6019 :type 'boolean
6020 :group 'editing-basics)
6022 (defcustom line-move-visual t
6023 "When non-nil, `line-move' moves point by visual lines.
6024 This movement is based on where the cursor is displayed on the
6025 screen, instead of relying on buffer contents alone. It takes
6026 into account variable-width characters and line continuation.
6027 If nil, `line-move' moves point by logical lines.
6028 A non-nil setting of `goal-column' overrides the value of this variable
6029 and forces movement by logical lines.
6030 A window that is horizontally scrolled also forces movement by logical
6031 lines."
6032 :type 'boolean
6033 :group 'editing-basics
6034 :version "23.1")
6036 ;; Only used if display-graphic-p.
6037 (declare-function font-info "font.c" (name &optional frame))
6039 (defun default-font-height ()
6040 "Return the height in pixels of the current buffer's default face font.
6042 If the default font is remapped (see `face-remapping-alist'), the
6043 function returns the height of the remapped face."
6044 (let ((default-font (face-font 'default)))
6045 (cond
6046 ((and (display-multi-font-p)
6047 ;; Avoid calling font-info if the frame's default font was
6048 ;; not changed since the frame was created. That's because
6049 ;; font-info is expensive for some fonts, see bug #14838.
6050 (not (string= (frame-parameter nil 'font) default-font)))
6051 (aref (font-info default-font) 3))
6052 (t (frame-char-height)))))
6054 (defun default-font-width ()
6055 "Return the width in pixels of the current buffer's default face font.
6057 If the default font is remapped (see `face-remapping-alist'), the
6058 function returns the width of the remapped face."
6059 (let ((default-font (face-font 'default)))
6060 (cond
6061 ((and (display-multi-font-p)
6062 ;; Avoid calling font-info if the frame's default font was
6063 ;; not changed since the frame was created. That's because
6064 ;; font-info is expensive for some fonts, see bug #14838.
6065 (not (string= (frame-parameter nil 'font) default-font)))
6066 (let* ((info (font-info (face-font 'default)))
6067 (width (aref info 11)))
6068 (if (> width 0)
6069 width
6070 (aref info 10))))
6071 (t (frame-char-width)))))
6073 (defun default-line-height ()
6074 "Return the pixel height of current buffer's default-face text line.
6076 The value includes `line-spacing', if any, defined for the buffer
6077 or the frame."
6078 (let ((dfh (default-font-height))
6079 (lsp (if (display-graphic-p)
6080 (or line-spacing
6081 (default-value 'line-spacing)
6082 (frame-parameter nil 'line-spacing)
6084 0)))
6085 (if (floatp lsp)
6086 (setq lsp (truncate (* (frame-char-height) lsp))))
6087 (+ dfh lsp)))
6089 (defun window-screen-lines ()
6090 "Return the number of screen lines in the text area of the selected window.
6092 This is different from `window-text-height' in that this function counts
6093 lines in units of the height of the font used by the default face displayed
6094 in the window, not in units of the frame's default font, and also accounts
6095 for `line-spacing', if any, defined for the window's buffer or frame.
6097 The value is a floating-point number."
6098 (let ((edges (window-inside-pixel-edges))
6099 (dlh (default-line-height)))
6100 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
6102 ;; Returns non-nil if partial move was done.
6103 (defun line-move-partial (arg noerror &optional _to-end)
6104 (if (< arg 0)
6105 ;; Move backward (up).
6106 ;; If already vscrolled, reduce vscroll
6107 (let ((vs (window-vscroll nil t))
6108 (dlh (default-line-height)))
6109 (when (> vs dlh)
6110 (set-window-vscroll nil (- vs dlh) t)))
6112 ;; Move forward (down).
6113 (let* ((lh (window-line-height -1))
6114 (rowh (car lh))
6115 (vpos (nth 1 lh))
6116 (ypos (nth 2 lh))
6117 (rbot (nth 3 lh))
6118 (this-lh (window-line-height))
6119 (this-height (car this-lh))
6120 (this-ypos (nth 2 this-lh))
6121 (dlh (default-line-height))
6122 (wslines (window-screen-lines))
6123 (edges (window-inside-pixel-edges))
6124 (winh (- (nth 3 edges) (nth 1 edges) 1))
6125 py vs last-line)
6126 (if (> (mod wslines 1.0) 0.0)
6127 (setq wslines (round (+ wslines 0.5))))
6128 (when (or (null lh)
6129 (>= rbot dlh)
6130 (<= ypos (- dlh))
6131 (null this-lh)
6132 (<= this-ypos (- dlh)))
6133 (unless lh
6134 (let ((wend (pos-visible-in-window-p t nil t)))
6135 (setq rbot (nth 3 wend)
6136 rowh (nth 4 wend)
6137 vpos (nth 5 wend))))
6138 (unless this-lh
6139 (let ((wstart (pos-visible-in-window-p nil nil t)))
6140 (setq this-ypos (nth 2 wstart)
6141 this-height (nth 4 wstart))))
6142 (setq py
6143 (or (nth 1 this-lh)
6144 (let ((ppos (posn-at-point))
6145 col-row)
6146 (setq col-row (posn-actual-col-row ppos))
6147 (if col-row
6148 (- (cdr col-row) (window-vscroll))
6149 (cdr (posn-col-row ppos))))))
6150 ;; VPOS > 0 means the last line is only partially visible.
6151 ;; But if the part that is visible is at least as tall as the
6152 ;; default font, that means the line is actually fully
6153 ;; readable, and something like line-spacing is hidden. So in
6154 ;; that case we accept the last line in the window as still
6155 ;; visible, and consider the margin as starting one line
6156 ;; later.
6157 (if (and vpos (> vpos 0))
6158 (if (and rowh
6159 (>= rowh (default-font-height))
6160 (< rowh dlh))
6161 (setq last-line (min (- wslines scroll-margin) vpos))
6162 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6163 (cond
6164 ;; If last line of window is fully visible, and vscrolling
6165 ;; more would make this line invisible, move forward.
6166 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6167 (null this-height)
6168 (<= this-height dlh))
6169 (or (null rbot) (= rbot 0)))
6170 nil)
6171 ;; If cursor is not in the bottom scroll margin, and the
6172 ;; current line is not too tall, move forward.
6173 ((and (or (null this-height) (<= this-height winh))
6174 vpos
6175 (> vpos 0)
6176 (< py last-line))
6177 nil)
6178 ;; When already vscrolled, we vscroll some more if we can,
6179 ;; or clear vscroll and move forward at end of tall image.
6180 ((> vs 0)
6181 (when (or (and rbot (> rbot 0))
6182 (and this-height (> this-height dlh)))
6183 (set-window-vscroll nil (+ vs dlh) t)))
6184 ;; If cursor just entered the bottom scroll margin, move forward,
6185 ;; but also optionally vscroll one line so redisplay won't recenter.
6186 ((and vpos
6187 (> vpos 0)
6188 (= py last-line))
6189 ;; Don't vscroll if the partially-visible line at window
6190 ;; bottom is not too tall (a.k.a. "just one more text
6191 ;; line"): in that case, we do want redisplay to behave
6192 ;; normally, i.e. recenter or whatever.
6194 ;; Note: ROWH + RBOT from the value returned by
6195 ;; pos-visible-in-window-p give the total height of the
6196 ;; partially-visible glyph row at the end of the window. As
6197 ;; we are dealing with floats, we disregard sub-pixel
6198 ;; discrepancies between that and DLH.
6199 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6200 (set-window-vscroll nil dlh t))
6201 (line-move-1 arg noerror)
6203 ;; If there are lines above the last line, scroll-up one line.
6204 ((and vpos (> vpos 0))
6205 (scroll-up 1)
6207 ;; Finally, start vscroll.
6209 (set-window-vscroll nil dlh t)))))))
6212 ;; This is like line-move-1 except that it also performs
6213 ;; vertical scrolling of tall images if appropriate.
6214 ;; That is not really a clean thing to do, since it mixes
6215 ;; scrolling with cursor motion. But so far we don't have
6216 ;; a cleaner solution to the problem of making C-n do something
6217 ;; useful given a tall image.
6218 (defun line-move (arg &optional noerror _to-end try-vscroll)
6219 "Move forward ARG lines.
6220 If NOERROR, don't signal an error if we can't move ARG lines.
6221 TO-END is unused.
6222 TRY-VSCROLL controls whether to vscroll tall lines: if either
6223 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6224 not vscroll."
6225 (if noninteractive
6226 (line-move-1 arg noerror)
6227 (unless (and auto-window-vscroll try-vscroll
6228 ;; Only vscroll for single line moves
6229 (= (abs arg) 1)
6230 ;; Under scroll-conservatively, the display engine
6231 ;; does this better.
6232 (zerop scroll-conservatively)
6233 ;; But don't vscroll in a keyboard macro.
6234 (not defining-kbd-macro)
6235 (not executing-kbd-macro)
6236 (line-move-partial arg noerror))
6237 (set-window-vscroll nil 0 t)
6238 (if (and line-move-visual
6239 ;; Display-based column are incompatible with goal-column.
6240 (not goal-column)
6241 ;; When the text in the window is scrolled to the left,
6242 ;; display-based motion doesn't make sense (because each
6243 ;; logical line occupies exactly one screen line).
6244 (not (> (window-hscroll) 0))
6245 ;; Likewise when the text _was_ scrolled to the left
6246 ;; when the current run of vertical motion commands
6247 ;; started.
6248 (not (and (memq last-command
6249 `(next-line previous-line ,this-command))
6250 auto-hscroll-mode
6251 (numberp temporary-goal-column)
6252 (>= temporary-goal-column
6253 (- (window-width) hscroll-margin)))))
6254 (prog1 (line-move-visual arg noerror)
6255 ;; If we moved into a tall line, set vscroll to make
6256 ;; scrolling through tall images more smooth.
6257 (let ((lh (line-pixel-height))
6258 (edges (window-inside-pixel-edges))
6259 (dlh (default-line-height))
6260 winh)
6261 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6262 (if (and (< arg 0)
6263 (< (point) (window-start))
6264 (> lh winh))
6265 (set-window-vscroll
6267 (- lh dlh) t))))
6268 (line-move-1 arg noerror)))))
6270 ;; Display-based alternative to line-move-1.
6271 ;; Arg says how many lines to move. The value is t if we can move the
6272 ;; specified number of lines.
6273 (defun line-move-visual (arg &optional noerror)
6274 "Move ARG lines forward.
6275 If NOERROR, don't signal an error if we can't move that many lines."
6276 (let ((opoint (point))
6277 (hscroll (window-hscroll))
6278 (lnum-width (line-number-display-width t))
6279 target-hscroll)
6280 ;; Check if the previous command was a line-motion command, or if
6281 ;; we were called from some other command.
6282 (if (and (consp temporary-goal-column)
6283 (memq last-command `(next-line previous-line ,this-command)))
6284 ;; If so, there's no need to reset `temporary-goal-column',
6285 ;; but we may need to hscroll.
6286 (progn
6287 (if (or (/= (cdr temporary-goal-column) hscroll)
6288 (> (cdr temporary-goal-column) 0))
6289 (setq target-hscroll (cdr temporary-goal-column)))
6290 ;; Update the COLUMN part of temporary-goal-column if the
6291 ;; line-number display changed its width since the last
6292 ;; time.
6293 (setq temporary-goal-column
6294 (cons (+ (car temporary-goal-column)
6295 (/ (float (- lnum-width last--line-number-width))
6296 (frame-char-width)))
6297 (cdr temporary-goal-column)))
6298 (setq last--line-number-width lnum-width))
6299 ;; Otherwise, we should reset `temporary-goal-column'.
6300 (let ((posn (posn-at-point))
6301 x-pos)
6302 (cond
6303 ;; Handle the `overflow-newline-into-fringe' case
6304 ;; (left-fringe is for the R2L case):
6305 ((memq (nth 1 posn) '(right-fringe left-fringe))
6306 (setq temporary-goal-column (cons (window-width) hscroll)))
6307 ((car (posn-x-y posn))
6308 (setq x-pos (car (posn-x-y posn)))
6309 ;; In R2L lines, the X pixel coordinate is measured from the
6310 ;; left edge of the window, but columns are still counted
6311 ;; from the logical-order beginning of the line, i.e. from
6312 ;; the right edge in this case. We need to adjust for that.
6313 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6314 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6315 (setq temporary-goal-column
6316 (cons (/ (float x-pos)
6317 (frame-char-width))
6318 hscroll)))
6319 (executing-kbd-macro
6320 ;; When we move beyond the first/last character visible in
6321 ;; the window, posn-at-point will return nil, so we need to
6322 ;; approximate the goal column as below.
6323 (setq temporary-goal-column
6324 (mod (current-column) (window-text-width)))))))
6325 (if target-hscroll
6326 (set-window-hscroll (selected-window) target-hscroll))
6327 ;; vertical-motion can move more than it was asked to if it moves
6328 ;; across display strings with newlines. We don't want to ring
6329 ;; the bell and announce beginning/end of buffer in that case.
6330 (or (and (or (and (>= arg 0)
6331 (>= (vertical-motion
6332 (cons (or goal-column
6333 (if (consp temporary-goal-column)
6334 (car temporary-goal-column)
6335 temporary-goal-column))
6336 arg))
6337 arg))
6338 (and (< arg 0)
6339 (<= (vertical-motion
6340 (cons (or goal-column
6341 (if (consp temporary-goal-column)
6342 (car temporary-goal-column)
6343 temporary-goal-column))
6344 arg))
6345 arg)))
6346 (or (>= arg 0)
6347 (/= (point) opoint)
6348 ;; If the goal column lies on a display string,
6349 ;; `vertical-motion' advances the cursor to the end
6350 ;; of the string. For arg < 0, this can cause the
6351 ;; cursor to get stuck. (Bug#3020).
6352 (= (vertical-motion arg) arg)))
6353 (unless noerror
6354 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6355 nil)))))
6357 ;; This is the guts of next-line and previous-line.
6358 ;; Arg says how many lines to move.
6359 ;; The value is t if we can move the specified number of lines.
6360 (defun line-move-1 (arg &optional noerror _to-end)
6361 ;; Don't run any point-motion hooks, and disregard intangibility,
6362 ;; for intermediate positions.
6363 (let ((inhibit-point-motion-hooks t)
6364 (opoint (point))
6365 (orig-arg arg))
6366 (if (consp temporary-goal-column)
6367 (setq temporary-goal-column (+ (car temporary-goal-column)
6368 (cdr temporary-goal-column))))
6369 (unwind-protect
6370 (progn
6371 (if (not (memq last-command '(next-line previous-line)))
6372 (setq temporary-goal-column
6373 (if (and track-eol (eolp)
6374 ;; Don't count beg of empty line as end of line
6375 ;; unless we just did explicit end-of-line.
6376 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6377 most-positive-fixnum
6378 (current-column))))
6380 (if (not (or (integerp selective-display)
6381 line-move-ignore-invisible))
6382 ;; Use just newline characters.
6383 ;; Set ARG to 0 if we move as many lines as requested.
6384 (or (if (> arg 0)
6385 (progn (if (> arg 1) (forward-line (1- arg)))
6386 ;; This way of moving forward ARG lines
6387 ;; verifies that we have a newline after the last one.
6388 ;; It doesn't get confused by intangible text.
6389 (end-of-line)
6390 (if (zerop (forward-line 1))
6391 (setq arg 0)))
6392 (and (zerop (forward-line arg))
6393 (bolp)
6394 (setq arg 0)))
6395 (unless noerror
6396 (signal (if (< arg 0)
6397 'beginning-of-buffer
6398 'end-of-buffer)
6399 nil)))
6400 ;; Move by arg lines, but ignore invisible ones.
6401 (let (done)
6402 (while (and (> arg 0) (not done))
6403 ;; If the following character is currently invisible,
6404 ;; skip all characters with that same `invisible' property value.
6405 (while (and (not (eobp)) (invisible-p (point)))
6406 (goto-char (next-char-property-change (point))))
6407 ;; Move a line.
6408 ;; We don't use `end-of-line', since we want to escape
6409 ;; from field boundaries occurring exactly at point.
6410 (goto-char (constrain-to-field
6411 (let ((inhibit-field-text-motion t))
6412 (line-end-position))
6413 (point) t t
6414 'inhibit-line-move-field-capture))
6415 ;; If there's no invisibility here, move over the newline.
6416 (cond
6417 ((eobp)
6418 (if (not noerror)
6419 (signal 'end-of-buffer nil)
6420 (setq done t)))
6421 ((and (> arg 1) ;; Use vertical-motion for last move
6422 (not (integerp selective-display))
6423 (not (invisible-p (point))))
6424 ;; We avoid vertical-motion when possible
6425 ;; because that has to fontify.
6426 (forward-line 1))
6427 ;; Otherwise move a more sophisticated way.
6428 ((zerop (vertical-motion 1))
6429 (if (not noerror)
6430 (signal 'end-of-buffer nil)
6431 (setq done t))))
6432 (unless done
6433 (setq arg (1- arg))))
6434 ;; The logic of this is the same as the loop above,
6435 ;; it just goes in the other direction.
6436 (while (and (< arg 0) (not done))
6437 ;; For completely consistency with the forward-motion
6438 ;; case, we should call beginning-of-line here.
6439 ;; However, if point is inside a field and on a
6440 ;; continued line, the call to (vertical-motion -1)
6441 ;; below won't move us back far enough; then we return
6442 ;; to the same column in line-move-finish, and point
6443 ;; gets stuck -- cyd
6444 (forward-line 0)
6445 (cond
6446 ((bobp)
6447 (if (not noerror)
6448 (signal 'beginning-of-buffer nil)
6449 (setq done t)))
6450 ((and (< arg -1) ;; Use vertical-motion for last move
6451 (not (integerp selective-display))
6452 (not (invisible-p (1- (point)))))
6453 (forward-line -1))
6454 ((zerop (vertical-motion -1))
6455 (if (not noerror)
6456 (signal 'beginning-of-buffer nil)
6457 (setq done t))))
6458 (unless done
6459 (setq arg (1+ arg))
6460 (while (and ;; Don't move over previous invis lines
6461 ;; if our target is the middle of this line.
6462 (or (zerop (or goal-column temporary-goal-column))
6463 (< arg 0))
6464 (not (bobp)) (invisible-p (1- (point))))
6465 (goto-char (previous-char-property-change (point))))))))
6466 ;; This is the value the function returns.
6467 (= arg 0))
6469 (cond ((> arg 0)
6470 ;; If we did not move down as far as desired, at least go
6471 ;; to end of line. Be sure to call point-entered and
6472 ;; point-left-hooks.
6473 (let* ((npoint (prog1 (line-end-position)
6474 (goto-char opoint)))
6475 (inhibit-point-motion-hooks nil))
6476 (goto-char npoint)))
6477 ((< arg 0)
6478 ;; If we did not move up as far as desired,
6479 ;; at least go to beginning of line.
6480 (let* ((npoint (prog1 (line-beginning-position)
6481 (goto-char opoint)))
6482 (inhibit-point-motion-hooks nil))
6483 (goto-char npoint)))
6485 (line-move-finish (or goal-column temporary-goal-column)
6486 opoint (> orig-arg 0)))))))
6488 (defun line-move-finish (column opoint forward)
6489 (let ((repeat t))
6490 (while repeat
6491 ;; Set REPEAT to t to repeat the whole thing.
6492 (setq repeat nil)
6494 (let (new
6495 (old (point))
6496 (line-beg (line-beginning-position))
6497 (line-end
6498 ;; Compute the end of the line
6499 ;; ignoring effectively invisible newlines.
6500 (save-excursion
6501 ;; Like end-of-line but ignores fields.
6502 (skip-chars-forward "^\n")
6503 (while (and (not (eobp)) (invisible-p (point)))
6504 (goto-char (next-char-property-change (point)))
6505 (skip-chars-forward "^\n"))
6506 (point))))
6508 ;; Move to the desired column.
6509 (if (and line-move-visual
6510 (not (or truncate-lines truncate-partial-width-windows)))
6511 ;; Under line-move-visual, goal-column should be
6512 ;; interpreted in units of the frame's canonical character
6513 ;; width, which is exactly what vertical-motion does.
6514 (vertical-motion (cons column 0))
6515 (line-move-to-column (truncate column)))
6517 ;; Corner case: suppose we start out in a field boundary in
6518 ;; the middle of a continued line. When we get to
6519 ;; line-move-finish, point is at the start of a new *screen*
6520 ;; line but the same text line; then line-move-to-column would
6521 ;; move us backwards. Test using C-n with point on the "x" in
6522 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6523 (and forward
6524 (< (point) old)
6525 (goto-char old))
6527 (setq new (point))
6529 ;; Process intangibility within a line.
6530 ;; With inhibit-point-motion-hooks bound to nil, a call to
6531 ;; goto-char moves point past intangible text.
6533 ;; However, inhibit-point-motion-hooks controls both the
6534 ;; intangibility and the point-entered/point-left hooks. The
6535 ;; following hack avoids calling the point-* hooks
6536 ;; unnecessarily. Note that we move *forward* past intangible
6537 ;; text when the initial and final points are the same.
6538 (goto-char new)
6539 (let ((inhibit-point-motion-hooks nil))
6540 (goto-char new)
6542 ;; If intangibility moves us to a different (later) place
6543 ;; in the same line, use that as the destination.
6544 (if (<= (point) line-end)
6545 (setq new (point))
6546 ;; If that position is "too late",
6547 ;; try the previous allowable position.
6548 ;; See if it is ok.
6549 (backward-char)
6550 (if (if forward
6551 ;; If going forward, don't accept the previous
6552 ;; allowable position if it is before the target line.
6553 (< line-beg (point))
6554 ;; If going backward, don't accept the previous
6555 ;; allowable position if it is still after the target line.
6556 (<= (point) line-end))
6557 (setq new (point))
6558 ;; As a last resort, use the end of the line.
6559 (setq new line-end))))
6561 ;; Now move to the updated destination, processing fields
6562 ;; as well as intangibility.
6563 (goto-char opoint)
6564 (let ((inhibit-point-motion-hooks nil))
6565 (goto-char
6566 ;; Ignore field boundaries if the initial and final
6567 ;; positions have the same `field' property, even if the
6568 ;; fields are non-contiguous. This seems to be "nicer"
6569 ;; behavior in many situations.
6570 (if (eq (get-char-property new 'field)
6571 (get-char-property opoint 'field))
6573 (constrain-to-field new opoint t t
6574 'inhibit-line-move-field-capture))))
6576 ;; If all this moved us to a different line,
6577 ;; retry everything within that new line.
6578 (when (or (< (point) line-beg) (> (point) line-end))
6579 ;; Repeat the intangibility and field processing.
6580 (setq repeat t))))))
6582 (defun line-move-to-column (col)
6583 "Try to find column COL, considering invisibility.
6584 This function works only in certain cases,
6585 because what we really need is for `move-to-column'
6586 and `current-column' to be able to ignore invisible text."
6587 (if (zerop col)
6588 (beginning-of-line)
6589 (move-to-column col))
6591 (when (and line-move-ignore-invisible
6592 (not (bolp)) (invisible-p (1- (point))))
6593 (let ((normal-location (point))
6594 (normal-column (current-column)))
6595 ;; If the following character is currently invisible,
6596 ;; skip all characters with that same `invisible' property value.
6597 (while (and (not (eobp))
6598 (invisible-p (point)))
6599 (goto-char (next-char-property-change (point))))
6600 ;; Have we advanced to a larger column position?
6601 (if (> (current-column) normal-column)
6602 ;; We have made some progress towards the desired column.
6603 ;; See if we can make any further progress.
6604 (line-move-to-column (+ (current-column) (- col normal-column)))
6605 ;; Otherwise, go to the place we originally found
6606 ;; and move back over invisible text.
6607 ;; that will get us to the same place on the screen
6608 ;; but with a more reasonable buffer position.
6609 (goto-char normal-location)
6610 (let ((line-beg
6611 ;; We want the real line beginning, so it's consistent
6612 ;; with bolp below, otherwise we might infloop.
6613 (let ((inhibit-field-text-motion t))
6614 (line-beginning-position))))
6615 (while (and (not (bolp)) (invisible-p (1- (point))))
6616 (goto-char (previous-char-property-change (point) line-beg))))))))
6618 (defun move-end-of-line (arg)
6619 "Move point to end of current line as displayed.
6620 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6621 If point reaches the beginning or end of buffer, it stops there.
6623 To ignore the effects of the `intangible' text or overlay
6624 property, bind `inhibit-point-motion-hooks' to t.
6625 If there is an image in the current line, this function
6626 disregards newlines that are part of the text on which the image
6627 rests."
6628 (interactive "^p")
6629 (or arg (setq arg 1))
6630 (let (done)
6631 (while (not done)
6632 (let ((newpos
6633 (save-excursion
6634 (let ((goal-column 0)
6635 (line-move-visual nil))
6636 (and (line-move arg t)
6637 ;; With bidi reordering, we may not be at bol,
6638 ;; so make sure we are.
6639 (skip-chars-backward "^\n")
6640 (not (bobp))
6641 (progn
6642 (while (and (not (bobp)) (invisible-p (1- (point))))
6643 (goto-char (previous-single-char-property-change
6644 (point) 'invisible)))
6645 (backward-char 1)))
6646 (point)))))
6647 (goto-char newpos)
6648 (if (and (> (point) newpos)
6649 (eq (preceding-char) ?\n))
6650 (backward-char 1)
6651 (if (and (> (point) newpos) (not (eobp))
6652 (not (eq (following-char) ?\n)))
6653 ;; If we skipped something intangible and now we're not
6654 ;; really at eol, keep going.
6655 (setq arg 1)
6656 (setq done t)))))))
6658 (defun move-beginning-of-line (arg)
6659 "Move point to beginning of current line as displayed.
6660 \(If there's an image in the line, this disregards newlines
6661 which are part of the text that the image rests on.)
6663 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6664 If point reaches the beginning or end of buffer, it stops there.
6665 \(But if the buffer doesn't end in a newline, it stops at the
6666 beginning of the last line.)
6667 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6668 (interactive "^p")
6669 (or arg (setq arg 1))
6671 (let ((orig (point))
6672 first-vis first-vis-field-value)
6674 ;; Move by lines, if ARG is not 1 (the default).
6675 (if (/= arg 1)
6676 (let ((line-move-visual nil))
6677 (line-move (1- arg) t)))
6679 ;; Move to beginning-of-line, ignoring fields and invisible text.
6680 (skip-chars-backward "^\n")
6681 (while (and (not (bobp)) (invisible-p (1- (point))))
6682 (goto-char (previous-char-property-change (point)))
6683 (skip-chars-backward "^\n"))
6685 ;; Now find first visible char in the line.
6686 (while (and (< (point) orig) (invisible-p (point)))
6687 (goto-char (next-char-property-change (point) orig)))
6688 (setq first-vis (point))
6690 ;; See if fields would stop us from reaching FIRST-VIS.
6691 (setq first-vis-field-value
6692 (constrain-to-field first-vis orig (/= arg 1) t nil))
6694 (goto-char (if (/= first-vis-field-value first-vis)
6695 ;; If yes, obey them.
6696 first-vis-field-value
6697 ;; Otherwise, move to START with attention to fields.
6698 ;; (It is possible that fields never matter in this case.)
6699 (constrain-to-field (point) orig
6700 (/= arg 1) t nil)))))
6703 ;; Many people have said they rarely use this feature, and often type
6704 ;; it by accident. Maybe it shouldn't even be on a key.
6705 (put 'set-goal-column 'disabled t)
6707 (defun set-goal-column (arg)
6708 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6709 Those commands will move to this position in the line moved to
6710 rather than trying to keep the same horizontal position.
6711 With a non-nil argument ARG, clears out the goal column
6712 so that \\[next-line] and \\[previous-line] resume vertical motion.
6713 The goal column is stored in the variable `goal-column'.
6714 This is a buffer-local setting."
6715 (interactive "P")
6716 (if arg
6717 (progn
6718 (setq goal-column nil)
6719 (message "No goal column"))
6720 (setq goal-column (current-column))
6721 ;; The older method below can be erroneous if `set-goal-column' is bound
6722 ;; to a sequence containing %
6723 ;;(message (substitute-command-keys
6724 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6725 ;;goal-column)
6726 (message "%s"
6727 (concat
6728 (format "Goal column %d " goal-column)
6729 (substitute-command-keys
6730 "(use \\[set-goal-column] with an arg to unset it)")))
6733 nil)
6735 ;;; Editing based on visual lines, as opposed to logical lines.
6737 (defun end-of-visual-line (&optional n)
6738 "Move point to end of current visual line.
6739 With argument N not nil or 1, move forward N - 1 visual lines first.
6740 If point reaches the beginning or end of buffer, it stops there.
6741 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6742 (interactive "^p")
6743 (or n (setq n 1))
6744 (if (/= n 1)
6745 (let ((line-move-visual t))
6746 (line-move (1- n) t)))
6747 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6748 ;; constrain to field boundaries, so we don't either.
6749 (vertical-motion (cons (window-width) 0)))
6751 (defun beginning-of-visual-line (&optional n)
6752 "Move point to beginning of current visual line.
6753 With argument N not nil or 1, move forward N - 1 visual lines first.
6754 If point reaches the beginning or end of buffer, it stops there.
6755 \(But if the buffer doesn't end in a newline, it stops at the
6756 beginning of the last visual line.)
6757 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6758 (interactive "^p")
6759 (or n (setq n 1))
6760 (let ((opoint (point)))
6761 (if (/= n 1)
6762 (let ((line-move-visual t))
6763 (line-move (1- n) t)))
6764 (vertical-motion 0)
6765 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6766 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6768 (defun kill-visual-line (&optional arg)
6769 "Kill the rest of the visual line.
6770 With prefix argument ARG, kill that many visual lines from point.
6771 If ARG is negative, kill visual lines backward.
6772 If ARG is zero, kill the text before point on the current visual
6773 line.
6775 If you want to append the killed line to the last killed text,
6776 use \\[append-next-kill] before \\[kill-line].
6778 If the buffer is read-only, Emacs will beep and refrain from deleting
6779 the line, but put the line in the kill ring anyway. This means that
6780 you can use this command to copy text from a read-only buffer.
6781 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6782 even beep.)"
6783 (interactive "P")
6784 ;; Like in `kill-line', it's better to move point to the other end
6785 ;; of the kill before killing.
6786 (let ((opoint (point))
6787 (kill-whole-line (and kill-whole-line (bolp))))
6788 (if arg
6789 (vertical-motion (prefix-numeric-value arg))
6790 (end-of-visual-line 1)
6791 (if (= (point) opoint)
6792 (vertical-motion 1)
6793 ;; Skip any trailing whitespace at the end of the visual line.
6794 ;; We used to do this only if `show-trailing-whitespace' is
6795 ;; nil, but that's wrong; the correct thing would be to check
6796 ;; whether the trailing whitespace is highlighted. But, it's
6797 ;; OK to just do this unconditionally.
6798 (skip-chars-forward " \t")))
6799 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6800 (1+ (point))
6801 (point)))))
6803 (defun next-logical-line (&optional arg try-vscroll)
6804 "Move cursor vertically down ARG lines.
6805 This is identical to `next-line', except that it always moves
6806 by logical lines instead of visual lines, ignoring the value of
6807 the variable `line-move-visual'."
6808 (interactive "^p\np")
6809 (let ((line-move-visual nil))
6810 (with-no-warnings
6811 (next-line arg try-vscroll))))
6813 (defun previous-logical-line (&optional arg try-vscroll)
6814 "Move cursor vertically up ARG lines.
6815 This is identical to `previous-line', except that it always moves
6816 by logical lines instead of visual lines, ignoring the value of
6817 the variable `line-move-visual'."
6818 (interactive "^p\np")
6819 (let ((line-move-visual nil))
6820 (with-no-warnings
6821 (previous-line arg try-vscroll))))
6823 (defgroup visual-line nil
6824 "Editing based on visual lines."
6825 :group 'convenience
6826 :version "23.1")
6828 (defvar visual-line-mode-map
6829 (let ((map (make-sparse-keymap)))
6830 (define-key map [remap kill-line] 'kill-visual-line)
6831 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6832 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6833 ;; These keybindings interfere with xterm function keys. Are
6834 ;; there any other suitable bindings?
6835 ;; (define-key map "\M-[" 'previous-logical-line)
6836 ;; (define-key map "\M-]" 'next-logical-line)
6837 map))
6839 (defcustom visual-line-fringe-indicators '(nil nil)
6840 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6841 The value should be a list of the form (LEFT RIGHT), where LEFT
6842 and RIGHT are symbols representing the bitmaps to display, to
6843 indicate wrapped lines, in the left and right fringes respectively.
6844 See also `fringe-indicator-alist'.
6845 The default is not to display fringe indicators for wrapped lines.
6846 This variable does not affect fringe indicators displayed for
6847 other purposes."
6848 :type '(list (choice (const :tag "Hide left indicator" nil)
6849 (const :tag "Left curly arrow" left-curly-arrow)
6850 (symbol :tag "Other bitmap"))
6851 (choice (const :tag "Hide right indicator" nil)
6852 (const :tag "Right curly arrow" right-curly-arrow)
6853 (symbol :tag "Other bitmap")))
6854 :set (lambda (symbol value)
6855 (dolist (buf (buffer-list))
6856 (with-current-buffer buf
6857 (when (and (boundp 'visual-line-mode)
6858 (symbol-value 'visual-line-mode))
6859 (setq fringe-indicator-alist
6860 (cons (cons 'continuation value)
6861 (assq-delete-all
6862 'continuation
6863 (copy-tree fringe-indicator-alist)))))))
6864 (set-default symbol value)))
6866 (defvar visual-line--saved-state nil)
6868 (define-minor-mode visual-line-mode
6869 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6870 Interactively, with a prefix argument, enable
6871 Visual Line mode if the prefix argument is positive,
6872 and disable it otherwise. If called from Lisp, toggle
6873 the mode if ARG is `toggle', disable the mode if ARG is
6874 a non-positive integer, and enable the mode otherwise
6875 \(including if ARG is omitted or nil or a positive integer).
6877 When Visual Line mode is enabled, `word-wrap' is turned on in
6878 this buffer, and simple editing commands are redefined to act on
6879 visual lines, not logical lines. See Info node `Visual Line
6880 Mode' for details."
6881 :keymap visual-line-mode-map
6882 :group 'visual-line
6883 :lighter " Wrap"
6884 (if visual-line-mode
6885 (progn
6886 (set (make-local-variable 'visual-line--saved-state) nil)
6887 ;; Save the local values of some variables, to be restored if
6888 ;; visual-line-mode is turned off.
6889 (dolist (var '(line-move-visual truncate-lines
6890 truncate-partial-width-windows
6891 word-wrap fringe-indicator-alist))
6892 (if (local-variable-p var)
6893 (push (cons var (symbol-value var))
6894 visual-line--saved-state)))
6895 (set (make-local-variable 'line-move-visual) t)
6896 (set (make-local-variable 'truncate-partial-width-windows) nil)
6897 (setq truncate-lines nil
6898 word-wrap t
6899 fringe-indicator-alist
6900 (cons (cons 'continuation visual-line-fringe-indicators)
6901 fringe-indicator-alist)))
6902 (kill-local-variable 'line-move-visual)
6903 (kill-local-variable 'word-wrap)
6904 (kill-local-variable 'truncate-lines)
6905 (kill-local-variable 'truncate-partial-width-windows)
6906 (kill-local-variable 'fringe-indicator-alist)
6907 (dolist (saved visual-line--saved-state)
6908 (set (make-local-variable (car saved)) (cdr saved)))
6909 (kill-local-variable 'visual-line--saved-state)))
6911 (defun turn-on-visual-line-mode ()
6912 (visual-line-mode 1))
6914 (define-globalized-minor-mode global-visual-line-mode
6915 visual-line-mode turn-on-visual-line-mode)
6918 (defun transpose-chars (arg)
6919 "Interchange characters around point, moving forward one character.
6920 With prefix arg ARG, effect is to take character before point
6921 and drag it forward past ARG other characters (backward if ARG negative).
6922 If no argument and at end of line, the previous two chars are exchanged."
6923 (interactive "*P")
6924 (when (and (null arg) (eolp) (not (bobp))
6925 (not (get-text-property (1- (point)) 'read-only)))
6926 (forward-char -1))
6927 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6929 (defun transpose-words (arg)
6930 "Interchange words around point, leaving point at end of them.
6931 With prefix arg ARG, effect is to take word before or around point
6932 and drag it forward past ARG other words (backward if ARG negative).
6933 If ARG is zero, the words around or after point and around or after mark
6934 are interchanged."
6935 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6936 (interactive "*p")
6937 (transpose-subr 'forward-word arg))
6939 (defun transpose-sexps (arg)
6940 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6941 Unlike `transpose-words', point must be between the two sexps and not
6942 in the middle of a sexp to be transposed.
6943 With non-zero prefix arg ARG, effect is to take the sexp before point
6944 and drag it forward past ARG other sexps (backward if ARG is negative).
6945 If ARG is zero, the sexps ending at or after point and at or after mark
6946 are interchanged."
6947 (interactive "*p")
6948 (transpose-subr
6949 (lambda (arg)
6950 ;; Here we should try to simulate the behavior of
6951 ;; (cons (progn (forward-sexp x) (point))
6952 ;; (progn (forward-sexp (- x)) (point)))
6953 ;; Except that we don't want to rely on the second forward-sexp
6954 ;; putting us back to where we want to be, since forward-sexp-function
6955 ;; might do funny things like infix-precedence.
6956 (if (if (> arg 0)
6957 (looking-at "\\sw\\|\\s_")
6958 (and (not (bobp))
6959 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6960 ;; Jumping over a symbol. We might be inside it, mind you.
6961 (progn (funcall (if (> arg 0)
6962 'skip-syntax-backward 'skip-syntax-forward)
6963 "w_")
6964 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6965 ;; Otherwise, we're between sexps. Take a step back before jumping
6966 ;; to make sure we'll obey the same precedence no matter which direction
6967 ;; we're going.
6968 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6969 (cons (save-excursion (forward-sexp arg) (point))
6970 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6971 (not (zerop (funcall (if (> arg 0)
6972 'skip-syntax-forward
6973 'skip-syntax-backward)
6974 ".")))))
6975 (point)))))
6976 arg 'special))
6978 (defun transpose-lines (arg)
6979 "Exchange current line and previous line, leaving point after both.
6980 With argument ARG, takes previous line and moves it past ARG lines.
6981 With argument 0, interchanges line point is in with line mark is in."
6982 (interactive "*p")
6983 (transpose-subr (function
6984 (lambda (arg)
6985 (if (> arg 0)
6986 (progn
6987 ;; Move forward over ARG lines,
6988 ;; but create newlines if necessary.
6989 (setq arg (forward-line arg))
6990 (if (/= (preceding-char) ?\n)
6991 (setq arg (1+ arg)))
6992 (if (> arg 0)
6993 (newline arg)))
6994 (forward-line arg))))
6995 arg))
6997 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6998 ;; which seems inconsistent with the ARG /= 0 case.
6999 ;; FIXME document SPECIAL.
7000 (defun transpose-subr (mover arg &optional special)
7001 "Subroutine to do the work of transposing objects.
7002 Works for lines, sentences, paragraphs, etc. MOVER is a function that
7003 moves forward by units of the given object (e.g. forward-sentence,
7004 forward-paragraph). If ARG is zero, exchanges the current object
7005 with the one containing mark. If ARG is an integer, moves the
7006 current object past ARG following (if ARG is positive) or
7007 preceding (if ARG is negative) objects, leaving point after the
7008 current object."
7009 (let ((aux (if special mover
7010 (lambda (x)
7011 (cons (progn (funcall mover x) (point))
7012 (progn (funcall mover (- x)) (point))))))
7013 pos1 pos2)
7014 (cond
7015 ((= arg 0)
7016 (save-excursion
7017 (setq pos1 (funcall aux 1))
7018 (goto-char (or (mark) (error "No mark set in this buffer")))
7019 (setq pos2 (funcall aux 1))
7020 (transpose-subr-1 pos1 pos2))
7021 (exchange-point-and-mark))
7022 ((> arg 0)
7023 (setq pos1 (funcall aux -1))
7024 (setq pos2 (funcall aux arg))
7025 (transpose-subr-1 pos1 pos2)
7026 (goto-char (car pos2)))
7028 (setq pos1 (funcall aux -1))
7029 (goto-char (car pos1))
7030 (setq pos2 (funcall aux arg))
7031 (transpose-subr-1 pos1 pos2)
7032 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
7034 (defun transpose-subr-1 (pos1 pos2)
7035 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
7036 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
7037 (when (> (car pos1) (car pos2))
7038 (let ((swap pos1))
7039 (setq pos1 pos2 pos2 swap)))
7040 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
7041 (atomic-change-group
7042 ;; This sequence of insertions attempts to preserve marker
7043 ;; positions at the start and end of the transposed objects.
7044 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
7045 (len1 (- (cdr pos1) (car pos1)))
7046 (len2 (length word))
7047 (boundary (make-marker)))
7048 (set-marker boundary (car pos2))
7049 (goto-char (cdr pos1))
7050 (insert-before-markers word)
7051 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
7052 (goto-char boundary)
7053 (insert word)
7054 (goto-char (+ boundary len1))
7055 (delete-region (point) (+ (point) len2))
7056 (set-marker boundary nil))))
7058 (defun backward-word (&optional arg)
7059 "Move backward until encountering the beginning of a word.
7060 With argument ARG, do this that many times.
7061 If ARG is omitted or nil, move point backward one word.
7063 The word boundaries are normally determined by the buffer's
7064 syntax table and character script (according to
7065 `char-script-table'), but `find-word-boundary-function-table',
7066 such as set up by `subword-mode', can change that. If a Lisp
7067 program needs to move by words determined strictly by the syntax
7068 table, it should use `backward-word-strictly' instead. See Info
7069 node `(elisp) Word Motion' for details."
7070 (interactive "^p")
7071 (forward-word (- (or arg 1))))
7073 (defun mark-word (&optional arg allow-extend)
7074 "Set mark ARG words away from point.
7075 The place mark goes is the same place \\[forward-word] would
7076 move to with the same argument.
7077 Interactively, if this command is repeated
7078 or (in Transient Mark mode) if the mark is active,
7079 it marks the next ARG words after the ones already marked."
7080 (interactive "P\np")
7081 (cond ((and allow-extend
7082 (or (and (eq last-command this-command) (mark t))
7083 (region-active-p)))
7084 (setq arg (if arg (prefix-numeric-value arg)
7085 (if (< (mark) (point)) -1 1)))
7086 (set-mark
7087 (save-excursion
7088 (goto-char (mark))
7089 (forward-word arg)
7090 (point))))
7092 (push-mark
7093 (save-excursion
7094 (forward-word (prefix-numeric-value arg))
7095 (point))
7096 nil t))))
7098 (defun kill-word (arg)
7099 "Kill characters forward until encountering the end of a word.
7100 With argument ARG, do this that many times."
7101 (interactive "p")
7102 (kill-region (point) (progn (forward-word arg) (point))))
7104 (defun backward-kill-word (arg)
7105 "Kill characters backward until encountering the beginning of a word.
7106 With argument ARG, do this that many times."
7107 (interactive "p")
7108 (kill-word (- arg)))
7110 (defun current-word (&optional strict really-word)
7111 "Return the word at or near point, as a string.
7112 The return value includes no text properties.
7114 If optional arg STRICT is non-nil, return nil unless point is
7115 within or adjacent to a word, otherwise look for a word within
7116 point's line. If there is no word anywhere on point's line, the
7117 value is nil regardless of STRICT.
7119 By default, this function treats as a single word any sequence of
7120 characters that have either word or symbol syntax. If optional
7121 arg REALLY-WORD is non-nil, only characters of word syntax can
7122 constitute a word."
7123 (save-excursion
7124 (let* ((oldpoint (point)) (start (point)) (end (point))
7125 (syntaxes (if really-word "w" "w_"))
7126 (not-syntaxes (concat "^" syntaxes)))
7127 (skip-syntax-backward syntaxes) (setq start (point))
7128 (goto-char oldpoint)
7129 (skip-syntax-forward syntaxes) (setq end (point))
7130 (when (and (eq start oldpoint) (eq end oldpoint)
7131 ;; Point is neither within nor adjacent to a word.
7132 (not strict))
7133 ;; Look for preceding word in same line.
7134 (skip-syntax-backward not-syntaxes (line-beginning-position))
7135 (if (bolp)
7136 ;; No preceding word in same line.
7137 ;; Look for following word in same line.
7138 (progn
7139 (skip-syntax-forward not-syntaxes (line-end-position))
7140 (setq start (point))
7141 (skip-syntax-forward syntaxes)
7142 (setq end (point)))
7143 (setq end (point))
7144 (skip-syntax-backward syntaxes)
7145 (setq start (point))))
7146 ;; If we found something nonempty, return it as a string.
7147 (unless (= start end)
7148 (buffer-substring-no-properties start end)))))
7150 (defcustom fill-prefix nil
7151 "String for filling to insert at front of new line, or nil for none."
7152 :type '(choice (const :tag "None" nil)
7153 string)
7154 :group 'fill)
7155 (make-variable-buffer-local 'fill-prefix)
7156 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7158 (defcustom auto-fill-inhibit-regexp nil
7159 "Regexp to match lines which should not be auto-filled."
7160 :type '(choice (const :tag "None" nil)
7161 regexp)
7162 :group 'fill)
7164 (defun do-auto-fill ()
7165 "The default value for `normal-auto-fill-function'.
7166 This is the default auto-fill function, some major modes use a different one.
7167 Returns t if it really did any work."
7168 (let (fc justify give-up
7169 (fill-prefix fill-prefix))
7170 (if (or (not (setq justify (current-justification)))
7171 (null (setq fc (current-fill-column)))
7172 (and (eq justify 'left)
7173 (<= (current-column) fc))
7174 (and auto-fill-inhibit-regexp
7175 (save-excursion (beginning-of-line)
7176 (looking-at auto-fill-inhibit-regexp))))
7177 nil ;; Auto-filling not required
7178 (if (memq justify '(full center right))
7179 (save-excursion (unjustify-current-line)))
7181 ;; Choose a fill-prefix automatically.
7182 (when (and adaptive-fill-mode
7183 (or (null fill-prefix) (string= fill-prefix "")))
7184 (let ((prefix
7185 (fill-context-prefix
7186 (save-excursion (fill-forward-paragraph -1) (point))
7187 (save-excursion (fill-forward-paragraph 1) (point)))))
7188 (and prefix (not (equal prefix ""))
7189 ;; Use auto-indentation rather than a guessed empty prefix.
7190 (not (and fill-indent-according-to-mode
7191 (string-match "\\`[ \t]*\\'" prefix)))
7192 (setq fill-prefix prefix))))
7194 (while (and (not give-up) (> (current-column) fc))
7195 ;; Determine where to split the line.
7196 (let ((fill-point
7197 (save-excursion
7198 (beginning-of-line)
7199 ;; Don't split earlier in the line than the length of the
7200 ;; fill prefix, since the resulting line would be longer.
7201 (when fill-prefix
7202 (move-to-column (string-width fill-prefix)))
7203 (let ((after-prefix (point)))
7204 (move-to-column (1+ fc))
7205 (fill-move-to-break-point after-prefix)
7206 (point)))))
7208 ;; See whether the place we found is any good.
7209 (if (save-excursion
7210 (goto-char fill-point)
7211 (or (bolp)
7212 ;; There is no use breaking at end of line.
7213 (save-excursion (skip-chars-forward " ") (eolp))
7214 ;; Don't split right after a comment starter
7215 ;; since we would just make another comment starter.
7216 (and comment-start-skip
7217 (let ((limit (point)))
7218 (beginning-of-line)
7219 (and (re-search-forward comment-start-skip
7220 limit t)
7221 (eq (point) limit))))))
7222 ;; No good place to break => stop trying.
7223 (setq give-up t)
7224 ;; Ok, we have a useful place to break the line. Do it.
7225 (let ((prev-column (current-column)))
7226 ;; If point is at the fill-point, do not `save-excursion'.
7227 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7228 ;; point will end up before it rather than after it.
7229 (if (save-excursion
7230 (skip-chars-backward " \t")
7231 (= (point) fill-point))
7232 (default-indent-new-line t)
7233 (save-excursion
7234 (goto-char fill-point)
7235 (default-indent-new-line t)))
7236 ;; Now do justification, if required
7237 (if (not (eq justify 'left))
7238 (save-excursion
7239 (end-of-line 0)
7240 (justify-current-line justify nil t)))
7241 ;; If making the new line didn't reduce the hpos of
7242 ;; the end of the line, then give up now;
7243 ;; trying again will not help.
7244 (if (>= (current-column) prev-column)
7245 (setq give-up t))))))
7246 ;; Justify last line.
7247 (justify-current-line justify t t)
7248 t)))
7250 (defvar comment-line-break-function 'comment-indent-new-line
7251 "Mode-specific function which line breaks and continues a comment.
7252 This function is called during auto-filling when a comment syntax
7253 is defined.
7254 The function should take a single optional argument, which is a flag
7255 indicating whether it should use soft newlines.")
7257 (defun default-indent-new-line (&optional soft)
7258 "Break line at point and indent.
7259 If a comment syntax is defined, call `comment-indent-new-line'.
7261 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7262 unless optional argument SOFT is non-nil."
7263 (interactive)
7264 (if comment-start
7265 (funcall comment-line-break-function soft)
7266 ;; Insert the newline before removing empty space so that markers
7267 ;; get preserved better.
7268 (if soft (insert-and-inherit ?\n) (newline 1))
7269 (save-excursion (forward-char -1) (delete-horizontal-space))
7270 (delete-horizontal-space)
7272 (if (and fill-prefix (not adaptive-fill-mode))
7273 ;; Blindly trust a non-adaptive fill-prefix.
7274 (progn
7275 (indent-to-left-margin)
7276 (insert-before-markers-and-inherit fill-prefix))
7278 (cond
7279 ;; If there's an adaptive prefix, use it unless we're inside
7280 ;; a comment and the prefix is not a comment starter.
7281 (fill-prefix
7282 (indent-to-left-margin)
7283 (insert-and-inherit fill-prefix))
7284 ;; If we're not inside a comment, just try to indent.
7285 (t (indent-according-to-mode))))))
7287 (defun internal-auto-fill ()
7288 "The function called by `self-insert-command' to perform auto-filling."
7289 (when (or (not comment-start)
7290 (not comment-auto-fill-only-comments)
7291 (nth 4 (syntax-ppss)))
7292 (funcall auto-fill-function)))
7294 (defvar normal-auto-fill-function 'do-auto-fill
7295 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7296 Some major modes set this.")
7298 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7299 ;; `functions' and `hooks' are usually unsafe to set, but setting
7300 ;; auto-fill-function to nil in a file-local setting is safe and
7301 ;; can be useful to prevent auto-filling.
7302 (put 'auto-fill-function 'safe-local-variable 'null)
7304 (define-minor-mode auto-fill-mode
7305 "Toggle automatic line breaking (Auto Fill mode).
7306 Interactively, with a prefix argument, enable
7307 Auto Fill mode if the prefix argument is positive,
7308 and disable it otherwise. If called from Lisp, toggle
7309 the mode if ARG is `toggle', disable the mode if ARG is
7310 a non-positive integer, and enable the mode otherwise
7311 \(including if ARG is omitted or nil or a positive integer).
7313 When Auto Fill mode is enabled, inserting a space at a column
7314 beyond `current-fill-column' automatically breaks the line at a
7315 previous space.
7317 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7318 non-nil.
7320 The value of `normal-auto-fill-function' specifies the function to use
7321 for `auto-fill-function' when turning Auto Fill mode on."
7322 :variable (auto-fill-function
7323 . (lambda (v) (setq auto-fill-function
7324 (if v normal-auto-fill-function)))))
7326 ;; This holds a document string used to document auto-fill-mode.
7327 (defun auto-fill-function ()
7328 "Automatically break line at a previous space, in insertion of text."
7329 nil)
7331 (defun turn-on-auto-fill ()
7332 "Unconditionally turn on Auto Fill mode."
7333 (auto-fill-mode 1))
7335 (defun turn-off-auto-fill ()
7336 "Unconditionally turn off Auto Fill mode."
7337 (auto-fill-mode -1))
7339 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7341 (defun set-fill-column (arg)
7342 "Set `fill-column' to specified argument.
7343 Use \\[universal-argument] followed by a number to specify a column.
7344 Just \\[universal-argument] as argument means to use the current column."
7345 (interactive
7346 (list (or current-prefix-arg
7347 ;; We used to use current-column silently, but C-x f is too easily
7348 ;; typed as a typo for C-x C-f, so we turned it into an error and
7349 ;; now an interactive prompt.
7350 (read-number "Set fill-column to: " (current-column)))))
7351 (if (consp arg)
7352 (setq arg (current-column)))
7353 (if (not (integerp arg))
7354 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7355 (error "set-fill-column requires an explicit argument")
7356 (message "Fill column set to %d (was %d)" arg fill-column)
7357 (setq fill-column arg)))
7359 (defun set-selective-display (arg)
7360 "Set `selective-display' to ARG; clear it if no arg.
7361 When the value of `selective-display' is a number > 0,
7362 lines whose indentation is >= that value are not displayed.
7363 The variable `selective-display' has a separate value for each buffer."
7364 (interactive "P")
7365 (if (eq selective-display t)
7366 (error "selective-display already in use for marked lines"))
7367 (let ((current-vpos
7368 (save-restriction
7369 (narrow-to-region (point-min) (point))
7370 (goto-char (window-start))
7371 (vertical-motion (window-height)))))
7372 (setq selective-display
7373 (and arg (prefix-numeric-value arg)))
7374 (recenter current-vpos))
7375 (set-window-start (selected-window) (window-start))
7376 (princ "selective-display set to " t)
7377 (prin1 selective-display t)
7378 (princ "." t))
7380 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7382 (defun toggle-truncate-lines (&optional arg)
7383 "Toggle truncating of long lines for the current buffer.
7384 When truncating is off, long lines are folded.
7385 With prefix argument ARG, truncate long lines if ARG is positive,
7386 otherwise fold them. Note that in side-by-side windows, this
7387 command has no effect if `truncate-partial-width-windows' is
7388 non-nil."
7389 (interactive "P")
7390 (setq truncate-lines
7391 (if (null arg)
7392 (not truncate-lines)
7393 (> (prefix-numeric-value arg) 0)))
7394 (force-mode-line-update)
7395 (unless truncate-lines
7396 (let ((buffer (current-buffer)))
7397 (walk-windows (lambda (window)
7398 (if (eq buffer (window-buffer window))
7399 (set-window-hscroll window 0)))
7400 nil t)))
7401 (message "Truncate long lines %s"
7402 (if truncate-lines "enabled" "disabled")))
7404 (defun toggle-word-wrap (&optional arg)
7405 "Toggle whether to use word-wrapping for continuation lines.
7406 With prefix argument ARG, wrap continuation lines at word boundaries
7407 if ARG is positive, otherwise wrap them at the right screen edge.
7408 This command toggles the value of `word-wrap'. It has no effect
7409 if long lines are truncated."
7410 (interactive "P")
7411 (setq word-wrap
7412 (if (null arg)
7413 (not word-wrap)
7414 (> (prefix-numeric-value arg) 0)))
7415 (force-mode-line-update)
7416 (message "Word wrapping %s"
7417 (if word-wrap "enabled" "disabled")))
7419 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7420 "The string displayed in the mode line when in overwrite mode.")
7421 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7422 "The string displayed in the mode line when in binary overwrite mode.")
7424 (define-minor-mode overwrite-mode
7425 "Toggle Overwrite mode.
7426 With a prefix argument ARG, enable Overwrite mode if ARG is
7427 positive, and disable it otherwise. If called from Lisp, enable
7428 the mode if ARG is omitted or nil.
7430 When Overwrite mode is enabled, printing characters typed in
7431 replace existing text on a one-for-one basis, rather than pushing
7432 it to the right. At the end of a line, such characters extend
7433 the line. Before a tab, such characters insert until the tab is
7434 filled in. \\[quoted-insert] still inserts characters in
7435 overwrite mode; this is supposed to make it easier to insert
7436 characters when necessary."
7437 :variable (overwrite-mode
7438 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7440 (define-minor-mode binary-overwrite-mode
7441 "Toggle Binary Overwrite mode.
7442 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7443 is positive, and disable it otherwise. If called from Lisp,
7444 enable the mode if ARG is omitted or nil.
7446 When Binary Overwrite mode is enabled, printing characters typed
7447 in replace existing text. Newlines are not treated specially, so
7448 typing at the end of a line joins the line to the next, with the
7449 typed character between them. Typing before a tab character
7450 simply replaces the tab with the character typed.
7451 \\[quoted-insert] replaces the text at the cursor, just as
7452 ordinary typing characters do.
7454 Note that Binary Overwrite mode is not its own minor mode; it is
7455 a specialization of overwrite mode, entered by setting the
7456 `overwrite-mode' variable to `overwrite-mode-binary'."
7457 :variable (overwrite-mode
7458 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7460 (define-minor-mode line-number-mode
7461 "Toggle line number display in the mode line (Line Number mode).
7462 With a prefix argument ARG, enable Line Number mode if ARG is
7463 positive, and disable it otherwise. If called from Lisp, enable
7464 the mode if ARG is omitted or nil.
7466 Line numbers do not appear for very large buffers and buffers
7467 with very long lines; see variables `line-number-display-limit'
7468 and `line-number-display-limit-width'."
7469 :init-value t :global t :group 'mode-line)
7471 (define-minor-mode column-number-mode
7472 "Toggle column number display in the mode line (Column Number mode).
7473 With a prefix argument ARG, enable Column Number mode if ARG is
7474 positive, and disable it otherwise.
7476 If called from Lisp, enable the mode if ARG is omitted or nil."
7477 :global t :group 'mode-line)
7479 (define-minor-mode size-indication-mode
7480 "Toggle buffer size display in the mode line (Size Indication mode).
7481 With a prefix argument ARG, enable Size Indication mode if ARG is
7482 positive, and disable it otherwise.
7484 If called from Lisp, enable the mode if ARG is omitted or nil."
7485 :global t :group 'mode-line)
7487 (define-minor-mode auto-save-mode
7488 "Toggle auto-saving in the current buffer (Auto Save mode).
7489 With a prefix argument ARG, enable Auto Save mode if ARG is
7490 positive, and disable it otherwise.
7492 If called from Lisp, enable the mode if ARG is omitted or nil."
7493 :variable ((and buffer-auto-save-file-name
7494 ;; If auto-save is off because buffer has shrunk,
7495 ;; then toggling should turn it on.
7496 (>= buffer-saved-size 0))
7497 . (lambda (val)
7498 (setq buffer-auto-save-file-name
7499 (cond
7500 ((null val) nil)
7501 ((and buffer-file-name auto-save-visited-file-name
7502 (not buffer-read-only))
7503 buffer-file-name)
7504 (t (make-auto-save-file-name))))))
7505 ;; If -1 was stored here, to temporarily turn off saving,
7506 ;; turn it back on.
7507 (and (< buffer-saved-size 0)
7508 (setq buffer-saved-size 0)))
7510 (defgroup paren-blinking nil
7511 "Blinking matching of parens and expressions."
7512 :prefix "blink-matching-"
7513 :group 'paren-matching)
7515 (defcustom blink-matching-paren t
7516 "Non-nil means show matching open-paren when close-paren is inserted.
7517 If t, highlight the paren. If `jump', briefly move cursor to its
7518 position. If `jump-offscreen', move cursor there even if the
7519 position is off screen. With any other non-nil value, the
7520 off-screen position of the opening paren will be shown in the
7521 echo area."
7522 :type '(choice
7523 (const :tag "Disable" nil)
7524 (const :tag "Highlight" t)
7525 (const :tag "Move cursor" jump)
7526 (const :tag "Move cursor, even if off screen" jump-offscreen))
7527 :group 'paren-blinking)
7529 (defcustom blink-matching-paren-on-screen t
7530 "Non-nil means show matching open-paren when it is on screen.
7531 If nil, don't show it (but the open-paren can still be shown
7532 in the echo area when it is off screen).
7534 This variable has no effect if `blink-matching-paren' is nil.
7535 \(In that case, the open-paren is never shown.)
7536 It is also ignored if `show-paren-mode' is enabled."
7537 :type 'boolean
7538 :group 'paren-blinking)
7540 (defcustom blink-matching-paren-distance (* 100 1024)
7541 "If non-nil, maximum distance to search backwards for matching open-paren.
7542 If nil, search stops at the beginning of the accessible portion of the buffer."
7543 :version "23.2" ; 25->100k
7544 :type '(choice (const nil) integer)
7545 :group 'paren-blinking)
7547 (defcustom blink-matching-delay 1
7548 "Time in seconds to delay after showing a matching paren."
7549 :type 'number
7550 :group 'paren-blinking)
7552 (defcustom blink-matching-paren-dont-ignore-comments nil
7553 "If nil, `blink-matching-paren' ignores comments.
7554 More precisely, when looking for the matching parenthesis,
7555 it skips the contents of comments that end before point."
7556 :type 'boolean
7557 :group 'paren-blinking)
7559 (defun blink-matching-check-mismatch (start end)
7560 "Return whether or not START...END are matching parens.
7561 END is the current point and START is the blink position.
7562 START might be nil if no matching starter was found.
7563 Returns non-nil if we find there is a mismatch."
7564 (let* ((end-syntax (syntax-after (1- end)))
7565 (matching-paren (and (consp end-syntax)
7566 (eq (syntax-class end-syntax) 5)
7567 (cdr end-syntax))))
7568 ;; For self-matched chars like " and $, we can't know when they're
7569 ;; mismatched or unmatched, so we can only do it for parens.
7570 (when matching-paren
7571 (not (and start
7573 (eq (char-after start) matching-paren)
7574 ;; The cdr might hold a new paren-class info rather than
7575 ;; a matching-char info, in which case the two CDRs
7576 ;; should match.
7577 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7579 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7580 "Function to check parentheses mismatches.
7581 The function takes two arguments (START and END) where START is the
7582 position just before the opening token and END is the position right after.
7583 START can be nil, if it was not found.
7584 The function should return non-nil if the two tokens do not match.")
7586 (defvar blink-matching--overlay
7587 (let ((ol (make-overlay (point) (point) nil t)))
7588 (overlay-put ol 'face 'show-paren-match)
7589 (delete-overlay ol)
7591 "Overlay used to highlight the matching paren.")
7593 (defun blink-matching-open ()
7594 "Momentarily highlight the beginning of the sexp before point."
7595 (interactive)
7596 (when (and (not (bobp))
7597 blink-matching-paren)
7598 (let* ((oldpos (point))
7599 (message-log-max nil) ; Don't log messages about paren matching.
7600 (blinkpos
7601 (save-excursion
7602 (save-restriction
7603 (if blink-matching-paren-distance
7604 (narrow-to-region
7605 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7606 (- (point) blink-matching-paren-distance))
7607 oldpos))
7608 (let ((parse-sexp-ignore-comments
7609 (and parse-sexp-ignore-comments
7610 (not blink-matching-paren-dont-ignore-comments))))
7611 (condition-case ()
7612 (progn
7613 (syntax-propertize (point))
7614 (forward-sexp -1)
7615 ;; backward-sexp skips backward over prefix chars,
7616 ;; so move back to the matching paren.
7617 (while (and (< (point) (1- oldpos))
7618 (let ((code (syntax-after (point))))
7619 (or (eq (syntax-class code) 6)
7620 (eq (logand 1048576 (car code))
7621 1048576))))
7622 (forward-char 1))
7623 (point))
7624 (error nil))))))
7625 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7626 (cond
7627 (mismatch
7628 (if blinkpos
7629 (if (minibufferp)
7630 (minibuffer-message "Mismatched parentheses")
7631 (message "Mismatched parentheses"))
7632 (if (minibufferp)
7633 (minibuffer-message "No matching parenthesis found")
7634 (message "No matching parenthesis found"))))
7635 ((not blinkpos) nil)
7636 ((or
7637 (eq blink-matching-paren 'jump-offscreen)
7638 (pos-visible-in-window-p blinkpos))
7639 ;; Matching open within window, temporarily move to or highlight
7640 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7641 ;; is non-nil.
7642 (and blink-matching-paren-on-screen
7643 (not show-paren-mode)
7644 (if (memq blink-matching-paren '(jump jump-offscreen))
7645 (save-excursion
7646 (goto-char blinkpos)
7647 (sit-for blink-matching-delay))
7648 (unwind-protect
7649 (progn
7650 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7651 (current-buffer))
7652 (sit-for blink-matching-delay))
7653 (delete-overlay blink-matching--overlay)))))
7655 (let ((open-paren-line-string
7656 (save-excursion
7657 (goto-char blinkpos)
7658 ;; Show what precedes the open in its line, if anything.
7659 (cond
7660 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7661 (buffer-substring (line-beginning-position)
7662 (1+ blinkpos)))
7663 ;; Show what follows the open in its line, if anything.
7664 ((save-excursion
7665 (forward-char 1)
7666 (skip-chars-forward " \t")
7667 (not (eolp)))
7668 (buffer-substring blinkpos
7669 (line-end-position)))
7670 ;; Otherwise show the previous nonblank line,
7671 ;; if there is one.
7672 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7673 (concat
7674 (buffer-substring (progn
7675 (skip-chars-backward "\n \t")
7676 (line-beginning-position))
7677 (progn (end-of-line)
7678 (skip-chars-backward " \t")
7679 (point)))
7680 ;; Replace the newline and other whitespace with `...'.
7681 "..."
7682 (buffer-substring blinkpos (1+ blinkpos))))
7683 ;; There is nothing to show except the char itself.
7684 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7685 (minibuffer-message
7686 "Matches %s"
7687 (substring-no-properties open-paren-line-string))))))))
7689 (defvar blink-paren-function 'blink-matching-open
7690 "Function called, if non-nil, whenever a close parenthesis is inserted.
7691 More precisely, a char with closeparen syntax is self-inserted.")
7693 (defun blink-paren-post-self-insert-function ()
7694 (when (and (eq (char-before) last-command-event) ; Sanity check.
7695 (memq (char-syntax last-command-event) '(?\) ?\$))
7696 blink-paren-function
7697 (not executing-kbd-macro)
7698 (not noninteractive)
7699 ;; Verify an even number of quoting characters precede the close.
7700 ;; FIXME: Also check if this parenthesis closes a comment as
7701 ;; can happen in Pascal and SML.
7702 (= 1 (logand 1 (- (point)
7703 (save-excursion
7704 (forward-char -1)
7705 (skip-syntax-backward "/\\")
7706 (point))))))
7707 (funcall blink-paren-function)))
7709 (put 'blink-paren-post-self-insert-function 'priority 100)
7711 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7712 ;; Most likely, this hook is nil, so this arg doesn't matter,
7713 ;; but I use it as a reminder that this function usually
7714 ;; likes to be run after others since it does
7715 ;; `sit-for'. That's also the reason it get a `priority' prop
7716 ;; of 100.
7717 'append)
7719 ;; This executes C-g typed while Emacs is waiting for a command.
7720 ;; Quitting out of a program does not go through here;
7721 ;; that happens in the maybe_quit function at the C code level.
7722 (defun keyboard-quit ()
7723 "Signal a `quit' condition.
7724 During execution of Lisp code, this character causes a quit directly.
7725 At top-level, as an editor command, this simply beeps."
7726 (interactive)
7727 ;; Avoid adding the region to the window selection.
7728 (setq saved-region-selection nil)
7729 (let (select-active-regions)
7730 (deactivate-mark))
7731 (if (fboundp 'kmacro-keyboard-quit)
7732 (kmacro-keyboard-quit))
7733 (when completion-in-region-mode
7734 (completion-in-region-mode -1))
7735 ;; Force the next redisplay cycle to remove the "Def" indicator from
7736 ;; all the mode lines.
7737 (if defining-kbd-macro
7738 (force-mode-line-update t))
7739 (setq defining-kbd-macro nil)
7740 (let ((debug-on-quit nil))
7741 (signal 'quit nil)))
7743 (defvar buffer-quit-function nil
7744 "Function to call to \"quit\" the current buffer, or nil if none.
7745 \\[keyboard-escape-quit] calls this function when its more local actions
7746 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7748 (defun keyboard-escape-quit ()
7749 "Exit the current \"mode\" (in a generalized sense of the word).
7750 This command can exit an interactive command such as `query-replace',
7751 can clear out a prefix argument or a region,
7752 can get out of the minibuffer or other recursive edit,
7753 cancel the use of the current buffer (for special-purpose buffers),
7754 or go back to just one window (by deleting all but the selected window)."
7755 (interactive)
7756 (cond ((eq last-command 'mode-exited) nil)
7757 ((region-active-p)
7758 (deactivate-mark))
7759 ((> (minibuffer-depth) 0)
7760 (abort-recursive-edit))
7761 (current-prefix-arg
7762 nil)
7763 ((> (recursion-depth) 0)
7764 (exit-recursive-edit))
7765 (buffer-quit-function
7766 (funcall buffer-quit-function))
7767 ((not (one-window-p t))
7768 (delete-other-windows))
7769 ((string-match "^ \\*" (buffer-name (current-buffer)))
7770 (bury-buffer))))
7772 (defun play-sound-file (file &optional volume device)
7773 "Play sound stored in FILE.
7774 VOLUME and DEVICE correspond to the keywords of the sound
7775 specification for `play-sound'."
7776 (interactive "fPlay sound file: ")
7777 (let ((sound (list :file file)))
7778 (if volume
7779 (plist-put sound :volume volume))
7780 (if device
7781 (plist-put sound :device device))
7782 (push 'sound sound)
7783 (play-sound sound)))
7786 (defcustom read-mail-command 'rmail
7787 "Your preference for a mail reading package.
7788 This is used by some keybindings which support reading mail.
7789 See also `mail-user-agent' concerning sending mail."
7790 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7791 (function-item :tag "Gnus" :format "%t\n" gnus)
7792 (function-item :tag "Emacs interface to MH"
7793 :format "%t\n" mh-rmail)
7794 (function :tag "Other"))
7795 :version "21.1"
7796 :group 'mail)
7798 (defcustom mail-user-agent 'message-user-agent
7799 "Your preference for a mail composition package.
7800 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7801 outgoing email message. This variable lets you specify which
7802 mail-sending package you prefer.
7804 Valid values include:
7806 `message-user-agent' -- use the Message package.
7807 See Info node `(message)'.
7808 `sendmail-user-agent' -- use the Mail package.
7809 See Info node `(emacs)Sending Mail'.
7810 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7811 See Info node `(mh-e)'.
7812 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7813 paraphernalia if Gnus is running, particularly
7814 the Gcc: header for archiving.
7816 Additional valid symbols may be available; check with the author of
7817 your package for details. The function should return non-nil if it
7818 succeeds.
7820 See also `read-mail-command' concerning reading mail."
7821 :type '(radio (function-item :tag "Message package"
7822 :format "%t\n"
7823 message-user-agent)
7824 (function-item :tag "Mail package"
7825 :format "%t\n"
7826 sendmail-user-agent)
7827 (function-item :tag "Emacs interface to MH"
7828 :format "%t\n"
7829 mh-e-user-agent)
7830 (function-item :tag "Message with full Gnus features"
7831 :format "%t\n"
7832 gnus-user-agent)
7833 (function :tag "Other"))
7834 :version "23.2" ; sendmail->message
7835 :group 'mail)
7837 (defcustom compose-mail-user-agent-warnings t
7838 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7839 If the value of `mail-user-agent' is the default, and the user
7840 appears to have customizations applying to the old default,
7841 `compose-mail' issues a warning."
7842 :type 'boolean
7843 :version "23.2"
7844 :group 'mail)
7846 (defun rfc822-goto-eoh ()
7847 "If the buffer starts with a mail header, move point to the header's end.
7848 Otherwise, moves to `point-min'.
7849 The end of the header is the start of the next line, if there is one,
7850 else the end of the last line. This function obeys RFC822."
7851 (goto-char (point-min))
7852 (when (re-search-forward
7853 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7854 (goto-char (match-beginning 0))))
7856 ;; Used by Rmail (e.g., rmail-forward).
7857 (defvar mail-encode-mml nil
7858 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7859 the outgoing message before sending it.")
7861 (defun compose-mail (&optional to subject other-headers continue
7862 switch-function yank-action send-actions
7863 return-action)
7864 "Start composing a mail message to send.
7865 This uses the user's chosen mail composition package
7866 as selected with the variable `mail-user-agent'.
7867 The optional arguments TO and SUBJECT specify recipients
7868 and the initial Subject field, respectively.
7870 OTHER-HEADERS is an alist specifying additional
7871 header fields. Elements look like (HEADER . VALUE) where both
7872 HEADER and VALUE are strings.
7874 CONTINUE, if non-nil, says to continue editing a message already
7875 being composed. Interactively, CONTINUE is the prefix argument.
7877 SWITCH-FUNCTION, if non-nil, is a function to use to
7878 switch to and display the buffer used for mail composition.
7880 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7881 to insert the raw text of the message being replied to.
7882 It has the form (FUNCTION . ARGS). The user agent will apply
7883 FUNCTION to ARGS, to insert the raw text of the original message.
7884 \(The user agent will also run `mail-citation-hook', *after* the
7885 original text has been inserted in this way.)
7887 SEND-ACTIONS is a list of actions to call when the message is sent.
7888 Each action has the form (FUNCTION . ARGS).
7890 RETURN-ACTION, if non-nil, is an action for returning to the
7891 caller. It has the form (FUNCTION . ARGS). The function is
7892 called after the mail has been sent or put aside, and the mail
7893 buffer buried."
7894 (interactive
7895 (list nil nil nil current-prefix-arg))
7897 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7898 ;; from sendmail-user-agent to message-user-agent. Some users may
7899 ;; encounter incompatibilities. This hack tries to detect problems
7900 ;; and warn about them.
7901 (and compose-mail-user-agent-warnings
7902 (eq mail-user-agent 'message-user-agent)
7903 (let (warn-vars)
7904 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7905 mail-citation-hook mail-archive-file-name
7906 mail-default-reply-to mail-mailing-lists
7907 mail-self-blind))
7908 (and (boundp var)
7909 (symbol-value var)
7910 (push var warn-vars)))
7911 (when warn-vars
7912 (display-warning 'mail
7913 (format-message "\
7914 The default mail mode is now Message mode.
7915 You have the following Mail mode variable%s customized:
7916 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7917 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7918 (if (> (length warn-vars) 1) "s" "")
7919 (mapconcat 'symbol-name
7920 warn-vars " "))))))
7922 (let ((function (get mail-user-agent 'composefunc)))
7923 (unless function
7924 (error "Invalid value for `mail-user-agent'"))
7925 (funcall function to subject other-headers continue switch-function
7926 yank-action send-actions return-action)))
7928 (defun compose-mail-other-window (&optional to subject other-headers continue
7929 yank-action send-actions
7930 return-action)
7931 "Like \\[compose-mail], but edit the outgoing message in another window."
7932 (interactive (list nil nil nil current-prefix-arg))
7933 (compose-mail to subject other-headers continue
7934 'switch-to-buffer-other-window yank-action send-actions
7935 return-action))
7937 (defun compose-mail-other-frame (&optional to subject other-headers continue
7938 yank-action send-actions
7939 return-action)
7940 "Like \\[compose-mail], but edit the outgoing message in another frame."
7941 (interactive (list nil nil nil current-prefix-arg))
7942 (compose-mail to subject other-headers continue
7943 'switch-to-buffer-other-frame yank-action send-actions
7944 return-action))
7947 (defvar set-variable-value-history nil
7948 "History of values entered with `set-variable'.
7950 Maximum length of the history list is determined by the value
7951 of `history-length', which see.")
7953 (defun set-variable (variable value &optional make-local)
7954 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7955 VARIABLE should be a user option variable name, a Lisp variable
7956 meant to be customized by users. You should enter VALUE in Lisp syntax,
7957 so if you want VALUE to be a string, you must surround it with doublequotes.
7958 VALUE is used literally, not evaluated.
7960 If VARIABLE has a `variable-interactive' property, that is used as if
7961 it were the arg to `interactive' (which see) to interactively read VALUE.
7963 If VARIABLE has been defined with `defcustom', then the type information
7964 in the definition is used to check that VALUE is valid.
7966 Note that this function is at heart equivalent to the basic `set' function.
7967 For a variable defined with `defcustom', it does not pay attention to
7968 any :set property that the variable might have (if you want that, use
7969 \\[customize-set-variable] instead).
7971 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7972 (interactive
7973 (let* ((default-var (variable-at-point))
7974 (var (if (custom-variable-p default-var)
7975 (read-variable (format "Set variable (default %s): " default-var)
7976 default-var)
7977 (read-variable "Set variable: ")))
7978 (minibuffer-help-form '(describe-variable var))
7979 (prop (get var 'variable-interactive))
7980 (obsolete (car (get var 'byte-obsolete-variable)))
7981 (prompt (format "Set %s %s to value: " var
7982 (cond ((local-variable-p var)
7983 "(buffer-local)")
7984 ((or current-prefix-arg
7985 (local-variable-if-set-p var))
7986 "buffer-locally")
7987 (t "globally"))))
7988 (val (progn
7989 (when obsolete
7990 (message (concat "`%S' is obsolete; "
7991 (if (symbolp obsolete) "use `%S' instead" "%s"))
7992 var obsolete)
7993 (sit-for 3))
7994 (if prop
7995 ;; Use VAR's `variable-interactive' property
7996 ;; as an interactive spec for prompting.
7997 (call-interactively `(lambda (arg)
7998 (interactive ,prop)
7999 arg))
8000 (read-from-minibuffer prompt nil
8001 read-expression-map t
8002 'set-variable-value-history
8003 (format "%S" (symbol-value var)))))))
8004 (list var val current-prefix-arg)))
8006 (and (custom-variable-p variable)
8007 (not (get variable 'custom-type))
8008 (custom-load-symbol variable))
8009 (let ((type (get variable 'custom-type)))
8010 (when type
8011 ;; Match with custom type.
8012 (require 'cus-edit)
8013 (setq type (widget-convert type))
8014 (unless (widget-apply type :match value)
8015 (user-error "Value `%S' does not match type %S of %S"
8016 value (car type) variable))))
8018 (if make-local
8019 (make-local-variable variable))
8021 (set variable value)
8023 ;; Force a thorough redisplay for the case that the variable
8024 ;; has an effect on the display, like `tab-width' has.
8025 (force-mode-line-update))
8027 ;; Define the major mode for lists of completions.
8029 (defvar completion-list-mode-map
8030 (let ((map (make-sparse-keymap)))
8031 (define-key map [mouse-2] 'choose-completion)
8032 (define-key map [follow-link] 'mouse-face)
8033 (define-key map [down-mouse-2] nil)
8034 (define-key map "\C-m" 'choose-completion)
8035 (define-key map "\e\e\e" 'delete-completion-window)
8036 (define-key map [left] 'previous-completion)
8037 (define-key map [right] 'next-completion)
8038 (define-key map [?\t] 'next-completion)
8039 (define-key map [backtab] 'previous-completion)
8040 (define-key map "q" 'quit-window)
8041 (define-key map "z" 'kill-current-buffer)
8042 map)
8043 "Local map for completion list buffers.")
8045 ;; Completion mode is suitable only for specially formatted data.
8046 (put 'completion-list-mode 'mode-class 'special)
8048 (defvar completion-reference-buffer nil
8049 "Record the buffer that was current when the completion list was requested.
8050 This is a local variable in the completion list buffer.
8051 Initial value is nil to avoid some compiler warnings.")
8053 (defvar completion-no-auto-exit nil
8054 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8055 This also applies to other functions such as `choose-completion'.")
8057 (defvar completion-base-position nil
8058 "Position of the base of the text corresponding to the shown completions.
8059 This variable is used in the *Completions* buffers.
8060 Its value is a list of the form (START END) where START is the place
8061 where the completion should be inserted and END (if non-nil) is the end
8062 of the text to replace. If END is nil, point is used instead.")
8064 (defvar completion-list-insert-choice-function #'completion--replace
8065 "Function to use to insert the text chosen in *Completions*.
8066 Called with three arguments (BEG END TEXT), it should replace the text
8067 between BEG and END with TEXT. Expected to be set buffer-locally
8068 in the *Completions* buffer.")
8070 (defvar completion-base-size nil
8071 "Number of chars before point not involved in completion.
8072 This is a local variable in the completion list buffer.
8073 It refers to the chars in the minibuffer if completing in the
8074 minibuffer, or in `completion-reference-buffer' otherwise.
8075 Only characters in the field at point are included.
8077 If nil, Emacs determines which part of the tail end of the
8078 buffer's text is involved in completion by comparing the text
8079 directly.")
8080 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8082 (defun delete-completion-window ()
8083 "Delete the completion list window.
8084 Go to the window from which completion was requested."
8085 (interactive)
8086 (let ((buf completion-reference-buffer))
8087 (if (one-window-p t)
8088 (if (window-dedicated-p) (delete-frame))
8089 (delete-window (selected-window))
8090 (if (get-buffer-window buf)
8091 (select-window (get-buffer-window buf))))))
8093 (defun previous-completion (n)
8094 "Move to the previous item in the completion list."
8095 (interactive "p")
8096 (next-completion (- n)))
8098 (defun next-completion (n)
8099 "Move to the next item in the completion list.
8100 With prefix argument N, move N items (negative N means move backward)."
8101 (interactive "p")
8102 (let ((beg (point-min)) (end (point-max)))
8103 (while (and (> n 0) (not (eobp)))
8104 ;; If in a completion, move to the end of it.
8105 (when (get-text-property (point) 'mouse-face)
8106 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8107 ;; Move to start of next one.
8108 (unless (get-text-property (point) 'mouse-face)
8109 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8110 (setq n (1- n)))
8111 (while (and (< n 0) (not (bobp)))
8112 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8113 ;; If in a completion, move to the start of it.
8114 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8115 (goto-char (previous-single-property-change
8116 (point) 'mouse-face nil beg)))
8117 ;; Move to end of the previous completion.
8118 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8119 (goto-char (previous-single-property-change
8120 (point) 'mouse-face nil beg)))
8121 ;; Move to the start of that one.
8122 (goto-char (previous-single-property-change
8123 (point) 'mouse-face nil beg))
8124 (setq n (1+ n))))))
8126 (defun choose-completion (&optional event)
8127 "Choose the completion at point.
8128 If EVENT, use EVENT's position to determine the starting position."
8129 (interactive (list last-nonmenu-event))
8130 ;; In case this is run via the mouse, give temporary modes such as
8131 ;; isearch a chance to turn off.
8132 (run-hooks 'mouse-leave-buffer-hook)
8133 (with-current-buffer (window-buffer (posn-window (event-start event)))
8134 (let ((buffer completion-reference-buffer)
8135 (base-size completion-base-size)
8136 (base-position completion-base-position)
8137 (insert-function completion-list-insert-choice-function)
8138 (choice
8139 (save-excursion
8140 (goto-char (posn-point (event-start event)))
8141 (let (beg end)
8142 (cond
8143 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8144 (setq end (point) beg (1+ (point))))
8145 ((and (not (bobp))
8146 (get-text-property (1- (point)) 'mouse-face))
8147 (setq end (1- (point)) beg (point)))
8148 (t (error "No completion here")))
8149 (setq beg (previous-single-property-change beg 'mouse-face))
8150 (setq end (or (next-single-property-change end 'mouse-face)
8151 (point-max)))
8152 (buffer-substring-no-properties beg end)))))
8154 (unless (buffer-live-p buffer)
8155 (error "Destination buffer is dead"))
8156 (quit-window nil (posn-window (event-start event)))
8158 (with-current-buffer buffer
8159 (choose-completion-string
8160 choice buffer
8161 (or base-position
8162 (when base-size
8163 ;; Someone's using old completion code that doesn't know
8164 ;; about base-position yet.
8165 (list (+ base-size (field-beginning))))
8166 ;; If all else fails, just guess.
8167 (list (choose-completion-guess-base-position choice)))
8168 insert-function)))))
8170 ;; Delete the longest partial match for STRING
8171 ;; that can be found before POINT.
8172 (defun choose-completion-guess-base-position (string)
8173 (save-excursion
8174 (let ((opoint (point))
8175 len)
8176 ;; Try moving back by the length of the string.
8177 (goto-char (max (- (point) (length string))
8178 (minibuffer-prompt-end)))
8179 ;; See how far back we were actually able to move. That is the
8180 ;; upper bound on how much we can match and delete.
8181 (setq len (- opoint (point)))
8182 (if completion-ignore-case
8183 (setq string (downcase string)))
8184 (while (and (> len 0)
8185 (let ((tail (buffer-substring (point) opoint)))
8186 (if completion-ignore-case
8187 (setq tail (downcase tail)))
8188 (not (string= tail (substring string 0 len)))))
8189 (setq len (1- len))
8190 (forward-char 1))
8191 (point))))
8193 (defun choose-completion-delete-max-match (string)
8194 (declare (obsolete choose-completion-guess-base-position "23.2"))
8195 (delete-region (choose-completion-guess-base-position string) (point)))
8197 (defvar choose-completion-string-functions nil
8198 "Functions that may override the normal insertion of a completion choice.
8199 These functions are called in order with three arguments:
8200 CHOICE - the string to insert in the buffer,
8201 BUFFER - the buffer in which the choice should be inserted,
8202 BASE-POSITION - where to insert the completion.
8204 If a function in the list returns non-nil, that function is supposed
8205 to have inserted the CHOICE in the BUFFER, and possibly exited
8206 the minibuffer; no further functions will be called.
8208 If all functions in the list return nil, that means to use
8209 the default method of inserting the completion in BUFFER.")
8211 (defun choose-completion-string (choice &optional
8212 buffer base-position insert-function)
8213 "Switch to BUFFER and insert the completion choice CHOICE.
8214 BASE-POSITION says where to insert the completion.
8215 INSERT-FUNCTION says how to insert the completion and falls
8216 back on `completion-list-insert-choice-function' when nil."
8218 ;; If BUFFER is the minibuffer, exit the minibuffer
8219 ;; unless it is reading a file name and CHOICE is a directory,
8220 ;; or completion-no-auto-exit is non-nil.
8222 ;; Some older code may call us passing `base-size' instead of
8223 ;; `base-position'. It's difficult to make any use of `base-size',
8224 ;; so we just ignore it.
8225 (unless (consp base-position)
8226 (message "Obsolete `base-size' passed to choose-completion-string")
8227 (setq base-position nil))
8229 (let* ((buffer (or buffer completion-reference-buffer))
8230 (mini-p (minibufferp buffer)))
8231 ;; If BUFFER is a minibuffer, barf unless it's the currently
8232 ;; active minibuffer.
8233 (if (and mini-p
8234 (not (and (active-minibuffer-window)
8235 (equal buffer
8236 (window-buffer (active-minibuffer-window))))))
8237 (error "Minibuffer is not active for completion")
8238 ;; Set buffer so buffer-local choose-completion-string-functions works.
8239 (set-buffer buffer)
8240 (unless (run-hook-with-args-until-success
8241 'choose-completion-string-functions
8242 ;; The fourth arg used to be `mini-p' but was useless
8243 ;; (since minibufferp can be used on the `buffer' arg)
8244 ;; and indeed unused. The last used to be `base-size', so we
8245 ;; keep it to try and avoid breaking old code.
8246 choice buffer base-position nil)
8247 ;; This remove-text-properties should be unnecessary since `choice'
8248 ;; comes from buffer-substring-no-properties.
8249 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8250 ;; Insert the completion into the buffer where it was requested.
8251 (funcall (or insert-function completion-list-insert-choice-function)
8252 (or (car base-position) (point))
8253 (or (cadr base-position) (point))
8254 choice)
8255 ;; Update point in the window that BUFFER is showing in.
8256 (let ((window (get-buffer-window buffer t)))
8257 (set-window-point window (point)))
8258 ;; If completing for the minibuffer, exit it with this choice.
8259 (and (not completion-no-auto-exit)
8260 (minibufferp buffer)
8261 minibuffer-completion-table
8262 ;; If this is reading a file name, and the file name chosen
8263 ;; is a directory, don't exit the minibuffer.
8264 (let* ((result (buffer-substring (field-beginning) (point)))
8265 (bounds
8266 (completion-boundaries result minibuffer-completion-table
8267 minibuffer-completion-predicate
8268 "")))
8269 (if (eq (car bounds) (length result))
8270 ;; The completion chosen leads to a new set of completions
8271 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8272 (let ((mini (active-minibuffer-window)))
8273 (select-window mini)
8274 (when minibuffer-auto-raise
8275 (raise-frame (window-frame mini))))
8276 (exit-minibuffer))))))))
8278 (define-derived-mode completion-list-mode nil "Completion List"
8279 "Major mode for buffers showing lists of possible completions.
8280 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8281 to select the completion near point.
8282 Or click to select one with the mouse.
8284 \\{completion-list-mode-map}"
8285 (set (make-local-variable 'completion-base-size) nil))
8287 (defun completion-list-mode-finish ()
8288 "Finish setup of the completions buffer.
8289 Called from `temp-buffer-show-hook'."
8290 (when (eq major-mode 'completion-list-mode)
8291 (setq buffer-read-only t)))
8293 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8296 ;; Variables and faces used in `completion-setup-function'.
8298 (defcustom completion-show-help t
8299 "Non-nil means show help message in *Completions* buffer."
8300 :type 'boolean
8301 :version "22.1"
8302 :group 'completion)
8304 ;; This function goes in completion-setup-hook, so that it is called
8305 ;; after the text of the completion list buffer is written.
8306 (defun completion-setup-function ()
8307 (let* ((mainbuf (current-buffer))
8308 (base-dir
8309 ;; FIXME: This is a bad hack. We try to set the default-directory
8310 ;; in the *Completions* buffer so that the relative file names
8311 ;; displayed there can be treated as valid file names, independently
8312 ;; from the completion context. But this suffers from many problems:
8313 ;; - It's not clear when the completions are file names. With some
8314 ;; completion tables (e.g. bzr revision specs), the listed
8315 ;; completions can mix file names and other things.
8316 ;; - It doesn't pay attention to possible quoting.
8317 ;; - With fancy completion styles, the code below will not always
8318 ;; find the right base directory.
8319 (if minibuffer-completing-file-name
8320 (file-name-as-directory
8321 (expand-file-name
8322 (buffer-substring (minibuffer-prompt-end)
8323 (- (point) (or completion-base-size 0))))))))
8324 (with-current-buffer standard-output
8325 (let ((base-size completion-base-size) ;Read before killing localvars.
8326 (base-position completion-base-position)
8327 (insert-fun completion-list-insert-choice-function))
8328 (completion-list-mode)
8329 (set (make-local-variable 'completion-base-size) base-size)
8330 (set (make-local-variable 'completion-base-position) base-position)
8331 (set (make-local-variable 'completion-list-insert-choice-function)
8332 insert-fun))
8333 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8334 (if base-dir (setq default-directory base-dir))
8335 ;; Maybe insert help string.
8336 (when completion-show-help
8337 (goto-char (point-min))
8338 (if (display-mouse-p)
8339 (insert "Click on a completion to select it.\n"))
8340 (insert (substitute-command-keys
8341 "In this buffer, type \\[choose-completion] to \
8342 select the completion near point.\n\n"))))))
8344 (add-hook 'completion-setup-hook 'completion-setup-function)
8346 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8347 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8349 (defun switch-to-completions ()
8350 "Select the completion list window."
8351 (interactive)
8352 (let ((window (or (get-buffer-window "*Completions*" 0)
8353 ;; Make sure we have a completions window.
8354 (progn (minibuffer-completion-help)
8355 (get-buffer-window "*Completions*" 0)))))
8356 (when window
8357 (select-window window)
8358 ;; In the new buffer, go to the first completion.
8359 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8360 (when (bobp)
8361 (next-completion 1)))))
8363 ;;; Support keyboard commands to turn on various modifiers.
8365 ;; These functions -- which are not commands -- each add one modifier
8366 ;; to the following event.
8368 (defun event-apply-alt-modifier (_ignore-prompt)
8369 "\\<function-key-map>Add the Alt modifier to the following event.
8370 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8371 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8372 (defun event-apply-super-modifier (_ignore-prompt)
8373 "\\<function-key-map>Add the Super modifier to the following event.
8374 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8375 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8376 (defun event-apply-hyper-modifier (_ignore-prompt)
8377 "\\<function-key-map>Add the Hyper modifier to the following event.
8378 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8379 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8380 (defun event-apply-shift-modifier (_ignore-prompt)
8381 "\\<function-key-map>Add the Shift modifier to the following event.
8382 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8383 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8384 (defun event-apply-control-modifier (_ignore-prompt)
8385 "\\<function-key-map>Add the Ctrl modifier to the following event.
8386 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8387 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8388 (defun event-apply-meta-modifier (_ignore-prompt)
8389 "\\<function-key-map>Add the Meta modifier to the following event.
8390 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8391 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8393 (defun event-apply-modifier (event symbol lshiftby prefix)
8394 "Apply a modifier flag to event EVENT.
8395 SYMBOL is the name of this modifier, as a symbol.
8396 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8397 PREFIX is the string that represents this modifier in an event type symbol."
8398 (if (numberp event)
8399 (cond ((eq symbol 'control)
8400 (if (and (<= (downcase event) ?z)
8401 (>= (downcase event) ?a))
8402 (- (downcase event) ?a -1)
8403 (if (and (<= (downcase event) ?Z)
8404 (>= (downcase event) ?A))
8405 (- (downcase event) ?A -1)
8406 (logior (lsh 1 lshiftby) event))))
8407 ((eq symbol 'shift)
8408 (if (and (<= (downcase event) ?z)
8409 (>= (downcase event) ?a))
8410 (upcase event)
8411 (logior (lsh 1 lshiftby) event)))
8413 (logior (lsh 1 lshiftby) event)))
8414 (if (memq symbol (event-modifiers event))
8415 event
8416 (let ((event-type (if (symbolp event) event (car event))))
8417 (setq event-type (intern (concat prefix (symbol-name event-type))))
8418 (if (symbolp event)
8419 event-type
8420 (cons event-type (cdr event)))))))
8422 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8423 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8424 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8425 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8426 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8427 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8429 ;;;; Keypad support.
8431 ;; Make the keypad keys act like ordinary typing keys. If people add
8432 ;; bindings for the function key symbols, then those bindings will
8433 ;; override these, so this shouldn't interfere with any existing
8434 ;; bindings.
8436 ;; Also tell read-char how to handle these keys.
8437 (mapc
8438 (lambda (keypad-normal)
8439 (let ((keypad (nth 0 keypad-normal))
8440 (normal (nth 1 keypad-normal)))
8441 (put keypad 'ascii-character normal)
8442 (define-key function-key-map (vector keypad) (vector normal))))
8443 ;; See also kp-keys bound in bindings.el.
8444 '((kp-space ?\s)
8445 (kp-tab ?\t)
8446 (kp-enter ?\r)
8447 (kp-separator ?,)
8448 (kp-equal ?=)
8449 ;; Do the same for various keys that are represented as symbols under
8450 ;; GUIs but naturally correspond to characters.
8451 (backspace 127)
8452 (delete 127)
8453 (tab ?\t)
8454 (linefeed ?\n)
8455 (clear ?\C-l)
8456 (return ?\C-m)
8457 (escape ?\e)
8460 ;;;;
8461 ;;;; forking a twin copy of a buffer.
8462 ;;;;
8464 (defvar clone-buffer-hook nil
8465 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8467 (defvar clone-indirect-buffer-hook nil
8468 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8470 (defun clone-process (process &optional newname)
8471 "Create a twin copy of PROCESS.
8472 If NEWNAME is nil, it defaults to PROCESS' name;
8473 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8474 If PROCESS is associated with a buffer, the new process will be associated
8475 with the current buffer instead.
8476 Returns nil if PROCESS has already terminated."
8477 (setq newname (or newname (process-name process)))
8478 (if (string-match "<[0-9]+>\\'" newname)
8479 (setq newname (substring newname 0 (match-beginning 0))))
8480 (when (memq (process-status process) '(run stop open))
8481 (let* ((process-connection-type (process-tty-name process))
8482 (new-process
8483 (if (memq (process-status process) '(open))
8484 (let ((args (process-contact process t)))
8485 (setq args (plist-put args :name newname))
8486 (setq args (plist-put args :buffer
8487 (if (process-buffer process)
8488 (current-buffer))))
8489 (apply 'make-network-process args))
8490 (apply 'start-process newname
8491 (if (process-buffer process) (current-buffer))
8492 (process-command process)))))
8493 (set-process-query-on-exit-flag
8494 new-process (process-query-on-exit-flag process))
8495 (set-process-inherit-coding-system-flag
8496 new-process (process-inherit-coding-system-flag process))
8497 (set-process-filter new-process (process-filter process))
8498 (set-process-sentinel new-process (process-sentinel process))
8499 (set-process-plist new-process (copy-sequence (process-plist process)))
8500 new-process)))
8502 ;; things to maybe add (currently partly covered by `funcall mode'):
8503 ;; - syntax-table
8504 ;; - overlays
8505 (defun clone-buffer (&optional newname display-flag)
8506 "Create and return a twin copy of the current buffer.
8507 Unlike an indirect buffer, the new buffer can be edited
8508 independently of the old one (if it is not read-only).
8509 NEWNAME is the name of the new buffer. It may be modified by
8510 adding or incrementing <N> at the end as necessary to create a
8511 unique buffer name. If nil, it defaults to the name of the
8512 current buffer, with the proper suffix. If DISPLAY-FLAG is
8513 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8514 clone a file-visiting buffer, or a buffer whose major mode symbol
8515 has a non-nil `no-clone' property, results in an error.
8517 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8518 current buffer with appropriate suffix. However, if a prefix
8519 argument is given, then the command prompts for NEWNAME in the
8520 minibuffer.
8522 This runs the normal hook `clone-buffer-hook' in the new buffer
8523 after it has been set up properly in other respects."
8524 (interactive
8525 (progn
8526 (if buffer-file-name
8527 (error "Cannot clone a file-visiting buffer"))
8528 (if (get major-mode 'no-clone)
8529 (error "Cannot clone a buffer in %s mode" mode-name))
8530 (list (if current-prefix-arg
8531 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8532 t)))
8533 (if buffer-file-name
8534 (error "Cannot clone a file-visiting buffer"))
8535 (if (get major-mode 'no-clone)
8536 (error "Cannot clone a buffer in %s mode" mode-name))
8537 (setq newname (or newname (buffer-name)))
8538 (if (string-match "<[0-9]+>\\'" newname)
8539 (setq newname (substring newname 0 (match-beginning 0))))
8540 (let ((buf (current-buffer))
8541 (ptmin (point-min))
8542 (ptmax (point-max))
8543 (pt (point))
8544 (mk (if mark-active (mark t)))
8545 (modified (buffer-modified-p))
8546 (mode major-mode)
8547 (lvars (buffer-local-variables))
8548 (process (get-buffer-process (current-buffer)))
8549 (new (generate-new-buffer (or newname (buffer-name)))))
8550 (save-restriction
8551 (widen)
8552 (with-current-buffer new
8553 (insert-buffer-substring buf)))
8554 (with-current-buffer new
8555 (narrow-to-region ptmin ptmax)
8556 (goto-char pt)
8557 (if mk (set-mark mk))
8558 (set-buffer-modified-p modified)
8560 ;; Clone the old buffer's process, if any.
8561 (when process (clone-process process))
8563 ;; Now set up the major mode.
8564 (funcall mode)
8566 ;; Set up other local variables.
8567 (mapc (lambda (v)
8568 (condition-case ()
8569 (if (symbolp v)
8570 (makunbound v)
8571 (set (make-local-variable (car v)) (cdr v)))
8572 (setting-constant nil))) ;E.g. for enable-multibyte-characters.
8573 lvars)
8575 (setq mark-ring (mapcar (lambda (mk) (copy-marker (marker-position mk)))
8576 mark-ring))
8578 ;; Run any hooks (typically set up by the major mode
8579 ;; for cloning to work properly).
8580 (run-hooks 'clone-buffer-hook))
8581 (if display-flag
8582 ;; Presumably the current buffer is shown in the selected frame, so
8583 ;; we want to display the clone elsewhere.
8584 (let ((same-window-regexps nil)
8585 (same-window-buffer-names))
8586 (pop-to-buffer new)))
8587 new))
8590 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8591 "Create an indirect buffer that is a twin copy of the current buffer.
8593 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8594 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8595 or if not called with a prefix arg, NEWNAME defaults to the current
8596 buffer's name. The name is modified by adding a `<N>' suffix to it
8597 or by incrementing the N in an existing suffix. Trying to clone a
8598 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8599 property results in an error.
8601 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8602 This is always done when called interactively.
8604 Optional third arg NORECORD non-nil means do not put this buffer at the
8605 front of the list of recently selected ones.
8607 Returns the newly created indirect buffer."
8608 (interactive
8609 (progn
8610 (if (get major-mode 'no-clone-indirect)
8611 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8612 (list (if current-prefix-arg
8613 (read-buffer "Name of indirect buffer: " (current-buffer)))
8614 t)))
8615 (if (get major-mode 'no-clone-indirect)
8616 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8617 (setq newname (or newname (buffer-name)))
8618 (if (string-match "<[0-9]+>\\'" newname)
8619 (setq newname (substring newname 0 (match-beginning 0))))
8620 (let* ((name (generate-new-buffer-name newname))
8621 (buffer (make-indirect-buffer (current-buffer) name t)))
8622 (with-current-buffer buffer
8623 (run-hooks 'clone-indirect-buffer-hook))
8624 (when display-flag
8625 (pop-to-buffer buffer nil norecord))
8626 buffer))
8629 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8630 "Like `clone-indirect-buffer' but display in another window."
8631 (interactive
8632 (progn
8633 (if (get major-mode 'no-clone-indirect)
8634 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8635 (list (if current-prefix-arg
8636 (read-buffer "Name of indirect buffer: " (current-buffer)))
8637 t)))
8638 (let ((pop-up-windows t))
8639 (clone-indirect-buffer newname display-flag norecord)))
8642 ;;; Handling of Backspace and Delete keys.
8644 (defcustom normal-erase-is-backspace 'maybe
8645 "Set the default behavior of the Delete and Backspace keys.
8647 If set to t, Delete key deletes forward and Backspace key deletes
8648 backward.
8650 If set to nil, both Delete and Backspace keys delete backward.
8652 If set to `maybe' (which is the default), Emacs automatically
8653 selects a behavior. On window systems, the behavior depends on
8654 the keyboard used. If the keyboard has both a Backspace key and
8655 a Delete key, and both are mapped to their usual meanings, the
8656 option's default value is set to t, so that Backspace can be used
8657 to delete backward, and Delete can be used to delete forward.
8659 If not running under a window system, customizing this option
8660 accomplishes a similar effect by mapping C-h, which is usually
8661 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8662 via `keyboard-translate'. The former functionality of C-h is
8663 available on the F1 key. You should probably not use this
8664 setting if you don't have both Backspace, Delete and F1 keys.
8666 Setting this variable with setq doesn't take effect. Programmatically,
8667 call `normal-erase-is-backspace-mode' (which see) instead."
8668 :type '(choice (const :tag "Off" nil)
8669 (const :tag "Maybe" maybe)
8670 (other :tag "On" t))
8671 :group 'editing-basics
8672 :version "21.1"
8673 :set (lambda (symbol value)
8674 ;; The fboundp is because of a problem with :set when
8675 ;; dumping Emacs. It doesn't really matter.
8676 (if (fboundp 'normal-erase-is-backspace-mode)
8677 (normal-erase-is-backspace-mode (or value 0))
8678 (set-default symbol value))))
8680 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8681 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8682 (unless frame (setq frame (selected-frame)))
8683 (with-selected-frame frame
8684 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8685 (normal-erase-is-backspace-mode
8686 (if (if (eq normal-erase-is-backspace 'maybe)
8687 (and (not noninteractive)
8688 (or (memq system-type '(ms-dos windows-nt))
8689 (memq window-system '(w32 ns))
8690 (and (memq window-system '(x))
8691 (fboundp 'x-backspace-delete-keys-p)
8692 (x-backspace-delete-keys-p))
8693 ;; If the terminal Emacs is running on has erase char
8694 ;; set to ^H, use the Backspace key for deleting
8695 ;; backward, and the Delete key for deleting forward.
8696 (and (null window-system)
8697 (eq tty-erase-char ?\^H))))
8698 normal-erase-is-backspace)
8699 1 0)))))
8701 (define-minor-mode normal-erase-is-backspace-mode
8702 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8703 With a prefix argument ARG, enable this feature if ARG is
8704 positive, and disable it otherwise. If called from Lisp, enable
8705 the mode if ARG is omitted or nil.
8707 On window systems, when this mode is on, Delete is mapped to C-d
8708 and Backspace is mapped to DEL; when this mode is off, both
8709 Delete and Backspace are mapped to DEL. (The remapping goes via
8710 `local-function-key-map', so binding Delete or Backspace in the
8711 global or local keymap will override that.)
8713 In addition, on window systems, the bindings of C-Delete, M-Delete,
8714 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8715 the global keymap in accordance with the functionality of Delete and
8716 Backspace. For example, if Delete is remapped to C-d, which deletes
8717 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8718 to DEL, which deletes backward, C-Delete is bound to
8719 `backward-kill-word'.
8721 If not running on a window system, a similar effect is accomplished by
8722 remapping C-h (normally produced by the Backspace key) and DEL via
8723 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8724 to C-d; if it's off, the keys are not remapped.
8726 When not running on a window system, and this mode is turned on, the
8727 former functionality of C-h is available on the F1 key. You should
8728 probably not turn on this mode on a text-only terminal if you don't
8729 have both Backspace, Delete and F1 keys.
8731 See also `normal-erase-is-backspace'."
8732 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8733 . (lambda (v)
8734 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8735 (if v 1 0))))
8736 (let ((enabled (eq 1 (terminal-parameter
8737 nil 'normal-erase-is-backspace))))
8739 (cond ((or (memq window-system '(x w32 ns pc))
8740 (memq system-type '(ms-dos windows-nt)))
8741 (let ((bindings
8742 `(([M-delete] [M-backspace])
8743 ([C-M-delete] [C-M-backspace])
8744 ([?\e C-delete] [?\e C-backspace]))))
8746 (if enabled
8747 (progn
8748 (define-key local-function-key-map [delete] [deletechar])
8749 (define-key local-function-key-map [kp-delete] [deletechar])
8750 (define-key local-function-key-map [backspace] [?\C-?])
8751 (dolist (b bindings)
8752 ;; Not sure if input-decode-map is really right, but
8753 ;; keyboard-translate-table (used below) only works
8754 ;; for integer events, and key-translation-table is
8755 ;; global (like the global-map, used earlier).
8756 (define-key input-decode-map (car b) nil)
8757 (define-key input-decode-map (cadr b) nil)))
8758 (define-key local-function-key-map [delete] [?\C-?])
8759 (define-key local-function-key-map [kp-delete] [?\C-?])
8760 (define-key local-function-key-map [backspace] [?\C-?])
8761 (dolist (b bindings)
8762 (define-key input-decode-map (car b) (cadr b))
8763 (define-key input-decode-map (cadr b) (car b))))))
8765 (if enabled
8766 (progn
8767 (keyboard-translate ?\C-h ?\C-?)
8768 (keyboard-translate ?\C-? ?\C-d))
8769 (keyboard-translate ?\C-h ?\C-h)
8770 (keyboard-translate ?\C-? ?\C-?))))
8772 (if (called-interactively-p 'interactive)
8773 (message "Delete key deletes %s"
8774 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8775 "forward" "backward")))))
8777 (defvar vis-mode-saved-buffer-invisibility-spec nil
8778 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8780 (define-minor-mode read-only-mode
8781 "Change whether the current buffer is read-only.
8782 With prefix argument ARG, make the buffer read-only if ARG is
8783 positive, otherwise make it writable. If buffer is read-only
8784 and `view-read-only' is non-nil, enter view mode.
8786 Do not call this from a Lisp program unless you really intend to
8787 do the same thing as the \\[read-only-mode] command, including
8788 possibly enabling or disabling View mode. Also, note that this
8789 command works by setting the variable `buffer-read-only', which
8790 does not affect read-only regions caused by text properties. To
8791 ignore read-only status in a Lisp program (whether due to text
8792 properties or buffer state), bind `inhibit-read-only' temporarily
8793 to a non-nil value."
8794 :variable buffer-read-only
8795 (cond
8796 ((and (not buffer-read-only) view-mode)
8797 (View-exit-and-edit)
8798 (make-local-variable 'view-read-only)
8799 (setq view-read-only t)) ; Must leave view mode.
8800 ((and buffer-read-only view-read-only
8801 ;; If view-mode is already active, `view-mode-enter' is a nop.
8802 (not view-mode)
8803 (not (eq (get major-mode 'mode-class) 'special)))
8804 (view-mode-enter))))
8806 (define-minor-mode visible-mode
8807 "Toggle making all invisible text temporarily visible (Visible mode).
8808 With a prefix argument ARG, enable Visible mode if ARG is
8809 positive, and disable it otherwise. If called from Lisp, enable
8810 the mode if ARG is omitted or nil.
8812 This mode works by saving the value of `buffer-invisibility-spec'
8813 and setting it to nil."
8814 :lighter " Vis"
8815 :group 'editing-basics
8816 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8817 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8818 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8819 (when visible-mode
8820 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8821 buffer-invisibility-spec)
8822 (setq buffer-invisibility-spec nil)))
8824 (defvar messages-buffer-mode-map
8825 (let ((map (make-sparse-keymap)))
8826 (set-keymap-parent map special-mode-map)
8827 (define-key map "g" nil) ; nothing to revert
8828 map))
8830 (define-derived-mode messages-buffer-mode special-mode "Messages"
8831 "Major mode used in the \"*Messages*\" buffer.")
8833 (defun messages-buffer ()
8834 "Return the \"*Messages*\" buffer.
8835 If it does not exist, create and it switch it to `messages-buffer-mode'."
8836 (or (get-buffer "*Messages*")
8837 (with-current-buffer (get-buffer-create "*Messages*")
8838 (messages-buffer-mode)
8839 (current-buffer))))
8842 ;; Minibuffer prompt stuff.
8844 ;;(defun minibuffer-prompt-modification (start end)
8845 ;; (error "You cannot modify the prompt"))
8848 ;;(defun minibuffer-prompt-insertion (start end)
8849 ;; (let ((inhibit-modification-hooks t))
8850 ;; (delete-region start end)
8851 ;; ;; Discard undo information for the text insertion itself
8852 ;; ;; and for the text deletion.above.
8853 ;; (when (consp buffer-undo-list)
8854 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8855 ;; (message "You cannot modify the prompt")))
8858 ;;(setq minibuffer-prompt-properties
8859 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8860 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8863 ;;;; Problematic external packages.
8865 ;; rms says this should be done by specifying symbols that define
8866 ;; versions together with bad values. This is therefore not as
8867 ;; flexible as it could be. See the thread:
8868 ;; https://lists.gnu.org/r/emacs-devel/2007-08/msg00300.html
8869 (defconst bad-packages-alist
8870 ;; Not sure exactly which semantic versions have problems.
8871 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8872 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8873 "The version of `semantic' loaded does not work in Emacs 22.
8874 It can cause constant high CPU load.
8875 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8876 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8877 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8878 ;; provided the `CUA-mode' feature. Since this is no longer true,
8879 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8880 (CUA-mode t nil
8881 "CUA-mode is now part of the standard GNU Emacs distribution,
8882 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8884 You have loaded an older version of CUA-mode which does not work
8885 correctly with this version of Emacs. You should remove the old
8886 version and use the one distributed with Emacs."))
8887 "Alist of packages known to cause problems in this version of Emacs.
8888 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8889 PACKAGE is either a regular expression to match file names, or a
8890 symbol (a feature name), like for `with-eval-after-load'.
8891 SYMBOL is either the name of a string variable, or t. Upon
8892 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8893 warning using STRING as the message.")
8895 (defun bad-package-check (package)
8896 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8897 (condition-case nil
8898 (let* ((list (assoc package bad-packages-alist))
8899 (symbol (nth 1 list)))
8900 (and list
8901 (boundp symbol)
8902 (or (eq symbol t)
8903 (and (stringp (setq symbol (eval symbol)))
8904 (string-match-p (nth 2 list) symbol)))
8905 (display-warning package (nth 3 list) :warning)))
8906 (error nil)))
8908 (dolist (elem bad-packages-alist)
8909 (let ((pkg (car elem)))
8910 (with-eval-after-load pkg
8911 (bad-package-check pkg))))
8914 ;;; Generic dispatcher commands
8916 ;; Macro `define-alternatives' is used to create generic commands.
8917 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8918 ;; that can have different alternative implementations where choosing
8919 ;; among them is exclusively a matter of user preference.
8921 ;; (define-alternatives COMMAND) creates a new interactive command
8922 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8923 ;; Typically, the user will not need to customize this variable; packages
8924 ;; wanting to add alternative implementations should use
8926 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8928 (defmacro define-alternatives (command &rest customizations)
8929 "Define the new command `COMMAND'.
8931 The argument `COMMAND' should be a symbol.
8933 Running `M-x COMMAND RET' for the first time prompts for which
8934 alternative to use and records the selected command as a custom
8935 variable.
8937 Running `C-u M-x COMMAND RET' prompts again for an alternative
8938 and overwrites the previous choice.
8940 The variable `COMMAND-alternatives' contains an alist with
8941 alternative implementations of COMMAND. `define-alternatives'
8942 does not have any effect until this variable is set.
8944 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8945 `defcustom' keywords and values to add to the declaration of
8946 `COMMAND-alternatives' (typically :group and :version)."
8947 (let* ((command-name (symbol-name command))
8948 (varalt-name (concat command-name "-alternatives"))
8949 (varalt-sym (intern varalt-name))
8950 (varimp-sym (intern (concat command-name "--implementation"))))
8951 `(progn
8953 (defcustom ,varalt-sym nil
8954 ,(format "Alist of alternative implementations for the `%s' command.
8956 Each entry must be a pair (ALTNAME . ALTFUN), where:
8957 ALTNAME - The name shown at user to describe the alternative implementation.
8958 ALTFUN - The function called to implement this alternative."
8959 command-name)
8960 :type '(alist :key-type string :value-type function)
8961 ,@customizations)
8963 (put ',varalt-sym 'definition-name ',command)
8964 (defvar ,varimp-sym nil "Internal use only.")
8966 (defun ,command (&optional arg)
8967 ,(format "Run generic command `%s'.
8968 If used for the first time, or with interactive ARG, ask the user which
8969 implementation to use for `%s'. The variable `%s'
8970 contains the list of implementations currently supported for this command."
8971 command-name command-name varalt-name)
8972 (interactive "P")
8973 (when (or arg (null ,varimp-sym))
8974 (let ((val (completing-read
8975 ,(format-message
8976 "Select implementation for command `%s': "
8977 command-name)
8978 ,varalt-sym nil t)))
8979 (unless (string-equal val "")
8980 (when (null ,varimp-sym)
8981 (message
8982 "Use C-u M-x %s RET`to select another implementation"
8983 ,command-name)
8984 (sit-for 3))
8985 (customize-save-variable ',varimp-sym
8986 (cdr (assoc-string val ,varalt-sym))))))
8987 (if ,varimp-sym
8988 (call-interactively ,varimp-sym)
8989 (message "%s" ,(format-message
8990 "No implementation selected for command `%s'"
8991 command-name)))))))
8994 ;;; Functions for changing capitalization that Do What I Mean
8995 (defun upcase-dwim (arg)
8996 "Upcase words in the region, if active; if not, upcase word at point.
8997 If the region is active, this function calls `upcase-region'.
8998 Otherwise, it calls `upcase-word', with prefix argument passed to it
8999 to upcase ARG words."
9000 (interactive "*p")
9001 (if (use-region-p)
9002 (upcase-region (region-beginning) (region-end) (region-noncontiguous-p))
9003 (upcase-word arg)))
9005 (defun downcase-dwim (arg)
9006 "Downcase words in the region, if active; if not, downcase word at point.
9007 If the region is active, this function calls `downcase-region'.
9008 Otherwise, it calls `downcase-word', with prefix argument passed to it
9009 to downcase ARG words."
9010 (interactive "*p")
9011 (if (use-region-p)
9012 (downcase-region (region-beginning) (region-end) (region-noncontiguous-p))
9013 (downcase-word arg)))
9015 (defun capitalize-dwim (arg)
9016 "Capitalize words in the region, if active; if not, capitalize word at point.
9017 If the region is active, this function calls `capitalize-region'.
9018 Otherwise, it calls `capitalize-word', with prefix argument passed to it
9019 to capitalize ARG words."
9020 (interactive "*p")
9021 (if (use-region-p)
9022 (capitalize-region (region-beginning) (region-end))
9023 (capitalize-word arg)))
9027 (provide 'simple)
9029 ;;; simple.el ends here