* lisp/loadhist.el (unload-hook-features-list): Remove obsolete alias.
[emacs.git] / lisp / simple.el
blobfa93cf87c7aa3f3030d39c261a93920e87bce708
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 ;; next-error-last-buffer is made buffer-local to keep the reference
126 ;; to the parent buffer used to navigate to the current buffer, so the
127 ;; next call of next-buffer will use the same parent buffer to
128 ;; continue navigation from it.
129 (make-variable-buffer-local 'next-error-last-buffer)
131 (defvar next-error-function nil
132 "Function to use to find the next error in the current buffer.
133 The function is called with 2 parameters:
134 ARG is an integer specifying by how many errors to move.
135 RESET is a boolean which, if non-nil, says to go back to the beginning
136 of the errors before moving.
137 Major modes providing compile-like functionality should set this variable
138 to indicate to `next-error' that this is a candidate buffer and how
139 to navigate in it.")
140 (make-variable-buffer-local 'next-error-function)
142 (defvar next-error-move-function nil
143 "Function to use to move to an error locus.
144 It takes two arguments, a buffer position in the error buffer
145 and a buffer position in the error locus buffer.
146 The buffer for the error locus should already be current.
147 nil means use goto-char using the second argument position.")
148 (make-variable-buffer-local 'next-error-move-function)
150 (defsubst next-error-buffer-p (buffer
151 &optional avoid-current
152 extra-test-inclusive
153 extra-test-exclusive)
154 "Return non-nil if BUFFER is a `next-error' capable buffer.
155 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
156 return nil.
158 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
159 BUFFER would not normally qualify. If it returns non-nil, BUFFER
160 is considered `next-error' capable, anyway, and the function
161 returns non-nil.
163 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
164 buffer would normally qualify. If it returns nil, BUFFER is
165 rejected, and the function returns nil."
166 (and (buffer-name buffer) ;First make sure it's live.
167 (not (and avoid-current (eq buffer (current-buffer))))
168 (with-current-buffer buffer
169 (if next-error-function ; This is the normal test.
170 ;; Optionally reject some buffers.
171 (if extra-test-exclusive
172 (funcall extra-test-exclusive)
174 ;; Optionally accept some other buffers.
175 (and extra-test-inclusive
176 (funcall extra-test-inclusive))))))
178 (defcustom next-error-find-buffer-function #'ignore
179 "Function called to find a `next-error' capable buffer."
180 :type '(choice (const :tag "Single next-error capable buffer on selected frame"
181 next-error-buffer-on-selected-frame)
182 (const :tag "No default" ignore)
183 (function :tag "Other function"))
184 :group 'next-error
185 :version "27.1")
187 (defun next-error-buffer-on-selected-frame (&optional avoid-current
188 extra-test-inclusive
189 extra-test-exclusive)
190 "Return a single visible next-error buffer on the selected frame."
191 (let ((window-buffers
192 (delete-dups
193 (delq nil (mapcar (lambda (w)
194 (if (next-error-buffer-p
195 (window-buffer w)
196 avoid-current
197 extra-test-inclusive extra-test-exclusive)
198 (window-buffer w)))
199 (window-list))))))
200 (if (eq (length window-buffers) 1)
201 (car window-buffers))))
203 (defun next-error-find-buffer (&optional avoid-current
204 extra-test-inclusive
205 extra-test-exclusive)
206 "Return a `next-error' capable buffer.
208 If AVOID-CURRENT is non-nil, treat the current buffer
209 as an absolute last resort only.
211 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
212 that normally would not qualify. If it returns t, the buffer
213 in question is treated as usable.
215 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
216 that would normally be considered usable. If it returns nil,
217 that buffer is rejected."
219 ;; 1. If a customizable function returns a buffer, use it.
220 (funcall next-error-find-buffer-function avoid-current
221 extra-test-inclusive
222 extra-test-exclusive)
223 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
224 (if (and next-error-last-buffer
225 (next-error-buffer-p next-error-last-buffer avoid-current
226 extra-test-inclusive extra-test-exclusive))
227 next-error-last-buffer)
228 ;; 3. If the current buffer is acceptable, choose it.
229 (if (next-error-buffer-p (current-buffer) avoid-current
230 extra-test-inclusive extra-test-exclusive)
231 (current-buffer))
232 ;; 4. Look for any acceptable buffer.
233 (let ((buffers (buffer-list)))
234 (while (and buffers
235 (not (next-error-buffer-p
236 (car buffers) avoid-current
237 extra-test-inclusive extra-test-exclusive)))
238 (setq buffers (cdr buffers)))
239 (car buffers))
240 ;; 5. Use the current buffer as a last resort if it qualifies,
241 ;; even despite AVOID-CURRENT.
242 (and avoid-current
243 (next-error-buffer-p (current-buffer) nil
244 extra-test-inclusive extra-test-exclusive)
245 (progn
246 (message "This is the only buffer with error message locations")
247 (current-buffer)))
248 ;; 6. Give up.
249 (error "No buffers contain error message locations")))
251 (defun next-error (&optional arg reset)
252 "Visit next `next-error' message and corresponding source code.
254 If all the error messages parsed so far have been processed already,
255 the message buffer is checked for new ones.
257 A prefix ARG specifies how many error messages to move;
258 negative means move back to previous error messages.
259 Just \\[universal-argument] as a prefix means reparse the error message buffer
260 and start at the first error.
262 The RESET argument specifies that we should restart from the beginning.
264 \\[next-error] normally uses the most recently started
265 compilation, grep, or occur buffer. It can also operate on any
266 buffer with output from the \\[compile], \\[grep] commands, or,
267 more generally, on any buffer in Compilation mode or with
268 Compilation Minor mode enabled, or any buffer in which
269 `next-error-function' is bound to an appropriate function.
270 To specify use of a particular buffer for error messages, type
271 \\[next-error] in that buffer when it is the only one displayed
272 in the current frame.
274 Once \\[next-error] has chosen the buffer for error messages, it
275 runs `next-error-hook' with `run-hooks', and stays with that buffer
276 until you use it in some other buffer which uses Compilation mode
277 or Compilation Minor mode.
279 To control which errors are matched, customize the variable
280 `compilation-error-regexp-alist'."
281 (interactive "P")
282 (if (consp arg) (setq reset t arg nil))
283 (let ((buffer (next-error-find-buffer)))
284 (when buffer
285 ;; We know here that next-error-function is a valid symbol we can funcall
286 (with-current-buffer buffer
287 ;; Allow next-error to be used from the next-error capable buffer.
288 (setq next-error-last-buffer buffer)
289 (funcall next-error-function (prefix-numeric-value arg) reset)
290 ;; Override possible change of next-error-last-buffer in next-error-function
291 (setq next-error-last-buffer buffer)
292 (setq-default next-error-last-buffer buffer)
293 (when next-error-recenter
294 (recenter next-error-recenter))
295 (message "%s error from %s"
296 (cond (reset "First")
297 ((eq (prefix-numeric-value arg) 0) "Current")
298 ((< (prefix-numeric-value arg) 0) "Previous")
299 (t "Next"))
300 next-error-last-buffer)
301 (run-hooks 'next-error-hook)))))
303 (defun next-error-internal ()
304 "Visit the source code corresponding to the `next-error' message at point."
305 (let ((buffer (current-buffer)))
306 ;; We know here that next-error-function is a valid symbol we can funcall
307 (with-current-buffer buffer
308 ;; Allow next-error to be used from the next-error capable buffer.
309 (setq next-error-last-buffer buffer)
310 (funcall next-error-function 0 nil)
311 ;; Override possible change of next-error-last-buffer in next-error-function
312 (setq next-error-last-buffer buffer)
313 (setq-default next-error-last-buffer buffer)
314 (when next-error-recenter
315 (recenter next-error-recenter))
316 (message "Current error from %s" next-error-last-buffer)
317 (run-hooks 'next-error-hook))))
319 (defun next-error-select-buffer (buffer)
320 "Select a `next-error' capable buffer and set it as the last used."
321 (interactive
322 (list (get-buffer
323 (read-buffer "Select next-error buffer: " nil nil
324 (lambda (b) (next-error-buffer-p (cdr b)))))))
325 (setq next-error-last-buffer buffer)
326 (setq-default next-error-last-buffer buffer))
328 (defalias 'goto-next-locus 'next-error)
329 (defalias 'next-match 'next-error)
331 (defun previous-error (&optional n)
332 "Visit previous `next-error' message and corresponding source code.
334 Prefix arg N says how many error messages to move backwards (or
335 forwards, if negative).
337 This operates on the output from the \\[compile] and \\[grep] commands."
338 (interactive "p")
339 (next-error (- (or n 1))))
341 (defun first-error (&optional n)
342 "Restart at the first error.
343 Visit corresponding source code.
344 With prefix arg N, visit the source code of the Nth error.
345 This operates on the output from the \\[compile] command, for instance."
346 (interactive "p")
347 (next-error n t))
349 (defun next-error-no-select (&optional n)
350 "Move point to the next error in the `next-error' buffer and highlight match.
351 Prefix arg N says how many error messages to move forwards (or
352 backwards, if negative).
353 Finds and highlights the source line like \\[next-error], but does not
354 select the source buffer."
355 (interactive "p")
356 (let ((next-error-highlight next-error-highlight-no-select))
357 (next-error n))
358 (pop-to-buffer next-error-last-buffer))
360 (defun previous-error-no-select (&optional n)
361 "Move point to the previous error in the `next-error' buffer and highlight match.
362 Prefix arg N says how many error messages to move backwards (or
363 forwards, if negative).
364 Finds and highlights the source line like \\[previous-error], but does not
365 select the source buffer."
366 (interactive "p")
367 (next-error-no-select (- (or n 1))))
369 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
370 (defvar next-error-follow-last-line nil)
372 (define-minor-mode next-error-follow-minor-mode
373 "Minor mode for compilation, occur and diff modes.
374 With a prefix argument ARG, enable mode if ARG is positive, and
375 disable it otherwise. If called from Lisp, enable mode if ARG is
376 omitted or nil.
377 When turned on, cursor motion in the compilation, grep, occur or diff
378 buffer causes automatic display of the corresponding source code location."
379 :group 'next-error :init-value nil :lighter " Fol"
380 (if (not next-error-follow-minor-mode)
381 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
382 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
383 (make-local-variable 'next-error-follow-last-line)))
385 ;; Used as a `post-command-hook' by `next-error-follow-mode'
386 ;; for the *Compilation* *grep* and *Occur* buffers.
387 (defun next-error-follow-mode-post-command-hook ()
388 (unless (equal next-error-follow-last-line (line-number-at-pos))
389 (setq next-error-follow-last-line (line-number-at-pos))
390 (condition-case nil
391 (let ((compilation-context-lines nil))
392 (setq compilation-current-error (point))
393 (next-error-no-select 0))
394 (error t))))
399 (defun fundamental-mode ()
400 "Major mode not specialized for anything in particular.
401 Other major modes are defined by comparison with this one."
402 (interactive)
403 (kill-all-local-variables)
404 (run-mode-hooks))
406 ;; Special major modes to view specially formatted data rather than files.
408 (defvar special-mode-map
409 (let ((map (make-sparse-keymap)))
410 (suppress-keymap map)
411 (define-key map "q" 'quit-window)
412 (define-key map " " 'scroll-up-command)
413 (define-key map [?\S-\ ] 'scroll-down-command)
414 (define-key map "\C-?" 'scroll-down-command)
415 (define-key map "?" 'describe-mode)
416 (define-key map "h" 'describe-mode)
417 (define-key map ">" 'end-of-buffer)
418 (define-key map "<" 'beginning-of-buffer)
419 (define-key map "g" 'revert-buffer)
420 map))
422 (put 'special-mode 'mode-class 'special)
423 (define-derived-mode special-mode nil "Special"
424 "Parent major mode from which special major modes should inherit."
425 (setq buffer-read-only t))
427 ;; Making and deleting lines.
429 (defvar self-insert-uses-region-functions nil
430 "Special hook to tell if `self-insert-command' will use the region.
431 It must be called via `run-hook-with-args-until-success' with no arguments.
433 If any function on this hook returns a non-nil value, `delete-selection-mode'
434 will act on that value (see `delete-selection-helper'), and will
435 usually delete the region. If all the functions on this hook return
436 nil, it is an indiction that `self-insert-command' needs the region
437 untouched by `delete-selection-mode', and will itself do whatever is
438 appropriate with the region.
439 Any function on `post-self-insert-hook' which act on the region should
440 add a function to this hook so that `delete-selection-mode' could
441 refrain from deleting the region before `post-self-insert-hook'
442 functions are called.
443 This hook is run by `delete-selection-uses-region-p', which see.")
445 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
446 "Propertized string representing a hard newline character.")
448 (defun newline (&optional arg interactive)
449 "Insert a newline, and move to left margin of the new line if it's blank.
450 If option `use-hard-newlines' is non-nil, the newline is marked with the
451 text-property `hard'.
452 With ARG, insert that many newlines.
454 If `electric-indent-mode' is enabled, this indents the final new line
455 that it adds, and reindents the preceding line. To just insert
456 a newline, use \\[electric-indent-just-newline].
458 Calls `auto-fill-function' if the current column number is greater
459 than the value of `fill-column' and ARG is nil.
460 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
461 (interactive "*P\np")
462 (barf-if-buffer-read-only)
463 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
464 ;; Set last-command-event to tell self-insert what to insert.
465 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
466 (beforepos (point))
467 (last-command-event ?\n)
468 ;; Don't auto-fill if we have a numeric argument.
469 (auto-fill-function (if arg nil auto-fill-function))
470 (arg (prefix-numeric-value arg))
471 (postproc
472 ;; Do the rest in post-self-insert-hook, because we want to do it
473 ;; *before* other functions on that hook.
474 (lambda ()
475 ;; Mark the newline(s) `hard'.
476 (if use-hard-newlines
477 (set-hard-newline-properties
478 (- (point) arg) (point)))
479 ;; If the newline leaves the previous line blank, and we
480 ;; have a left margin, delete that from the blank line.
481 (save-excursion
482 (goto-char beforepos)
483 (beginning-of-line)
484 (and (looking-at "[ \t]$")
485 (> (current-left-margin) 0)
486 (delete-region (point)
487 (line-end-position))))
488 ;; Indent the line after the newline, except in one case:
489 ;; when we added the newline at the beginning of a line which
490 ;; starts a page.
491 (or was-page-start
492 (move-to-left-margin nil t)))))
493 (if (not interactive)
494 ;; FIXME: For non-interactive uses, many calls actually
495 ;; just want (insert "\n"), so maybe we should do just
496 ;; that, so as to avoid the risk of filling or running
497 ;; abbrevs unexpectedly.
498 (let ((post-self-insert-hook (list postproc)))
499 (self-insert-command arg))
500 (unwind-protect
501 (progn
502 (add-hook 'post-self-insert-hook postproc nil t)
503 (self-insert-command arg))
504 ;; We first used let-binding to protect the hook, but that
505 ;; was naive since add-hook affects the symbol-default
506 ;; value of the variable, whereas the let-binding might
507 ;; only protect the buffer-local value.
508 (remove-hook 'post-self-insert-hook postproc t))))
509 nil)
511 (defun set-hard-newline-properties (from to)
512 (let ((sticky (get-text-property from 'rear-nonsticky)))
513 (put-text-property from to 'hard 't)
514 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
515 (if (and (listp sticky) (not (memq 'hard sticky)))
516 (put-text-property from (point) 'rear-nonsticky
517 (cons 'hard sticky)))))
519 (defun open-line (n)
520 "Insert a newline and leave point before it.
521 If there is a fill prefix and/or a `left-margin', insert them on
522 the new line if the line would have been blank.
523 With arg N, insert N newlines."
524 (interactive "*p")
525 (let* ((do-fill-prefix (and fill-prefix (bolp)))
526 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
527 (loc (point-marker))
528 ;; Don't expand an abbrev before point.
529 (abbrev-mode nil))
530 (newline n)
531 (goto-char loc)
532 (while (> n 0)
533 (cond ((bolp)
534 (if do-left-margin (indent-to (current-left-margin)))
535 (if do-fill-prefix (insert-and-inherit fill-prefix))))
536 (forward-line 1)
537 (setq n (1- n)))
538 (goto-char loc)
539 ;; Necessary in case a margin or prefix was inserted.
540 (end-of-line)))
542 (defun split-line (&optional arg)
543 "Split current line, moving portion beyond point vertically down.
544 If the current line starts with `fill-prefix', insert it on the new
545 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
547 When called from Lisp code, ARG may be a prefix string to copy."
548 (interactive "*P")
549 (skip-chars-forward " \t")
550 (let* ((col (current-column))
551 (pos (point))
552 ;; What prefix should we check for (nil means don't).
553 (prefix (cond ((stringp arg) arg)
554 (arg nil)
555 (t fill-prefix)))
556 ;; Does this line start with it?
557 (have-prfx (and prefix
558 (save-excursion
559 (beginning-of-line)
560 (looking-at (regexp-quote prefix))))))
561 (newline 1)
562 (if have-prfx (insert-and-inherit prefix))
563 (indent-to col 0)
564 (goto-char pos)))
566 (defun delete-indentation (&optional arg)
567 "Join this line to previous and fix up whitespace at join.
568 If there is a fill prefix, delete it from the beginning of this line.
569 With argument, join this line to following line."
570 (interactive "*P")
571 (beginning-of-line)
572 (if arg (forward-line 1))
573 (if (eq (preceding-char) ?\n)
574 (progn
575 (delete-region (point) (1- (point)))
576 ;; If the second line started with the fill prefix,
577 ;; delete the prefix.
578 (if (and fill-prefix
579 (<= (+ (point) (length fill-prefix)) (point-max))
580 (string= fill-prefix
581 (buffer-substring (point)
582 (+ (point) (length fill-prefix)))))
583 (delete-region (point) (+ (point) (length fill-prefix))))
584 (fixup-whitespace))))
586 (defalias 'join-line #'delete-indentation) ; easier to find
588 (defun delete-blank-lines ()
589 "On blank line, delete all surrounding blank lines, leaving just one.
590 On isolated blank line, delete that one.
591 On nonblank line, delete any immediately following blank lines."
592 (interactive "*")
593 (let (thisblank singleblank)
594 (save-excursion
595 (beginning-of-line)
596 (setq thisblank (looking-at "[ \t]*$"))
597 ;; Set singleblank if there is just one blank line here.
598 (setq singleblank
599 (and thisblank
600 (not (looking-at "[ \t]*\n[ \t]*$"))
601 (or (bobp)
602 (progn (forward-line -1)
603 (not (looking-at "[ \t]*$")))))))
604 ;; Delete preceding blank lines, and this one too if it's the only one.
605 (if thisblank
606 (progn
607 (beginning-of-line)
608 (if singleblank (forward-line 1))
609 (delete-region (point)
610 (if (re-search-backward "[^ \t\n]" nil t)
611 (progn (forward-line 1) (point))
612 (point-min)))))
613 ;; Delete following blank lines, unless the current line is blank
614 ;; and there are no following blank lines.
615 (if (not (and thisblank singleblank))
616 (save-excursion
617 (end-of-line)
618 (forward-line 1)
619 (delete-region (point)
620 (if (re-search-forward "[^ \t\n]" nil t)
621 (progn (beginning-of-line) (point))
622 (point-max)))))
623 ;; Handle the special case where point is followed by newline and eob.
624 ;; Delete the line, leaving point at eob.
625 (if (looking-at "^[ \t]*\n\\'")
626 (delete-region (point) (point-max)))))
628 (defcustom delete-trailing-lines t
629 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
630 Trailing lines are deleted only if `delete-trailing-whitespace'
631 is called on the entire buffer (rather than an active region)."
632 :type 'boolean
633 :group 'editing
634 :version "24.3")
636 (defun region-modifiable-p (start end)
637 "Return non-nil if the region contains no read-only text."
638 (and (not (get-text-property start 'read-only))
639 (eq end (next-single-property-change start 'read-only nil end))))
641 (defun delete-trailing-whitespace (&optional start end)
642 "Delete trailing whitespace between START and END.
643 If called interactively, START and END are the start/end of the
644 region if the mark is active, or of the buffer's accessible
645 portion if the mark is inactive.
647 This command deletes whitespace characters after the last
648 non-whitespace character in each line between START and END. It
649 does not consider formfeed characters to be whitespace.
651 If this command acts on the entire buffer (i.e. if called
652 interactively with the mark inactive, or called from Lisp with
653 END nil), it also deletes all trailing lines at the end of the
654 buffer if the variable `delete-trailing-lines' is non-nil."
655 (interactive (progn
656 (barf-if-buffer-read-only)
657 (if (use-region-p)
658 (list (region-beginning) (region-end))
659 (list nil nil))))
660 (save-match-data
661 (save-excursion
662 (let ((end-marker (and end (copy-marker end))))
663 (goto-char (or start (point-min)))
664 (with-syntax-table (make-syntax-table (syntax-table))
665 ;; Don't delete formfeeds, even if they are considered whitespace.
666 (modify-syntax-entry ?\f "_")
667 (while (re-search-forward "\\s-$" end-marker t)
668 (skip-syntax-backward "-" (line-beginning-position))
669 (let ((b (point)) (e (match-end 0)))
670 (when (region-modifiable-p b e)
671 (delete-region b e)))))
672 (if end
673 (set-marker end-marker nil)
674 ;; Delete trailing empty lines.
675 (and delete-trailing-lines
676 ;; Really the end of buffer.
677 (= (goto-char (point-max)) (1+ (buffer-size)))
678 (<= (skip-chars-backward "\n") -2)
679 (region-modifiable-p (1+ (point)) (point-max))
680 (delete-region (1+ (point)) (point-max)))))))
681 ;; Return nil for the benefit of `write-file-functions'.
682 nil)
684 (defun newline-and-indent ()
685 "Insert a newline, then indent according to major mode.
686 Indentation is done using the value of `indent-line-function'.
687 In programming language modes, this is the same as TAB.
688 In some text modes, where TAB inserts a tab, this command indents to the
689 column specified by the function `current-left-margin'."
690 (interactive "*")
691 (delete-horizontal-space t)
692 (newline nil t)
693 (indent-according-to-mode))
695 (defun reindent-then-newline-and-indent ()
696 "Reindent current line, insert newline, then indent the new line.
697 Indentation of both lines is done according to the current major mode,
698 which means calling the current value of `indent-line-function'.
699 In programming language modes, this is the same as TAB.
700 In some text modes, where TAB inserts a tab, this indents to the
701 column specified by the function `current-left-margin'."
702 (interactive "*")
703 (let ((pos (point)))
704 ;; Be careful to insert the newline before indenting the line.
705 ;; Otherwise, the indentation might be wrong.
706 (newline)
707 (save-excursion
708 (goto-char pos)
709 ;; We are at EOL before the call to indent-according-to-mode, and
710 ;; after it we usually are as well, but not always. We tried to
711 ;; address it with `save-excursion' but that uses a normal marker
712 ;; whereas we need `move after insertion', so we do the save/restore
713 ;; by hand.
714 (setq pos (copy-marker pos t))
715 (indent-according-to-mode)
716 (goto-char pos)
717 ;; Remove the trailing white-space after indentation because
718 ;; indentation may introduce the whitespace.
719 (delete-horizontal-space t))
720 (indent-according-to-mode)))
722 (defcustom read-quoted-char-radix 8
723 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
724 Legitimate radix values are 8, 10 and 16."
725 :type '(choice (const 8) (const 10) (const 16))
726 :group 'editing-basics)
728 (defun read-quoted-char (&optional prompt)
729 "Like `read-char', but do not allow quitting.
730 Also, if the first character read is an octal digit,
731 we read any number of octal digits and return the
732 specified character code. Any nondigit terminates the sequence.
733 If the terminator is RET, it is discarded;
734 any other terminator is used itself as input.
736 The optional argument PROMPT specifies a string to use to prompt the user.
737 The variable `read-quoted-char-radix' controls which radix to use
738 for numeric input."
739 (let ((message-log-max nil)
740 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
741 help-event-list)))
742 done (first t) (code 0) char translated)
743 (while (not done)
744 (let ((inhibit-quit first)
745 ;; Don't let C-h or other help chars get the help
746 ;; message--only help function keys. See bug#16617.
747 (help-char nil)
748 (help-event-list help-events)
749 (help-form
750 "Type the special character you want to use,
751 or the octal character code.
752 RET terminates the character code and is discarded;
753 any other non-digit terminates the character code and is then used as input."))
754 (setq char (read-event (and prompt (format "%s-" prompt)) t))
755 (if inhibit-quit (setq quit-flag nil)))
756 ;; Translate TAB key into control-I ASCII character, and so on.
757 ;; Note: `read-char' does it using the `ascii-character' property.
758 ;; We tried using read-key instead, but that disables the keystroke
759 ;; echo produced by 'C-q', see bug#24635.
760 (let ((translation (lookup-key local-function-key-map (vector char))))
761 (setq translated (if (arrayp translation)
762 (aref translation 0)
763 char)))
764 (if (integerp translated)
765 (setq translated (char-resolve-modifiers translated)))
766 (cond ((null translated))
767 ((not (integerp translated))
768 (setq unread-command-events (list char)
769 done t))
770 ((/= (logand translated ?\M-\^@) 0)
771 ;; Turn a meta-character into a character with the 0200 bit set.
772 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
773 done t))
774 ((and (<= ?0 translated)
775 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
776 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
777 (and prompt (setq prompt (message "%s %c" prompt translated))))
778 ((and (<= ?a (downcase translated))
779 (< (downcase translated)
780 (+ ?a -10 (min 36 read-quoted-char-radix))))
781 (setq code (+ (* code read-quoted-char-radix)
782 (+ 10 (- (downcase translated) ?a))))
783 (and prompt (setq prompt (message "%s %c" prompt translated))))
784 ((and (not first) (eq translated ?\C-m))
785 (setq done t))
786 ((not first)
787 (setq unread-command-events (list char)
788 done t))
789 (t (setq code translated
790 done t)))
791 (setq first nil))
792 code))
794 (defun quoted-insert (arg)
795 "Read next input character and insert it.
796 This is useful for inserting control characters.
797 With argument, insert ARG copies of the character.
799 If the first character you type after this command is an octal digit,
800 you should type a sequence of octal digits which specify a character code.
801 Any nondigit terminates the sequence. If the terminator is a RET,
802 it is discarded; any other terminator is used itself as input.
803 The variable `read-quoted-char-radix' specifies the radix for this feature;
804 set it to 10 or 16 to use decimal or hex instead of octal.
806 In overwrite mode, this function inserts the character anyway, and
807 does not handle octal digits specially. This means that if you use
808 overwrite as your normal editing mode, you can use this function to
809 insert characters when necessary.
811 In binary overwrite mode, this function does overwrite, and octal
812 digits are interpreted as a character code. This is intended to be
813 useful for editing binary files."
814 (interactive "*p")
815 (let* ((char
816 ;; Avoid "obsolete" warnings for translation-table-for-input.
817 (with-no-warnings
818 (let (translation-table-for-input input-method-function)
819 (if (or (not overwrite-mode)
820 (eq overwrite-mode 'overwrite-mode-binary))
821 (read-quoted-char)
822 (read-char))))))
823 ;; This used to assume character codes 0240 - 0377 stand for
824 ;; characters in some single-byte character set, and converted them
825 ;; to Emacs characters. But in 23.1 this feature is deprecated
826 ;; in favor of inserting the corresponding Unicode characters.
827 ;; (if (and enable-multibyte-characters
828 ;; (>= char ?\240)
829 ;; (<= char ?\377))
830 ;; (setq char (unibyte-char-to-multibyte char)))
831 (unless (characterp char)
832 (user-error "%s is not a valid character"
833 (key-description (vector char))))
834 (if (> arg 0)
835 (if (eq overwrite-mode 'overwrite-mode-binary)
836 (delete-char arg)))
837 (while (> arg 0)
838 (insert-and-inherit char)
839 (setq arg (1- arg)))))
841 (defun forward-to-indentation (&optional arg)
842 "Move forward ARG lines and position at first nonblank character."
843 (interactive "^p")
844 (forward-line (or arg 1))
845 (skip-chars-forward " \t"))
847 (defun backward-to-indentation (&optional arg)
848 "Move backward ARG lines and position at first nonblank character."
849 (interactive "^p")
850 (forward-line (- (or arg 1)))
851 (skip-chars-forward " \t"))
853 (defun back-to-indentation ()
854 "Move point to the first non-whitespace character on this line."
855 (interactive "^")
856 (beginning-of-line 1)
857 (skip-syntax-forward " " (line-end-position))
858 ;; Move back over chars that have whitespace syntax but have the p flag.
859 (backward-prefix-chars))
861 (defun fixup-whitespace ()
862 "Fixup white space between objects around point.
863 Leave one space or none, according to the context."
864 (interactive "*")
865 (save-excursion
866 (delete-horizontal-space)
867 (if (or (looking-at "^\\|$\\|\\s)")
868 (save-excursion (forward-char -1)
869 (looking-at "$\\|\\s(\\|\\s'")))
871 (insert ?\s))))
873 (defun delete-horizontal-space (&optional backward-only)
874 "Delete all spaces and tabs around point.
875 If BACKWARD-ONLY is non-nil, only delete them before point."
876 (interactive "*P")
877 (let ((orig-pos (point)))
878 (delete-region
879 (if backward-only
880 orig-pos
881 (progn
882 (skip-chars-forward " \t")
883 (constrain-to-field nil orig-pos t)))
884 (progn
885 (skip-chars-backward " \t")
886 (constrain-to-field nil orig-pos)))))
888 (defun just-one-space (&optional n)
889 "Delete all spaces and tabs around point, leaving one space (or N spaces).
890 If N is negative, delete newlines as well, leaving -N spaces.
891 See also `cycle-spacing'."
892 (interactive "*p")
893 (cycle-spacing n nil 'single-shot))
895 (defvar cycle-spacing--context nil
896 "Store context used in consecutive calls to `cycle-spacing' command.
897 The first time `cycle-spacing' runs, it saves in this variable:
898 its N argument, the original point position, and the original spacing
899 around point.")
901 (defun cycle-spacing (&optional n preserve-nl-back mode)
902 "Manipulate whitespace around point in a smart way.
903 In interactive use, this function behaves differently in successive
904 consecutive calls.
906 The first call in a sequence acts like `just-one-space'.
907 It deletes all spaces and tabs around point, leaving one space
908 \(or N spaces). N is the prefix argument. If N is negative,
909 it deletes newlines as well, leaving -N spaces.
910 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
912 The second call in a sequence deletes all spaces.
914 The third call in a sequence restores the original whitespace (and point).
916 If MODE is `single-shot', it only performs the first step in the sequence.
917 If MODE is `fast' and the first step would not result in any change
918 \(i.e., there are exactly (abs N) spaces around point),
919 the function goes straight to the second step.
921 Repeatedly calling the function with different values of N starts a
922 new sequence each time."
923 (interactive "*p")
924 (let ((orig-pos (point))
925 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
926 (num (abs (or n 1))))
927 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
928 (constrain-to-field nil orig-pos)
929 (cond
930 ;; Command run for the first time, single-shot mode or different argument
931 ((or (eq 'single-shot mode)
932 (not (equal last-command this-command))
933 (not cycle-spacing--context)
934 (not (eq (car cycle-spacing--context) n)))
935 (let* ((start (point))
936 (num (- num (skip-chars-forward " " (+ num (point)))))
937 (mid (point))
938 (end (progn
939 (skip-chars-forward skip-characters)
940 (constrain-to-field nil orig-pos t))))
941 (setq cycle-spacing--context ;; Save for later.
942 ;; Special handling for case where there was no space at all.
943 (unless (= start end)
944 (cons n (cons orig-pos (buffer-substring start (point))))))
945 ;; If this run causes no change in buffer content, delete all spaces,
946 ;; otherwise delete all excess spaces.
947 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
948 start mid) end)
949 (insert (make-string num ?\s))))
951 ;; Command run for the second time.
952 ((not (equal orig-pos (point)))
953 (delete-region (point) orig-pos))
955 ;; Command run for the third time.
957 (insert (cddr cycle-spacing--context))
958 (goto-char (cadr cycle-spacing--context))
959 (setq cycle-spacing--context nil)))))
961 (defun beginning-of-buffer (&optional arg)
962 "Move point to the beginning of the buffer.
963 With numeric arg N, put point N/10 of the way from the beginning.
964 If the buffer is narrowed, this command uses the beginning of the
965 accessible part of the buffer.
967 Push mark at previous position, unless either a \\[universal-argument] prefix
968 is supplied, or Transient Mark mode is enabled and the mark is active."
969 (declare (interactive-only "use `(goto-char (point-min))' instead."))
970 (interactive "^P")
971 (or (consp arg)
972 (region-active-p)
973 (push-mark))
974 (let ((size (- (point-max) (point-min))))
975 (goto-char (if (and arg (not (consp arg)))
976 (+ (point-min)
977 (if (> size 10000)
978 ;; Avoid overflow for large buffer sizes!
979 (* (prefix-numeric-value arg)
980 (/ size 10))
981 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
982 (point-min))))
983 (if (and arg (not (consp arg))) (forward-line 1)))
985 (defun end-of-buffer (&optional arg)
986 "Move point to the end of the buffer.
987 With numeric arg N, put point N/10 of the way from the end.
988 If the buffer is narrowed, this command uses the end of the
989 accessible part of the buffer.
991 Push mark at previous position, unless either a \\[universal-argument] prefix
992 is supplied, or Transient Mark mode is enabled and the mark is active."
993 (declare (interactive-only "use `(goto-char (point-max))' instead."))
994 (interactive "^P")
995 (or (consp arg) (region-active-p) (push-mark))
996 (let ((size (- (point-max) (point-min))))
997 (goto-char (if (and arg (not (consp arg)))
998 (- (point-max)
999 (if (> size 10000)
1000 ;; Avoid overflow for large buffer sizes!
1001 (* (prefix-numeric-value arg)
1002 (/ size 10))
1003 (/ (* size (prefix-numeric-value arg)) 10)))
1004 (point-max))))
1005 ;; If we went to a place in the middle of the buffer,
1006 ;; adjust it to the beginning of a line.
1007 (cond ((and arg (not (consp arg))) (forward-line 1))
1008 ((and (eq (current-buffer) (window-buffer))
1009 (> (point) (window-end nil t)))
1010 ;; If the end of the buffer is not already on the screen,
1011 ;; then scroll specially to put it near, but not at, the bottom.
1012 (overlay-recenter (point))
1013 (recenter -3))))
1015 (defcustom delete-active-region t
1016 "Whether single-char deletion commands delete an active region.
1017 This has an effect only if Transient Mark mode is enabled, and
1018 affects `delete-forward-char' and `delete-backward-char', though
1019 not `delete-char'.
1021 If the value is the symbol `kill', the active region is killed
1022 instead of deleted."
1023 :type '(choice (const :tag "Delete active region" t)
1024 (const :tag "Kill active region" kill)
1025 (const :tag "Do ordinary deletion" nil))
1026 :group 'killing
1027 :version "24.1")
1029 (defvar region-extract-function
1030 (lambda (method)
1031 (when (region-beginning)
1032 (cond
1033 ((eq method 'bounds)
1034 (list (cons (region-beginning) (region-end))))
1035 ((eq method 'delete-only)
1036 (delete-region (region-beginning) (region-end)))
1038 (filter-buffer-substring (region-beginning) (region-end) method)))))
1039 "Function to get the region's content.
1040 Called with one argument METHOD.
1041 If METHOD is `delete-only', then delete the region; the return value
1042 is undefined. If METHOD is nil, then return the content as a string.
1043 If METHOD is `bounds', then return the boundaries of the region
1044 as a list of cons cells of the form (START . END).
1045 If METHOD is anything else, delete the region and return its content
1046 as a string, after filtering it with `filter-buffer-substring', which
1047 is called with METHOD as its 3rd argument.")
1049 (defvar region-insert-function
1050 (lambda (lines)
1051 (let ((first t))
1052 (while lines
1053 (or first
1054 (insert ?\n))
1055 (insert-for-yank (car lines))
1056 (setq lines (cdr lines)
1057 first nil))))
1058 "Function to insert the region's content.
1059 Called with one argument LINES.
1060 Insert the region as a list of lines.")
1062 (defun delete-backward-char (n &optional killflag)
1063 "Delete the previous N characters (following if N is negative).
1064 If Transient Mark mode is enabled, the mark is active, and N is 1,
1065 delete the text in the region and deactivate the mark instead.
1066 To disable this, set option `delete-active-region' to nil.
1068 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1069 kill ring) instead of delete. Interactively, N is the prefix
1070 arg, and KILLFLAG is set if N is explicitly specified.
1072 When killing, the killed text is filtered by
1073 `filter-buffer-substring' before it is saved in the kill ring, so
1074 the actual saved text might be different from what was killed.
1076 In Overwrite mode, single character backward deletion may replace
1077 tabs with spaces so as to back over columns, unless point is at
1078 the end of the line."
1079 (declare (interactive-only delete-char))
1080 (interactive "p\nP")
1081 (unless (integerp n)
1082 (signal 'wrong-type-argument (list 'integerp n)))
1083 (cond ((and (use-region-p)
1084 delete-active-region
1085 (= n 1))
1086 ;; If a region is active, kill or delete it.
1087 (if (eq delete-active-region 'kill)
1088 (kill-region (region-beginning) (region-end) 'region)
1089 (funcall region-extract-function 'delete-only)))
1090 ;; In Overwrite mode, maybe untabify while deleting
1091 ((null (or (null overwrite-mode)
1092 (<= n 0)
1093 (memq (char-before) '(?\t ?\n))
1094 (eobp)
1095 (eq (char-after) ?\n)))
1096 (let ((ocol (current-column)))
1097 (delete-char (- n) killflag)
1098 (save-excursion
1099 (insert-char ?\s (- ocol (current-column)) nil))))
1100 ;; Otherwise, do simple deletion.
1101 (t (delete-char (- n) killflag))))
1103 (defun delete-forward-char (n &optional killflag)
1104 "Delete the following N characters (previous if N is negative).
1105 If Transient Mark mode is enabled, the mark is active, and N is 1,
1106 delete the text in the region and deactivate the mark instead.
1107 To disable this, set variable `delete-active-region' to nil.
1109 Optional second arg KILLFLAG non-nil means to kill (save in kill
1110 ring) instead of delete. Interactively, N is the prefix arg, and
1111 KILLFLAG is set if N was explicitly specified.
1113 When killing, the killed text is filtered by
1114 `filter-buffer-substring' before it is saved in the kill ring, so
1115 the actual saved text might be different from what was killed."
1116 (declare (interactive-only delete-char))
1117 (interactive "p\nP")
1118 (unless (integerp n)
1119 (signal 'wrong-type-argument (list 'integerp n)))
1120 (cond ((and (use-region-p)
1121 delete-active-region
1122 (= n 1))
1123 ;; If a region is active, kill or delete it.
1124 (if (eq delete-active-region 'kill)
1125 (kill-region (region-beginning) (region-end) 'region)
1126 (funcall region-extract-function 'delete-only)))
1128 ;; Otherwise, do simple deletion.
1129 (t (delete-char n killflag))))
1131 (defun mark-whole-buffer ()
1132 "Put point at beginning and mark at end of buffer.
1133 Also push mark at point before pushing mark at end of buffer.
1134 If narrowing is in effect, only uses the accessible part of the buffer.
1135 You probably should not use this function in Lisp programs;
1136 it is usually a mistake for a Lisp function to use any subroutine
1137 that uses or sets the mark."
1138 (declare (interactive-only t))
1139 (interactive)
1140 (push-mark)
1141 (push-mark (point-max) nil t)
1142 ;; This is really `point-min' in most cases, but if we're in the
1143 ;; minibuffer, this is at the end of the prompt.
1144 (goto-char (minibuffer-prompt-end)))
1147 ;; Counting lines, one way or another.
1149 (defun goto-line (line &optional buffer)
1150 "Go to LINE, counting from line 1 at beginning of buffer.
1151 If called interactively, a numeric prefix argument specifies
1152 LINE; without a numeric prefix argument, read LINE from the
1153 minibuffer.
1155 If optional argument BUFFER is non-nil, switch to that buffer and
1156 move to line LINE there. If called interactively with \\[universal-argument]
1157 as argument, BUFFER is the most recently selected other buffer.
1159 Prior to moving point, this function sets the mark (without
1160 activating it), unless Transient Mark mode is enabled and the
1161 mark is already active.
1163 This function is usually the wrong thing to use in a Lisp program.
1164 What you probably want instead is something like:
1165 (goto-char (point-min))
1166 (forward-line (1- N))
1167 If at all possible, an even better solution is to use char counts
1168 rather than line counts."
1169 (declare (interactive-only forward-line))
1170 (interactive
1171 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1172 (list (prefix-numeric-value current-prefix-arg))
1173 ;; Look for a default, a number in the buffer at point.
1174 (let* ((default
1175 (save-excursion
1176 (skip-chars-backward "0-9")
1177 (if (looking-at "[0-9]")
1178 (string-to-number
1179 (buffer-substring-no-properties
1180 (point)
1181 (progn (skip-chars-forward "0-9")
1182 (point)))))))
1183 ;; Decide if we're switching buffers.
1184 (buffer
1185 (if (consp current-prefix-arg)
1186 (other-buffer (current-buffer) t)))
1187 (buffer-prompt
1188 (if buffer
1189 (concat " in " (buffer-name buffer))
1190 "")))
1191 ;; Read the argument, offering that number (if any) as default.
1192 (list (read-number (format "Goto line%s: " buffer-prompt)
1193 (list default (line-number-at-pos)))
1194 buffer))))
1195 ;; Switch to the desired buffer, one way or another.
1196 (if buffer
1197 (let ((window (get-buffer-window buffer)))
1198 (if window (select-window window)
1199 (switch-to-buffer-other-window buffer))))
1200 ;; Leave mark at previous position
1201 (or (region-active-p) (push-mark))
1202 ;; Move to the specified line number in that buffer.
1203 (save-restriction
1204 (widen)
1205 (goto-char (point-min))
1206 (if (eq selective-display t)
1207 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1208 (forward-line (1- line)))))
1210 (defun count-words-region (start end &optional arg)
1211 "Count the number of words in the region.
1212 If called interactively, print a message reporting the number of
1213 lines, words, and characters in the region (whether or not the
1214 region is active); with prefix ARG, report for the entire buffer
1215 rather than the region.
1217 If called from Lisp, return the number of words between positions
1218 START and END."
1219 (interactive (if current-prefix-arg
1220 (list nil nil current-prefix-arg)
1221 (list (region-beginning) (region-end) nil)))
1222 (cond ((not (called-interactively-p 'any))
1223 (count-words start end))
1224 (arg
1225 (count-words--buffer-message))
1227 (count-words--message "Region" start end))))
1229 (defun count-words (start end)
1230 "Count words between START and END.
1231 If called interactively, START and END are normally the start and
1232 end of the buffer; but if the region is active, START and END are
1233 the start and end of the region. Print a message reporting the
1234 number of lines, words, and chars.
1236 If called from Lisp, return the number of words between START and
1237 END, without printing any message."
1238 (interactive (list nil nil))
1239 (cond ((not (called-interactively-p 'any))
1240 (let ((words 0))
1241 (save-excursion
1242 (save-restriction
1243 (narrow-to-region start end)
1244 (goto-char (point-min))
1245 (while (forward-word-strictly 1)
1246 (setq words (1+ words)))))
1247 words))
1248 ((use-region-p)
1249 (call-interactively 'count-words-region))
1251 (count-words--buffer-message))))
1253 (defun count-words--buffer-message ()
1254 (count-words--message
1255 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1256 (point-min) (point-max)))
1258 (defun count-words--message (str start end)
1259 (let ((lines (count-lines start end))
1260 (words (count-words start end))
1261 (chars (- end start)))
1262 (message "%s has %d line%s, %d word%s, and %d character%s."
1264 lines (if (= lines 1) "" "s")
1265 words (if (= words 1) "" "s")
1266 chars (if (= chars 1) "" "s"))))
1268 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1270 (defun what-line ()
1271 "Print the current buffer line number and narrowed line number of point."
1272 (interactive)
1273 (let ((start (point-min))
1274 (n (line-number-at-pos)))
1275 (if (= start 1)
1276 (message "Line %d" n)
1277 (save-excursion
1278 (save-restriction
1279 (widen)
1280 (message "line %d (narrowed line %d)"
1281 (+ n (line-number-at-pos start) -1) n))))))
1283 (defun count-lines (start end)
1284 "Return number of lines between START and END.
1285 This is usually the number of newlines between them,
1286 but can be one more if START is not equal to END
1287 and the greater of them is not at the start of a line."
1288 (save-excursion
1289 (save-restriction
1290 (narrow-to-region start end)
1291 (goto-char (point-min))
1292 (if (eq selective-display t)
1293 (save-match-data
1294 (let ((done 0))
1295 (while (re-search-forward "[\n\C-m]" nil t 40)
1296 (setq done (+ 40 done)))
1297 (while (re-search-forward "[\n\C-m]" nil t 1)
1298 (setq done (+ 1 done)))
1299 (goto-char (point-max))
1300 (if (and (/= start end)
1301 (not (bolp)))
1302 (1+ done)
1303 done)))
1304 (- (buffer-size) (forward-line (buffer-size)))))))
1306 (defun line-number-at-pos (&optional pos absolute)
1307 "Return buffer line number at position POS.
1308 If POS is nil, use current buffer location.
1310 If ABSOLUTE is nil, the default, counting starts
1311 at (point-min), so the value refers to the contents of the
1312 accessible portion of the (potentially narrowed) buffer. If
1313 ABSOLUTE is non-nil, ignore any narrowing and return the
1314 absolute line number."
1315 (save-restriction
1316 (when absolute
1317 (widen))
1318 (let ((opoint (or pos (point))) start)
1319 (save-excursion
1320 (goto-char (point-min))
1321 (setq start (point))
1322 (goto-char opoint)
1323 (forward-line 0)
1324 (1+ (count-lines start (point)))))))
1326 (defun what-cursor-position (&optional detail)
1327 "Print info on cursor position (on screen and within buffer).
1328 Also describe the character after point, and give its character code
1329 in octal, decimal and hex.
1331 For a non-ASCII multibyte character, also give its encoding in the
1332 buffer's selected coding system if the coding system encodes the
1333 character safely. If the character is encoded into one byte, that
1334 code is shown in hex. If the character is encoded into more than one
1335 byte, just \"...\" is shown.
1337 In addition, with prefix argument, show details about that character
1338 in *Help* buffer. See also the command `describe-char'."
1339 (interactive "P")
1340 (let* ((char (following-char))
1341 (bidi-fixer
1342 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1343 ;; start a directional embedding, which could completely
1344 ;; disrupt the rest of the line (e.g., RLO will display the
1345 ;; rest of the line right-to-left). So we put an invisible
1346 ;; PDF character after these characters, to end the
1347 ;; embedding, which eliminates any effects on the rest of
1348 ;; the line. For RLE and RLO we also append an invisible
1349 ;; LRM, to avoid reordering the following numerical
1350 ;; characters. For LRI/RLI/FSI we append a PDI.
1351 (cond ((memq char '(?\x202a ?\x202d))
1352 (propertize (string ?\x202c) 'invisible t))
1353 ((memq char '(?\x202b ?\x202e))
1354 (propertize (string ?\x202c ?\x200e) 'invisible t))
1355 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1356 (propertize (string ?\x2069) 'invisible t))
1357 ;; Strong right-to-left characters cause reordering of
1358 ;; the following numerical characters which show the
1359 ;; codepoint, so append LRM to countermand that.
1360 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1361 (propertize (string ?\x200e) 'invisible t))
1363 "")))
1364 (beg (point-min))
1365 (end (point-max))
1366 (pos (point))
1367 (total (buffer-size))
1368 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1369 (hscroll (if (= (window-hscroll) 0)
1371 (format " Hscroll=%d" (window-hscroll))))
1372 (col (current-column)))
1373 (if (= pos end)
1374 (if (or (/= beg 1) (/= end (1+ total)))
1375 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1376 pos total percent beg end col hscroll)
1377 (message "point=%d of %d (EOB) column=%d%s"
1378 pos total col hscroll))
1379 (let ((coding buffer-file-coding-system)
1380 encoded encoding-msg display-prop under-display)
1381 (if (or (not coding)
1382 (eq (coding-system-type coding) t))
1383 (setq coding (default-value 'buffer-file-coding-system)))
1384 (if (eq (char-charset char) 'eight-bit)
1385 (setq encoding-msg
1386 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1387 ;; Check if the character is displayed with some `display'
1388 ;; text property. In that case, set under-display to the
1389 ;; buffer substring covered by that property.
1390 (setq display-prop (get-char-property pos 'display))
1391 (if display-prop
1392 (let ((to (or (next-single-char-property-change pos 'display)
1393 (point-max))))
1394 (if (< to (+ pos 4))
1395 (setq under-display "")
1396 (setq under-display "..."
1397 to (+ pos 4)))
1398 (setq under-display
1399 (concat (buffer-substring-no-properties pos to)
1400 under-display)))
1401 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1402 (setq encoding-msg
1403 (if display-prop
1404 (if (not (stringp display-prop))
1405 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1406 char char char under-display)
1407 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1408 char char char under-display display-prop))
1409 (if encoded
1410 (format "(%d, #o%o, #x%x, file %s)"
1411 char char char
1412 (if (> (length encoded) 1)
1413 "..."
1414 (encoded-string-description encoded coding)))
1415 (format "(%d, #o%o, #x%x)" char char char)))))
1416 (if detail
1417 ;; We show the detailed information about CHAR.
1418 (describe-char (point)))
1419 (if (or (/= beg 1) (/= end (1+ total)))
1420 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1421 (if (< char 256)
1422 (single-key-description char)
1423 (buffer-substring-no-properties (point) (1+ (point))))
1424 bidi-fixer
1425 encoding-msg pos total percent beg end col hscroll)
1426 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1427 (if enable-multibyte-characters
1428 (if (< char 128)
1429 (single-key-description char)
1430 (buffer-substring-no-properties (point) (1+ (point))))
1431 (single-key-description char))
1432 bidi-fixer encoding-msg pos total percent col hscroll))))))
1434 ;; Initialize read-expression-map. It is defined at C level.
1435 (defvar read-expression-map
1436 (let ((m (make-sparse-keymap)))
1437 (define-key m "\M-\t" 'completion-at-point)
1438 ;; Might as well bind TAB to completion, since inserting a TAB char is
1439 ;; much too rarely useful.
1440 (define-key m "\t" 'completion-at-point)
1441 (set-keymap-parent m minibuffer-local-map)
1444 (defun read-minibuffer (prompt &optional initial-contents)
1445 "Return a Lisp object read using the minibuffer, unevaluated.
1446 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1447 is a string to insert in the minibuffer before reading.
1448 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1449 Such arguments are used as in `read-from-minibuffer'.)"
1450 ;; Used for interactive spec `x'.
1451 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1452 t 'minibuffer-history))
1454 (defun eval-minibuffer (prompt &optional initial-contents)
1455 "Return value of Lisp expression read using the minibuffer.
1456 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1457 is a string to insert in the minibuffer before reading.
1458 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1459 Such arguments are used as in `read-from-minibuffer'.)"
1460 ;; Used for interactive spec `X'.
1461 (eval (read--expression prompt initial-contents)))
1463 (defvar minibuffer-completing-symbol nil
1464 "Non-nil means completing a Lisp symbol in the minibuffer.")
1465 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1467 (defvar minibuffer-default nil
1468 "The current default value or list of default values in the minibuffer.
1469 The functions `read-from-minibuffer' and `completing-read' bind
1470 this variable locally.")
1472 (defcustom eval-expression-print-level 4
1473 "Value for `print-level' while printing value in `eval-expression'.
1474 A value of nil means no limit."
1475 :group 'lisp
1476 :type '(choice (const :tag "No Limit" nil) integer)
1477 :version "21.1")
1479 (defcustom eval-expression-print-length 12
1480 "Value for `print-length' while printing value in `eval-expression'.
1481 A value of nil means no limit."
1482 :group 'lisp
1483 :type '(choice (const :tag "No Limit" nil) integer)
1484 :version "21.1")
1486 (defcustom eval-expression-debug-on-error t
1487 "If non-nil set `debug-on-error' to t in `eval-expression'.
1488 If nil, don't change the value of `debug-on-error'."
1489 :group 'lisp
1490 :type 'boolean
1491 :version "21.1")
1493 (defcustom eval-expression-print-maximum-character 127
1494 "The largest integer that will be displayed as a character.
1495 This affects printing by `eval-expression' (via
1496 `eval-expression-print-format')."
1497 :group 'lisp
1498 :type 'integer
1499 :version "26.1")
1501 (defun eval-expression-print-format (value)
1502 "If VALUE in an integer, return a specially formatted string.
1503 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1504 If VALUE is not an integer, nil is returned.
1505 This function is used by commands like `eval-expression' that
1506 display the result of expression evaluation."
1507 (when (integerp value)
1508 (let ((char-string
1509 (and (characterp value)
1510 (<= value eval-expression-print-maximum-character)
1511 (char-displayable-p value)
1512 (prin1-char value))))
1513 (if char-string
1514 (format " (#o%o, #x%x, %s)" value value char-string)
1515 (format " (#o%o, #x%x)" value value)))))
1517 (defvar eval-expression-minibuffer-setup-hook nil
1518 "Hook run by `eval-expression' when entering the minibuffer.")
1520 (defun read--expression (prompt &optional initial-contents)
1521 (let ((minibuffer-completing-symbol t))
1522 (minibuffer-with-setup-hook
1523 (lambda ()
1524 ;; FIXME: call emacs-lisp-mode?
1525 (add-function :before-until (local 'eldoc-documentation-function)
1526 #'elisp-eldoc-documentation-function)
1527 (eldoc-mode 1)
1528 (add-hook 'completion-at-point-functions
1529 #'elisp-completion-at-point nil t)
1530 (run-hooks 'eval-expression-minibuffer-setup-hook))
1531 (read-from-minibuffer prompt initial-contents
1532 read-expression-map t
1533 'read-expression-history))))
1535 (defun eval-expression-get-print-arguments (prefix-argument)
1536 "Get arguments for commands that print an expression result.
1537 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1538 based on PREFIX-ARG. This function determines the interpretation
1539 of the prefix argument for `eval-expression' and
1540 `eval-last-sexp'."
1541 (let ((num (prefix-numeric-value prefix-argument)))
1542 (list (not (memq prefix-argument '(- nil)))
1543 (= num 0)
1544 (cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
1545 ((= num -1) most-positive-fixnum)
1546 (t eval-expression-print-maximum-character)))))
1548 ;; We define this, rather than making `eval' interactive,
1549 ;; for the sake of completion of names like eval-region, eval-buffer.
1550 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
1551 "Evaluate EXP and print value in the echo area.
1552 When called interactively, read an Emacs Lisp expression and
1553 evaluate it. Value is also consed on to front of the variable
1554 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1555 with a non `-' prefix argument) means insert the result into the
1556 current buffer instead of printing it in the echo area.
1558 Normally, this function truncates long output according to the
1559 value of the variables `eval-expression-print-length' and
1560 `eval-expression-print-level'. When NO-TRUNCATE is
1561 non-nil (interactively, with a prefix argument of zero), however,
1562 there is no such truncation.
1564 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1565 non-nil (interactively, unless given a positive prefix argument)
1566 it will be printed in several additional formats (octal,
1567 hexadecimal, and character). The character format is only used
1568 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1569 prefix argument is -1 or the value is below
1570 `eval-expression-print-maximum-character').
1572 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1573 minibuffer.
1575 If `eval-expression-debug-on-error' is non-nil, which is the default,
1576 this command arranges for all errors to enter the debugger."
1577 (interactive
1578 (cons (read--expression "Eval: ")
1579 (eval-expression-get-print-arguments current-prefix-arg)))
1581 (if (null eval-expression-debug-on-error)
1582 (push (eval exp lexical-binding) values)
1583 (let ((old-value (make-symbol "t")) new-value)
1584 ;; Bind debug-on-error to something unique so that we can
1585 ;; detect when evalled code changes it.
1586 (let ((debug-on-error old-value))
1587 (push (eval (macroexpand-all exp) lexical-binding) values)
1588 (setq new-value debug-on-error))
1589 ;; If evalled code has changed the value of debug-on-error,
1590 ;; propagate that change to the global binding.
1591 (unless (eq old-value new-value)
1592 (setq debug-on-error new-value))))
1594 (let ((print-length (unless no-truncate eval-expression-print-length))
1595 (print-level (unless no-truncate eval-expression-print-level))
1596 (eval-expression-print-maximum-character char-print-limit)
1597 (deactivate-mark))
1598 (let ((out (if insert-value (current-buffer) t)))
1599 (prog1
1600 (prin1 (car values) out)
1601 (let ((str (and char-print-limit
1602 (eval-expression-print-format (car values)))))
1603 (when str (princ str out)))))))
1605 (defun edit-and-eval-command (prompt command)
1606 "Prompting with PROMPT, let user edit COMMAND and eval result.
1607 COMMAND is a Lisp expression. Let user edit that expression in
1608 the minibuffer, then read and evaluate the result."
1609 (let ((command
1610 (let ((print-level nil)
1611 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1612 (unwind-protect
1613 (read-from-minibuffer prompt
1614 (prin1-to-string command)
1615 read-expression-map t
1616 'command-history)
1617 ;; If command was added to command-history as a string,
1618 ;; get rid of that. We want only evaluable expressions there.
1619 (if (stringp (car command-history))
1620 (setq command-history (cdr command-history)))))))
1622 ;; If command to be redone does not match front of history,
1623 ;; add it to the history.
1624 (or (equal command (car command-history))
1625 (setq command-history (cons command command-history)))
1626 (eval command)))
1628 (defun repeat-complex-command (arg)
1629 "Edit and re-evaluate last complex command, or ARGth from last.
1630 A complex command is one which used the minibuffer.
1631 The command is placed in the minibuffer as a Lisp form for editing.
1632 The result is executed, repeating the command as changed.
1633 If the command has been changed or is not the most recent previous
1634 command it is added to the front of the command history.
1635 You can use the minibuffer history commands \
1636 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1637 to get different commands to edit and resubmit."
1638 (interactive "p")
1639 (let ((elt (nth (1- arg) command-history))
1640 newcmd)
1641 (if elt
1642 (progn
1643 (setq newcmd
1644 (let ((print-level nil)
1645 (minibuffer-history-position arg)
1646 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1647 (unwind-protect
1648 (read-from-minibuffer
1649 "Redo: " (prin1-to-string elt) read-expression-map t
1650 (cons 'command-history arg))
1652 ;; If command was added to command-history as a
1653 ;; string, get rid of that. We want only
1654 ;; evaluable expressions there.
1655 (if (stringp (car command-history))
1656 (setq command-history (cdr command-history))))))
1658 ;; If command to be redone does not match front of history,
1659 ;; add it to the history.
1660 (or (equal newcmd (car command-history))
1661 (setq command-history (cons newcmd command-history)))
1662 (apply #'funcall-interactively
1663 (car newcmd)
1664 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1665 (if command-history
1666 (error "Argument %d is beyond length of command history" arg)
1667 (error "There are no previous complex commands to repeat")))))
1670 (defvar extended-command-history nil)
1671 (defvar execute-extended-command--last-typed nil)
1673 (defun read-extended-command ()
1674 "Read command name to invoke in `execute-extended-command'."
1675 (minibuffer-with-setup-hook
1676 (lambda ()
1677 (add-hook 'post-self-insert-hook
1678 (lambda ()
1679 (setq execute-extended-command--last-typed
1680 (minibuffer-contents)))
1681 nil 'local)
1682 (set (make-local-variable 'minibuffer-default-add-function)
1683 (lambda ()
1684 ;; Get a command name at point in the original buffer
1685 ;; to propose it after M-n.
1686 (with-current-buffer (window-buffer (minibuffer-selected-window))
1687 (and (commandp (function-called-at-point))
1688 (format "%S" (function-called-at-point)))))))
1689 ;; Read a string, completing from and restricting to the set of
1690 ;; all defined commands. Don't provide any initial input.
1691 ;; Save the command read on the extended-command history list.
1692 (completing-read
1693 (concat (cond
1694 ((eq current-prefix-arg '-) "- ")
1695 ((and (consp current-prefix-arg)
1696 (eq (car current-prefix-arg) 4)) "C-u ")
1697 ((and (consp current-prefix-arg)
1698 (integerp (car current-prefix-arg)))
1699 (format "%d " (car current-prefix-arg)))
1700 ((integerp current-prefix-arg)
1701 (format "%d " current-prefix-arg)))
1702 ;; This isn't strictly correct if `execute-extended-command'
1703 ;; is bound to anything else (e.g. [menu]).
1704 ;; It could use (key-description (this-single-command-keys)),
1705 ;; but actually a prompt other than "M-x" would be confusing,
1706 ;; because "M-x" is a well-known prompt to read a command
1707 ;; and it serves as a shorthand for "Extended command: ".
1708 "M-x ")
1709 (lambda (string pred action)
1710 (let ((pred
1711 (if (memq action '(nil t))
1712 ;; Exclude obsolete commands from completions.
1713 (lambda (sym)
1714 (and (funcall pred sym)
1715 (or (equal string (symbol-name sym))
1716 (not (get sym 'byte-obsolete-info)))))
1717 pred)))
1718 (complete-with-action action obarray string pred)))
1719 #'commandp t nil 'extended-command-history)))
1721 (defcustom suggest-key-bindings t
1722 "Non-nil means show the equivalent key-binding when M-x command has one.
1723 The value can be a length of time to show the message for.
1724 If the value is non-nil and not a number, we wait 2 seconds."
1725 :group 'keyboard
1726 :type '(choice (const :tag "off" nil)
1727 (integer :tag "time" 2)
1728 (other :tag "on")))
1730 (defcustom extended-command-suggest-shorter t
1731 "If non-nil, show a shorter M-x invocation when there is one."
1732 :group 'keyboard
1733 :type 'boolean
1734 :version "26.1")
1736 (defun execute-extended-command--shorter-1 (name length)
1737 (cond
1738 ((zerop length) (list ""))
1739 ((equal name "") nil)
1741 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1742 (execute-extended-command--shorter-1
1743 (substring name 1) (1- length)))
1744 (when (string-match "\\`\\(-\\)?[^-]*" name)
1745 (execute-extended-command--shorter-1
1746 (substring name (match-end 0)) length))))))
1748 (defun execute-extended-command--shorter (name typed)
1749 (let ((candidates '())
1750 (max (length typed))
1751 (len 1)
1752 binding)
1753 (while (and (not binding)
1754 (progn
1755 (unless candidates
1756 (setq len (1+ len))
1757 (setq candidates (execute-extended-command--shorter-1
1758 name len)))
1759 ;; Don't show the help message if the binding isn't
1760 ;; significantly shorter than the M-x command the user typed.
1761 (< len (- max 5))))
1762 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1763 (let ((candidate (pop candidates)))
1764 (when (equal name
1765 (car-safe (completion-try-completion
1766 candidate obarray 'commandp len)))
1767 (setq binding candidate))))
1768 binding))
1770 (defun execute-extended-command (prefixarg &optional command-name typed)
1771 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1772 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1773 "Read a command name, then read the arguments and call the command.
1774 To pass a prefix argument to the command you are
1775 invoking, give a prefix argument to `execute-extended-command'."
1776 (declare (interactive-only command-execute))
1777 ;; FIXME: Remember the actual text typed by the user before completion,
1778 ;; so that we don't later on suggest the same shortening.
1779 (interactive
1780 (let ((execute-extended-command--last-typed nil))
1781 (list current-prefix-arg
1782 (read-extended-command)
1783 execute-extended-command--last-typed)))
1784 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1785 (unless command-name
1786 (let ((current-prefix-arg prefixarg) ; for prompt
1787 (execute-extended-command--last-typed nil))
1788 (setq command-name (read-extended-command))
1789 (setq typed execute-extended-command--last-typed)))
1790 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1791 (binding (and suggest-key-bindings
1792 (not executing-kbd-macro)
1793 (where-is-internal function overriding-local-map t))))
1794 (unless (commandp function)
1795 (error "`%s' is not a valid command name" command-name))
1796 ;; Some features, such as novice.el, rely on this-command-keys
1797 ;; including M-x COMMAND-NAME RET.
1798 (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
1799 (setq this-command function)
1800 ;; Normally `real-this-command' should never be changed, but here we really
1801 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1802 ;; binding" for <cmd>, so the command the user really wanted to run is
1803 ;; `function' and not `execute-extended-command'. The difference is
1804 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1805 (setq real-this-command function)
1806 (let ((prefix-arg prefixarg))
1807 (command-execute function 'record))
1808 ;; If enabled, show which key runs this command.
1809 ;; But first wait, and skip the message if there is input.
1810 (let* ((waited
1811 ;; If this command displayed something in the echo area;
1812 ;; wait a few seconds, then display our suggestion message.
1813 ;; FIXME: Wait *after* running post-command-hook!
1814 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1815 ;; find a better answer anyway!
1816 (when suggest-key-bindings
1817 (sit-for (cond
1818 ((zerop (length (current-message))) 0)
1819 ((numberp suggest-key-bindings) suggest-key-bindings)
1820 (t 2))))))
1821 (when (and waited (not (consp unread-command-events)))
1822 (unless (or (not extended-command-suggest-shorter)
1823 binding executing-kbd-macro (not (symbolp function))
1824 (<= (length (symbol-name function)) 2))
1825 ;; There's no binding for CMD. Let's try and find the shortest
1826 ;; string to use in M-x.
1827 ;; FIXME: Can be slow. Cache it maybe?
1828 (while-no-input
1829 (setq binding (execute-extended-command--shorter
1830 (symbol-name function) typed))))
1831 (when binding
1832 (with-temp-message
1833 (format-message "You can run the command `%s' with %s"
1834 function
1835 (if (stringp binding)
1836 (concat "M-x " binding " RET")
1837 (key-description binding)))
1838 (sit-for (if (numberp suggest-key-bindings)
1839 suggest-key-bindings
1840 2))))))))
1842 (defun command-execute (cmd &optional record-flag keys special)
1843 ;; BEWARE: Called directly from the C code.
1844 "Execute CMD as an editor command.
1845 CMD must be a symbol that satisfies the `commandp' predicate.
1846 Optional second arg RECORD-FLAG non-nil
1847 means unconditionally put this command in the variable `command-history'.
1848 Otherwise, that is done only if an arg is read using the minibuffer.
1849 The argument KEYS specifies the value to use instead of (this-command-keys)
1850 when reading the arguments; if it is nil, (this-command-keys) is used.
1851 The argument SPECIAL, if non-nil, means that this command is executing
1852 a special event, so ignore the prefix argument and don't clear it."
1853 (setq debug-on-next-call nil)
1854 (let ((prefixarg (unless special
1855 ;; FIXME: This should probably be done around
1856 ;; pre-command-hook rather than here!
1857 (prog1 prefix-arg
1858 (setq current-prefix-arg prefix-arg)
1859 (setq prefix-arg nil)
1860 (when current-prefix-arg
1861 (prefix-command-update))))))
1862 (if (and (symbolp cmd)
1863 (get cmd 'disabled)
1864 disabled-command-function)
1865 ;; FIXME: Weird calling convention!
1866 (run-hooks 'disabled-command-function)
1867 (let ((final cmd))
1868 (while
1869 (progn
1870 (setq final (indirect-function final))
1871 (if (autoloadp final)
1872 (setq final (autoload-do-load final cmd)))))
1873 (cond
1874 ((arrayp final)
1875 ;; If requested, place the macro in the command history. For
1876 ;; other sorts of commands, call-interactively takes care of this.
1877 (when record-flag
1878 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1879 ;; Don't keep command history around forever.
1880 (when (and (numberp history-length) (> history-length 0))
1881 (let ((cell (nthcdr history-length command-history)))
1882 (if (consp cell) (setcdr cell nil)))))
1883 (execute-kbd-macro final prefixarg))
1885 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1886 (prog1 (call-interactively cmd record-flag keys)
1887 (when (and (symbolp cmd)
1888 (get cmd 'byte-obsolete-info)
1889 (not (get cmd 'command-execute-obsolete-warned)))
1890 (put cmd 'command-execute-obsolete-warned t)
1891 (message "%s" (macroexp--obsolete-warning
1892 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1894 (defvar minibuffer-history nil
1895 "Default minibuffer history list.
1896 This is used for all minibuffer input
1897 except when an alternate history list is specified.
1899 Maximum length of the history list is determined by the value
1900 of `history-length', which see.")
1901 (defvar minibuffer-history-sexp-flag nil
1902 "Control whether history list elements are expressions or strings.
1903 If the value of this variable equals current minibuffer depth,
1904 they are expressions; otherwise they are strings.
1905 \(That convention is designed to do the right thing for
1906 recursive uses of the minibuffer.)")
1907 (setq minibuffer-history-variable 'minibuffer-history)
1908 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1909 (defvar minibuffer-history-search-history nil)
1911 (defvar minibuffer-text-before-history nil
1912 "Text that was in this minibuffer before any history commands.
1913 This is nil if there have not yet been any history commands
1914 in this use of the minibuffer.")
1916 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1918 (defun minibuffer-history-initialize ()
1919 (setq minibuffer-text-before-history nil))
1921 (defun minibuffer-avoid-prompt (_new _old)
1922 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1923 (declare (obsolete cursor-intangible-mode "25.1"))
1924 (constrain-to-field nil (point-max)))
1926 (defcustom minibuffer-history-case-insensitive-variables nil
1927 "Minibuffer history variables for which matching should ignore case.
1928 If a history variable is a member of this list, then the
1929 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1930 commands ignore case when searching it, regardless of `case-fold-search'."
1931 :type '(repeat variable)
1932 :group 'minibuffer)
1934 (defun previous-matching-history-element (regexp n)
1935 "Find the previous history element that matches REGEXP.
1936 \(Previous history elements refer to earlier actions.)
1937 With prefix argument N, search for Nth previous match.
1938 If N is negative, find the next or Nth next match.
1939 Normally, history elements are matched case-insensitively if
1940 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1941 makes the search case-sensitive.
1942 See also `minibuffer-history-case-insensitive-variables'."
1943 (interactive
1944 (let* ((enable-recursive-minibuffers t)
1945 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1947 minibuffer-local-map
1949 'minibuffer-history-search-history
1950 (car minibuffer-history-search-history))))
1951 ;; Use the last regexp specified, by default, if input is empty.
1952 (list (if (string= regexp "")
1953 (if minibuffer-history-search-history
1954 (car minibuffer-history-search-history)
1955 (user-error "No previous history search regexp"))
1956 regexp)
1957 (prefix-numeric-value current-prefix-arg))))
1958 (unless (zerop n)
1959 (if (and (zerop minibuffer-history-position)
1960 (null minibuffer-text-before-history))
1961 (setq minibuffer-text-before-history
1962 (minibuffer-contents-no-properties)))
1963 (let ((history (symbol-value minibuffer-history-variable))
1964 (case-fold-search
1965 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1966 ;; On some systems, ignore case for file names.
1967 (if (memq minibuffer-history-variable
1968 minibuffer-history-case-insensitive-variables)
1970 ;; Respect the user's setting for case-fold-search:
1971 case-fold-search)
1972 nil))
1973 prevpos
1974 match-string
1975 match-offset
1976 (pos minibuffer-history-position))
1977 (while (/= n 0)
1978 (setq prevpos pos)
1979 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1980 (when (= pos prevpos)
1981 (user-error (if (= pos 1)
1982 "No later matching history item"
1983 "No earlier matching history item")))
1984 (setq match-string
1985 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1986 (let ((print-level nil))
1987 (prin1-to-string (nth (1- pos) history)))
1988 (nth (1- pos) history)))
1989 (setq match-offset
1990 (if (< n 0)
1991 (and (string-match regexp match-string)
1992 (match-end 0))
1993 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1994 (match-beginning 1))))
1995 (when match-offset
1996 (setq n (+ n (if (< n 0) 1 -1)))))
1997 (setq minibuffer-history-position pos)
1998 (goto-char (point-max))
1999 (delete-minibuffer-contents)
2000 (insert match-string)
2001 (goto-char (+ (minibuffer-prompt-end) match-offset))))
2002 (if (memq (car (car command-history)) '(previous-matching-history-element
2003 next-matching-history-element))
2004 (setq command-history (cdr command-history))))
2006 (defun next-matching-history-element (regexp n)
2007 "Find the next history element that matches REGEXP.
2008 \(The next history element refers to a more recent action.)
2009 With prefix argument N, search for Nth next match.
2010 If N is negative, find the previous or Nth previous match.
2011 Normally, history elements are matched case-insensitively if
2012 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
2013 makes the search case-sensitive."
2014 (interactive
2015 (let* ((enable-recursive-minibuffers t)
2016 (regexp (read-from-minibuffer "Next element matching (regexp): "
2018 minibuffer-local-map
2020 'minibuffer-history-search-history
2021 (car minibuffer-history-search-history))))
2022 ;; Use the last regexp specified, by default, if input is empty.
2023 (list (if (string= regexp "")
2024 (if minibuffer-history-search-history
2025 (car minibuffer-history-search-history)
2026 (user-error "No previous history search regexp"))
2027 regexp)
2028 (prefix-numeric-value current-prefix-arg))))
2029 (previous-matching-history-element regexp (- n)))
2031 (defvar minibuffer-temporary-goal-position nil)
2033 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
2034 "Function run by `goto-history-element' before consuming default values.
2035 This is useful to dynamically add more elements to the list of default values
2036 when `goto-history-element' reaches the end of this list.
2037 Before calling this function `goto-history-element' sets the variable
2038 `minibuffer-default-add-done' to t, so it will call this function only
2039 once. In special cases, when this function needs to be called more
2040 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2041 overriding the setting of this variable to t in `goto-history-element'.")
2043 (defvar minibuffer-default-add-done nil
2044 "When nil, add more elements to the end of the list of default values.
2045 The value nil causes `goto-history-element' to add more elements to
2046 the list of defaults when it reaches the end of this list. It does
2047 this by calling a function defined by `minibuffer-default-add-function'.")
2049 (make-variable-buffer-local 'minibuffer-default-add-done)
2051 (defun minibuffer-default-add-completions ()
2052 "Return a list of all completions without the default value.
2053 This function is used to add all elements of the completion table to
2054 the end of the list of defaults just after the default value."
2055 (let ((def minibuffer-default)
2056 (all (all-completions ""
2057 minibuffer-completion-table
2058 minibuffer-completion-predicate)))
2059 (if (listp def)
2060 (append def all)
2061 (cons def (delete def all)))))
2063 (defun goto-history-element (nabs)
2064 "Puts element of the minibuffer history in the minibuffer.
2065 The argument NABS specifies the absolute history position."
2066 (interactive "p")
2067 (when (and (not minibuffer-default-add-done)
2068 (functionp minibuffer-default-add-function)
2069 (< nabs (- (if (listp minibuffer-default)
2070 (length minibuffer-default)
2071 1))))
2072 (setq minibuffer-default-add-done t
2073 minibuffer-default (funcall minibuffer-default-add-function)))
2074 (let ((minimum (if minibuffer-default
2075 (- (if (listp minibuffer-default)
2076 (length minibuffer-default)
2079 elt minibuffer-returned-to-present)
2080 (if (and (zerop minibuffer-history-position)
2081 (null minibuffer-text-before-history))
2082 (setq minibuffer-text-before-history
2083 (minibuffer-contents-no-properties)))
2084 (if (< nabs minimum)
2085 (user-error (if minibuffer-default
2086 "End of defaults; no next item"
2087 "End of history; no default available")))
2088 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2089 (length (symbol-value minibuffer-history-variable))
2091 (user-error "Beginning of history; no preceding item"))
2092 (unless (memq last-command '(next-history-element
2093 previous-history-element))
2094 (let ((prompt-end (minibuffer-prompt-end)))
2095 (set (make-local-variable 'minibuffer-temporary-goal-position)
2096 (cond ((<= (point) prompt-end) prompt-end)
2097 ((eobp) nil)
2098 (t (point))))))
2099 (goto-char (point-max))
2100 (delete-minibuffer-contents)
2101 (setq minibuffer-history-position nabs)
2102 (cond ((< nabs 0)
2103 (setq elt (if (listp minibuffer-default)
2104 (nth (1- (abs nabs)) minibuffer-default)
2105 minibuffer-default)))
2106 ((= nabs 0)
2107 (setq elt (or minibuffer-text-before-history ""))
2108 (setq minibuffer-returned-to-present t)
2109 (setq minibuffer-text-before-history nil))
2110 (t (setq elt (nth (1- minibuffer-history-position)
2111 (symbol-value minibuffer-history-variable)))))
2112 (insert
2113 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2114 (not minibuffer-returned-to-present))
2115 (let ((print-level nil))
2116 (prin1-to-string elt))
2117 elt))
2118 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2120 (defun next-history-element (n)
2121 "Puts next element of the minibuffer history in the minibuffer.
2122 With argument N, it uses the Nth following element."
2123 (interactive "p")
2124 (or (zerop n)
2125 (goto-history-element (- minibuffer-history-position n))))
2127 (defun previous-history-element (n)
2128 "Puts previous element of the minibuffer history in the minibuffer.
2129 With argument N, it uses the Nth previous element."
2130 (interactive "p")
2131 (or (zerop n)
2132 (goto-history-element (+ minibuffer-history-position n))))
2134 (defun next-line-or-history-element (&optional arg)
2135 "Move cursor vertically down ARG lines, or to the next history element.
2136 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2137 next element of the minibuffer history in the minibuffer."
2138 (interactive "^p")
2139 (or arg (setq arg 1))
2140 (let* ((old-point (point))
2141 ;; Don't add newlines if they have the mode enabled globally.
2142 (next-line-add-newlines nil)
2143 ;; Remember the original goal column of possibly multi-line input
2144 ;; excluding the length of the prompt on the first line.
2145 (prompt-end (minibuffer-prompt-end))
2146 (old-column (unless (and (eolp) (> (point) prompt-end))
2147 (if (= (line-number-at-pos) 1)
2148 (max (- (current-column) (1- prompt-end)) 0)
2149 (current-column)))))
2150 (condition-case nil
2151 (with-no-warnings
2152 (next-line arg))
2153 (end-of-buffer
2154 ;; Restore old position since `line-move-visual' moves point to
2155 ;; the end of the line when it fails to go to the next line.
2156 (goto-char old-point)
2157 (next-history-element arg)
2158 ;; Reset `temporary-goal-column' because a correct value is not
2159 ;; calculated when `next-line' above fails by bumping against
2160 ;; the bottom of the minibuffer (bug#22544).
2161 (setq temporary-goal-column 0)
2162 ;; Restore the original goal column on the last line
2163 ;; of possibly multi-line input.
2164 (goto-char (point-max))
2165 (when old-column
2166 (if (= (line-number-at-pos) 1)
2167 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2168 (move-to-column old-column)))))))
2170 (defun previous-line-or-history-element (&optional arg)
2171 "Move cursor vertically up ARG lines, or to the previous history element.
2172 When point moves over the top line of multi-line minibuffer, puts ARGth
2173 previous element of the minibuffer history in the minibuffer."
2174 (interactive "^p")
2175 (or arg (setq arg 1))
2176 (let* ((old-point (point))
2177 ;; Remember the original goal column of possibly multi-line input
2178 ;; excluding the length of the prompt on the first line.
2179 (prompt-end (minibuffer-prompt-end))
2180 (old-column (unless (and (eolp) (> (point) prompt-end))
2181 (if (= (line-number-at-pos) 1)
2182 (max (- (current-column) (1- prompt-end)) 0)
2183 (current-column)))))
2184 (condition-case nil
2185 (with-no-warnings
2186 (previous-line arg))
2187 (beginning-of-buffer
2188 ;; Restore old position since `line-move-visual' moves point to
2189 ;; the beginning of the line when it fails to go to the previous line.
2190 (goto-char old-point)
2191 (previous-history-element arg)
2192 ;; Reset `temporary-goal-column' because a correct value is not
2193 ;; calculated when `previous-line' above fails by bumping against
2194 ;; the top of the minibuffer (bug#22544).
2195 (setq temporary-goal-column 0)
2196 ;; Restore the original goal column on the first line
2197 ;; of possibly multi-line input.
2198 (goto-char (minibuffer-prompt-end))
2199 (if old-column
2200 (if (= (line-number-at-pos) 1)
2201 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2202 (move-to-column old-column))
2203 ;; Put the cursor at the end of the visual line instead of the
2204 ;; logical line, so the next `previous-line-or-history-element'
2205 ;; would move to the previous history element, not to a possible upper
2206 ;; visual line from the end of logical line in `line-move-visual' mode.
2207 (end-of-visual-line)
2208 ;; Since `end-of-visual-line' puts the cursor at the beginning
2209 ;; of the next visual line, move it one char back to the end
2210 ;; of the first visual line (bug#22544).
2211 (unless (eolp) (backward-char 1)))))))
2213 (defun next-complete-history-element (n)
2214 "Get next history element which completes the minibuffer before the point.
2215 The contents of the minibuffer after the point are deleted, and replaced
2216 by the new completion."
2217 (interactive "p")
2218 (let ((point-at-start (point)))
2219 (next-matching-history-element
2220 (concat
2221 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2223 ;; next-matching-history-element always puts us at (point-min).
2224 ;; Move to the position we were at before changing the buffer contents.
2225 ;; This is still sensible, because the text before point has not changed.
2226 (goto-char point-at-start)))
2228 (defun previous-complete-history-element (n)
2230 Get previous history element which completes the minibuffer before the point.
2231 The contents of the minibuffer after the point are deleted, and replaced
2232 by the new completion."
2233 (interactive "p")
2234 (next-complete-history-element (- n)))
2236 ;; For compatibility with the old subr of the same name.
2237 (defun minibuffer-prompt-width ()
2238 "Return the display width of the minibuffer prompt.
2239 Return 0 if current buffer is not a minibuffer."
2240 ;; Return the width of everything before the field at the end of
2241 ;; the buffer; this should be 0 for normal buffers.
2242 (1- (minibuffer-prompt-end)))
2244 ;; isearch minibuffer history
2245 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2247 (defvar minibuffer-history-isearch-message-overlay)
2248 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2250 (defun minibuffer-history-isearch-setup ()
2251 "Set up a minibuffer for using isearch to search the minibuffer history.
2252 Intended to be added to `minibuffer-setup-hook'."
2253 (set (make-local-variable 'isearch-search-fun-function)
2254 'minibuffer-history-isearch-search)
2255 (set (make-local-variable 'isearch-message-function)
2256 'minibuffer-history-isearch-message)
2257 (set (make-local-variable 'isearch-wrap-function)
2258 'minibuffer-history-isearch-wrap)
2259 (set (make-local-variable 'isearch-push-state-function)
2260 'minibuffer-history-isearch-push-state)
2261 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2263 (defun minibuffer-history-isearch-end ()
2264 "Clean up the minibuffer after terminating isearch in the minibuffer."
2265 (if minibuffer-history-isearch-message-overlay
2266 (delete-overlay minibuffer-history-isearch-message-overlay)))
2268 (defun minibuffer-history-isearch-search ()
2269 "Return the proper search function, for isearch in minibuffer history."
2270 (lambda (string bound noerror)
2271 (let ((search-fun
2272 ;; Use standard functions to search within minibuffer text
2273 (isearch-search-fun-default))
2274 found)
2275 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2276 ;; searching forward. Lazy-highlight calls this lambda with the
2277 ;; bound arg, so skip the minibuffer prompt.
2278 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2279 (goto-char (minibuffer-prompt-end)))
2281 ;; 1. First try searching in the initial minibuffer text
2282 (funcall search-fun string
2283 (if isearch-forward bound (minibuffer-prompt-end))
2284 noerror)
2285 ;; 2. If the above search fails, start putting next/prev history
2286 ;; elements in the minibuffer successively, and search the string
2287 ;; in them. Do this only when bound is nil (i.e. not while
2288 ;; lazy-highlighting search strings in the current minibuffer text).
2289 (unless bound
2290 (condition-case nil
2291 (progn
2292 (while (not found)
2293 (cond (isearch-forward
2294 (next-history-element 1)
2295 (goto-char (minibuffer-prompt-end)))
2297 (previous-history-element 1)
2298 (goto-char (point-max))))
2299 (setq isearch-barrier (point) isearch-opoint (point))
2300 ;; After putting the next/prev history element, search
2301 ;; the string in them again, until next-history-element
2302 ;; or previous-history-element raises an error at the
2303 ;; beginning/end of history.
2304 (setq found (funcall search-fun string
2305 (unless isearch-forward
2306 ;; For backward search, don't search
2307 ;; in the minibuffer prompt
2308 (minibuffer-prompt-end))
2309 noerror)))
2310 ;; Return point of the new search result
2311 (point))
2312 ;; Return nil when next(prev)-history-element fails
2313 (error nil)))))))
2315 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2316 "Display the minibuffer history search prompt.
2317 If there are no search errors, this function displays an overlay with
2318 the isearch prompt which replaces the original minibuffer prompt.
2319 Otherwise, it displays the standard isearch message returned from
2320 the function `isearch-message'."
2321 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2322 ;; Use standard function `isearch-message' when not in the minibuffer,
2323 ;; or search fails, or has an error (like incomplete regexp).
2324 ;; This function overwrites minibuffer text with isearch message,
2325 ;; so it's possible to see what is wrong in the search string.
2326 (isearch-message c-q-hack ellipsis)
2327 ;; Otherwise, put the overlay with the standard isearch prompt over
2328 ;; the initial minibuffer prompt.
2329 (if (overlayp minibuffer-history-isearch-message-overlay)
2330 (move-overlay minibuffer-history-isearch-message-overlay
2331 (point-min) (minibuffer-prompt-end))
2332 (setq minibuffer-history-isearch-message-overlay
2333 (make-overlay (point-min) (minibuffer-prompt-end)))
2334 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2335 (overlay-put minibuffer-history-isearch-message-overlay
2336 'display (isearch-message-prefix c-q-hack ellipsis))
2337 ;; And clear any previous isearch message.
2338 (message "")))
2340 (defun minibuffer-history-isearch-wrap ()
2341 "Wrap the minibuffer history search when search fails.
2342 Move point to the first history element for a forward search,
2343 or to the last history element for a backward search."
2344 ;; When `minibuffer-history-isearch-search' fails on reaching the
2345 ;; beginning/end of the history, wrap the search to the first/last
2346 ;; minibuffer history element.
2347 (if isearch-forward
2348 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2349 (goto-history-element 0))
2350 (setq isearch-success t)
2351 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2353 (defun minibuffer-history-isearch-push-state ()
2354 "Save a function restoring the state of minibuffer history search.
2355 Save `minibuffer-history-position' to the additional state parameter
2356 in the search status stack."
2357 (let ((pos minibuffer-history-position))
2358 (lambda (cmd)
2359 (minibuffer-history-isearch-pop-state cmd pos))))
2361 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2362 "Restore the minibuffer history search state.
2363 Go to the history element by the absolute history position HIST-POS."
2364 (goto-history-element hist-pos))
2367 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2368 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2370 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2371 "Table mapping redo records to the corresponding undo one.
2372 A redo record for undo-in-region maps to t.
2373 A redo record for ordinary undo maps to the following (earlier) undo.")
2375 (defvar undo-in-region nil
2376 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2378 (defvar undo-no-redo nil
2379 "If t, `undo' doesn't go through redo entries.")
2381 (defvar pending-undo-list nil
2382 "Within a run of consecutive undo commands, list remaining to be undone.
2383 If t, we undid all the way to the end of it.")
2385 (defun undo (&optional arg)
2386 "Undo some previous changes.
2387 Repeat this command to undo more changes.
2388 A numeric ARG serves as a repeat count.
2390 In Transient Mark mode when the mark is active, only undo changes within
2391 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2392 as an argument limits undo to changes within the current region."
2393 (interactive "*P")
2394 ;; Make last-command indicate for the next command that this was an undo.
2395 ;; That way, another undo will undo more.
2396 ;; If we get to the end of the undo history and get an error,
2397 ;; another undo command will find the undo history empty
2398 ;; and will get another error. To begin undoing the undos,
2399 ;; you must type some other command.
2400 (let* ((modified (buffer-modified-p))
2401 ;; For an indirect buffer, look in the base buffer for the
2402 ;; auto-save data.
2403 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2404 (recent-save (with-current-buffer base-buffer
2405 (recent-auto-save-p)))
2406 message)
2407 ;; If we get an error in undo-start,
2408 ;; the next command should not be a "consecutive undo".
2409 ;; So set `this-command' to something other than `undo'.
2410 (setq this-command 'undo-start)
2412 (unless (and (eq last-command 'undo)
2413 (or (eq pending-undo-list t)
2414 ;; If something (a timer or filter?) changed the buffer
2415 ;; since the previous command, don't continue the undo seq.
2416 (let ((list buffer-undo-list))
2417 (while (eq (car list) nil)
2418 (setq list (cdr list)))
2419 ;; If the last undo record made was made by undo
2420 ;; it shows nothing else happened in between.
2421 (gethash list undo-equiv-table))))
2422 (setq undo-in-region
2423 (or (region-active-p) (and arg (not (numberp arg)))))
2424 (if undo-in-region
2425 (undo-start (region-beginning) (region-end))
2426 (undo-start))
2427 ;; get rid of initial undo boundary
2428 (undo-more 1))
2429 ;; If we got this far, the next command should be a consecutive undo.
2430 (setq this-command 'undo)
2431 ;; Check to see whether we're hitting a redo record, and if
2432 ;; so, ask the user whether she wants to skip the redo/undo pair.
2433 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2434 (or (eq (selected-window) (minibuffer-window))
2435 (setq message (format "%s%s!"
2436 (if (or undo-no-redo (not equiv))
2437 "Undo" "Redo")
2438 (if undo-in-region " in region" ""))))
2439 (when (and (consp equiv) undo-no-redo)
2440 ;; The equiv entry might point to another redo record if we have done
2441 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2442 (while (let ((next (gethash equiv undo-equiv-table)))
2443 (if next (setq equiv next))))
2444 (setq pending-undo-list equiv)))
2445 (undo-more
2446 (if (numberp arg)
2447 (prefix-numeric-value arg)
2449 ;; Record the fact that the just-generated undo records come from an
2450 ;; undo operation--that is, they are redo records.
2451 ;; In the ordinary case (not within a region), map the redo
2452 ;; record to the following undos.
2453 ;; I don't know how to do that in the undo-in-region case.
2454 (let ((list buffer-undo-list))
2455 ;; Strip any leading undo boundaries there might be, like we do
2456 ;; above when checking.
2457 (while (eq (car list) nil)
2458 (setq list (cdr list)))
2459 (puthash list
2460 ;; Prevent identity mapping. This can happen if
2461 ;; consecutive nils are erroneously in undo list.
2462 (if (or undo-in-region (eq list pending-undo-list))
2464 pending-undo-list)
2465 undo-equiv-table))
2466 ;; Don't specify a position in the undo record for the undo command.
2467 ;; Instead, undoing this should move point to where the change is.
2468 (let ((tail buffer-undo-list)
2469 (prev nil))
2470 (while (car tail)
2471 (when (integerp (car tail))
2472 (let ((pos (car tail)))
2473 (if prev
2474 (setcdr prev (cdr tail))
2475 (setq buffer-undo-list (cdr tail)))
2476 (setq tail (cdr tail))
2477 (while (car tail)
2478 (if (eq pos (car tail))
2479 (if prev
2480 (setcdr prev (cdr tail))
2481 (setq buffer-undo-list (cdr tail)))
2482 (setq prev tail))
2483 (setq tail (cdr tail)))
2484 (setq tail nil)))
2485 (setq prev tail tail (cdr tail))))
2486 ;; Record what the current undo list says,
2487 ;; so the next command can tell if the buffer was modified in between.
2488 (and modified (not (buffer-modified-p))
2489 (with-current-buffer base-buffer
2490 (delete-auto-save-file-if-necessary recent-save)))
2491 ;; Display a message announcing success.
2492 (if message
2493 (message "%s" message))))
2495 (defun buffer-disable-undo (&optional buffer)
2496 "Make BUFFER stop keeping undo information.
2497 No argument or nil as argument means do this for the current buffer."
2498 (interactive)
2499 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2500 (setq buffer-undo-list t)))
2502 (defun undo-only (&optional arg)
2503 "Undo some previous changes.
2504 Repeat this command to undo more changes.
2505 A numeric ARG serves as a repeat count.
2506 Contrary to `undo', this will not redo a previous undo."
2507 (interactive "*p")
2508 (let ((undo-no-redo t)) (undo arg)))
2510 (defvar undo-in-progress nil
2511 "Non-nil while performing an undo.
2512 Some change-hooks test this variable to do something different.")
2514 (defun undo-more (n)
2515 "Undo back N undo-boundaries beyond what was already undone recently.
2516 Call `undo-start' to get ready to undo recent changes,
2517 then call `undo-more' one or more times to undo them."
2518 (or (listp pending-undo-list)
2519 (user-error (concat "No further undo information"
2520 (and undo-in-region " for region"))))
2521 (let ((undo-in-progress t))
2522 ;; Note: The following, while pulling elements off
2523 ;; `pending-undo-list' will call primitive change functions which
2524 ;; will push more elements onto `buffer-undo-list'.
2525 (setq pending-undo-list (primitive-undo n pending-undo-list))
2526 (if (null pending-undo-list)
2527 (setq pending-undo-list t))))
2529 (defun primitive-undo (n list)
2530 "Undo N records from the front of the list LIST.
2531 Return what remains of the list."
2533 ;; This is a good feature, but would make undo-start
2534 ;; unable to do what is expected.
2535 ;;(when (null (car (list)))
2536 ;; ;; If the head of the list is a boundary, it is the boundary
2537 ;; ;; preceding this command. Get rid of it and don't count it.
2538 ;; (setq list (cdr list))))
2540 (let ((arg n)
2541 ;; In a writable buffer, enable undoing read-only text that is
2542 ;; so because of text properties.
2543 (inhibit-read-only t)
2544 ;; Don't let `intangible' properties interfere with undo.
2545 (inhibit-point-motion-hooks t)
2546 ;; We use oldlist only to check for EQ. ++kfs
2547 (oldlist buffer-undo-list)
2548 (did-apply nil)
2549 (next nil))
2550 (while (> arg 0)
2551 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2552 ;; Handle an integer by setting point to that value.
2553 (pcase next
2554 ((pred integerp) (goto-char next))
2555 ;; Element (t . TIME) records previous modtime.
2556 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2557 ;; UNKNOWN_MODTIME_NSECS.
2558 (`(t . ,time)
2559 ;; If this records an obsolete save
2560 ;; (not matching the actual disk file)
2561 ;; then don't mark unmodified.
2562 (when (or (equal time (visited-file-modtime))
2563 (and (consp time)
2564 (equal (list (car time) (cdr time))
2565 (visited-file-modtime))))
2566 (when (fboundp 'unlock-buffer)
2567 (unlock-buffer))
2568 (set-buffer-modified-p nil)))
2569 ;; Element (nil PROP VAL BEG . END) is property change.
2570 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2571 (when (or (> (point-min) beg) (< (point-max) end))
2572 (error "Changes to be undone are outside visible portion of buffer"))
2573 (put-text-property beg end prop val))
2574 ;; Element (BEG . END) means range was inserted.
2575 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2576 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2577 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2578 (when (or (> (point-min) beg) (< (point-max) end))
2579 (error "Changes to be undone are outside visible portion of buffer"))
2580 ;; Set point first thing, so that undoing this undo
2581 ;; does not send point back to where it is now.
2582 (goto-char beg)
2583 (delete-region beg end))
2584 ;; Element (apply FUN . ARGS) means call FUN to undo.
2585 (`(apply . ,fun-args)
2586 (let ((currbuff (current-buffer)))
2587 (if (integerp (car fun-args))
2588 ;; Long format: (apply DELTA START END FUN . ARGS).
2589 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2590 (start-mark (copy-marker start nil))
2591 (end-mark (copy-marker end t)))
2592 (when (or (> (point-min) start) (< (point-max) end))
2593 (error "Changes to be undone are outside visible portion of buffer"))
2594 (apply fun args) ;; Use `save-current-buffer'?
2595 ;; Check that the function did what the entry
2596 ;; said it would do.
2597 (unless (and (= start start-mark)
2598 (= (+ delta end) end-mark))
2599 (error "Changes to be undone by function different than announced"))
2600 (set-marker start-mark nil)
2601 (set-marker end-mark nil))
2602 (apply fun-args))
2603 (unless (eq currbuff (current-buffer))
2604 (error "Undo function switched buffer"))
2605 (setq did-apply t)))
2606 ;; Element (STRING . POS) means STRING was deleted.
2607 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2608 (let ((valid-marker-adjustments nil)
2609 (apos (abs pos)))
2610 (when (or (< apos (point-min)) (> apos (point-max)))
2611 (error "Changes to be undone are outside visible portion of buffer"))
2612 ;; Check that marker adjustments which were recorded
2613 ;; with the (STRING . POS) record are still valid, ie
2614 ;; the markers haven't moved. We check their validity
2615 ;; before reinserting the string so as we don't need to
2616 ;; mind marker insertion-type.
2617 (while (and (markerp (car-safe (car list)))
2618 (integerp (cdr-safe (car list))))
2619 (let* ((marker-adj (pop list))
2620 (m (car marker-adj)))
2621 (and (eq (marker-buffer m) (current-buffer))
2622 (= apos m)
2623 (push marker-adj valid-marker-adjustments))))
2624 ;; Insert string and adjust point
2625 (if (< pos 0)
2626 (progn
2627 (goto-char (- pos))
2628 (insert string))
2629 (goto-char pos)
2630 (insert string)
2631 (goto-char pos))
2632 ;; Adjust the valid marker adjustments
2633 (dolist (adj valid-marker-adjustments)
2634 ;; Insert might have invalidated some of the markers
2635 ;; via modification hooks. Update only the currently
2636 ;; valid ones (bug#25599).
2637 (if (marker-buffer (car adj))
2638 (set-marker (car adj)
2639 (- (car adj) (cdr adj)))))))
2640 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2641 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2642 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2643 next)
2644 ;; Even though these elements are not expected in the undo
2645 ;; list, adjust them to be conservative for the 24.4
2646 ;; release. (Bug#16818)
2647 (when (marker-buffer marker)
2648 (set-marker marker
2649 (- marker offset)
2650 (marker-buffer marker))))
2651 (_ (error "Unrecognized entry in undo list %S" next))))
2652 (setq arg (1- arg)))
2653 ;; Make sure an apply entry produces at least one undo entry,
2654 ;; so the test in `undo' for continuing an undo series
2655 ;; will work right.
2656 (if (and did-apply
2657 (eq oldlist buffer-undo-list))
2658 (setq buffer-undo-list
2659 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2660 list)
2662 ;; Deep copy of a list
2663 (defun undo-copy-list (list)
2664 "Make a copy of undo list LIST."
2665 (mapcar 'undo-copy-list-1 list))
2667 (defun undo-copy-list-1 (elt)
2668 (if (consp elt)
2669 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2670 elt))
2672 (defun undo-start (&optional beg end)
2673 "Set `pending-undo-list' to the front of the undo list.
2674 The next call to `undo-more' will undo the most recently made change.
2675 If BEG and END are specified, then only undo elements
2676 that apply to text between BEG and END are used; other undo elements
2677 are ignored. If BEG and END are nil, all undo elements are used."
2678 (if (eq buffer-undo-list t)
2679 (user-error "No undo information in this buffer"))
2680 (setq pending-undo-list
2681 (if (and beg end (not (= beg end)))
2682 (undo-make-selective-list (min beg end) (max beg end))
2683 buffer-undo-list)))
2685 ;; The positions given in elements of the undo list are the positions
2686 ;; as of the time that element was recorded to undo history. In
2687 ;; general, subsequent buffer edits render those positions invalid in
2688 ;; the current buffer, unless adjusted according to the intervening
2689 ;; undo elements.
2691 ;; Undo in region is a use case that requires adjustments to undo
2692 ;; elements. It must adjust positions of elements in the region based
2693 ;; on newer elements not in the region so as they may be correctly
2694 ;; applied in the current buffer. undo-make-selective-list
2695 ;; accomplishes this with its undo-deltas list of adjustments. An
2696 ;; example undo history from oldest to newest:
2698 ;; buf pos:
2699 ;; 123456789 buffer-undo-list undo-deltas
2700 ;; --------- ---------------- -----------
2701 ;; aaa (1 . 4) (1 . -3)
2702 ;; aaba (3 . 4) N/A (in region)
2703 ;; ccaaba (1 . 3) (1 . -2)
2704 ;; ccaabaddd (7 . 10) (7 . -3)
2705 ;; ccaabdd ("ad" . 6) (6 . 2)
2706 ;; ccaabaddd (6 . 8) (6 . -2)
2707 ;; | |<-- region: "caab", from 2 to 6
2709 ;; When the user starts a run of undos in region,
2710 ;; undo-make-selective-list is called to create the full list of in
2711 ;; region elements. Each element is adjusted forward chronologically
2712 ;; through undo-deltas to determine if it is in the region.
2714 ;; In the above example, the insertion of "b" is (3 . 4) in the
2715 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2716 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2717 ;; . 6) is assessed as in the region and placed in the selective list.
2718 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2719 ;; due to the selected element. The "b" insertion is the only element
2720 ;; fully in the region, so in this example undo-make-selective-list
2721 ;; returns (nil (5 . 6)).
2723 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2724 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2725 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2726 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2727 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2729 ;; More interesting is how to adjust the "ddd" insertion due to the
2730 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2731 ;; If the reinsertion was a manual retyping of "ad", then the total
2732 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2733 ;; the reinsertion was due to undo, one might expect the first "d"
2734 ;; character would again be a part of the "ddd" text, meaning its
2735 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2737 ;; undo-make-selective-list assumes in this situation that "ad" was a
2738 ;; new edit, even if it was inserted because of an undo.
2739 ;; Consequently, if the user undos in region "8 to 10" of the
2740 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2741 ;; "ccaabad", as though the first "d" became detached from the
2742 ;; original "ddd" insertion. This quirk is a FIXME.
2744 (defun undo-make-selective-list (start end)
2745 "Return a list of undo elements for the region START to END.
2746 The elements come from `buffer-undo-list', but we keep only the
2747 elements inside this region, and discard those outside this
2748 region. The elements' positions are adjusted so as the returned
2749 list can be applied to the current buffer."
2750 (let ((ulist buffer-undo-list)
2751 ;; A list of position adjusted undo elements in the region.
2752 (selective-list (list nil))
2753 ;; A list of undo-deltas for out of region undo elements.
2754 undo-deltas
2755 undo-elt)
2756 (while ulist
2757 (when undo-no-redo
2758 (while (gethash ulist undo-equiv-table)
2759 (setq ulist (gethash ulist undo-equiv-table))))
2760 (setq undo-elt (car ulist))
2761 (cond
2762 ((null undo-elt)
2763 ;; Don't put two nils together in the list
2764 (when (car selective-list)
2765 (push nil selective-list)))
2766 ((and (consp undo-elt) (eq (car undo-elt) t))
2767 ;; This is a "was unmodified" element. Keep it
2768 ;; if we have kept everything thus far.
2769 (when (not undo-deltas)
2770 (push undo-elt selective-list)))
2771 ;; Skip over marker adjustments, instead relying
2772 ;; on finding them after (TEXT . POS) elements
2773 ((markerp (car-safe undo-elt))
2774 nil)
2776 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2777 undo-deltas)))
2778 (if (undo-elt-in-region adjusted-undo-elt start end)
2779 (progn
2780 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2781 (push adjusted-undo-elt selective-list)
2782 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2783 ;; kept. primitive-undo may discard them later.
2784 (when (and (stringp (car-safe adjusted-undo-elt))
2785 (integerp (cdr-safe adjusted-undo-elt)))
2786 (let ((list-i (cdr ulist)))
2787 (while (markerp (car-safe (car list-i)))
2788 (push (pop list-i) selective-list)))))
2789 (let ((delta (undo-delta undo-elt)))
2790 (when (/= 0 (cdr delta))
2791 (push delta undo-deltas)))))))
2792 (pop ulist))
2793 (nreverse selective-list)))
2795 (defun undo-elt-in-region (undo-elt start end)
2796 "Determine whether UNDO-ELT falls inside the region START ... END.
2797 If it crosses the edge, we return nil.
2799 Generally this function is not useful for determining
2800 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2801 because markers can be arbitrarily relocated. Instead, pass the
2802 marker adjustment's corresponding (TEXT . POS) element."
2803 (cond ((integerp undo-elt)
2804 (and (>= undo-elt start)
2805 (<= undo-elt end)))
2806 ((eq undo-elt nil)
2808 ((atom undo-elt)
2809 nil)
2810 ((stringp (car undo-elt))
2811 ;; (TEXT . POSITION)
2812 (and (>= (abs (cdr undo-elt)) start)
2813 (<= (abs (cdr undo-elt)) end)))
2814 ((and (consp undo-elt) (markerp (car undo-elt)))
2815 ;; (MARKER . ADJUSTMENT)
2816 (<= start (car undo-elt) end))
2817 ((null (car undo-elt))
2818 ;; (nil PROPERTY VALUE BEG . END)
2819 (let ((tail (nthcdr 3 undo-elt)))
2820 (and (>= (car tail) start)
2821 (<= (cdr tail) end))))
2822 ((integerp (car undo-elt))
2823 ;; (BEGIN . END)
2824 (and (>= (car undo-elt) start)
2825 (<= (cdr undo-elt) end)))))
2827 (defun undo-elt-crosses-region (undo-elt start end)
2828 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2829 This assumes we have already decided that UNDO-ELT
2830 is not *inside* the region START...END."
2831 (declare (obsolete nil "25.1"))
2832 (cond ((atom undo-elt) nil)
2833 ((null (car undo-elt))
2834 ;; (nil PROPERTY VALUE BEG . END)
2835 (let ((tail (nthcdr 3 undo-elt)))
2836 (and (< (car tail) end)
2837 (> (cdr tail) start))))
2838 ((integerp (car undo-elt))
2839 ;; (BEGIN . END)
2840 (and (< (car undo-elt) end)
2841 (> (cdr undo-elt) start)))))
2843 (defun undo-adjust-elt (elt deltas)
2844 "Return adjustment of undo element ELT by the undo DELTAS
2845 list."
2846 (pcase elt
2847 ;; POSITION
2848 ((pred integerp)
2849 (undo-adjust-pos elt deltas))
2850 ;; (BEG . END)
2851 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2852 (undo-adjust-beg-end beg end deltas))
2853 ;; (TEXT . POSITION)
2854 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2855 (cons text (* (if (< pos 0) -1 1)
2856 (undo-adjust-pos (abs pos) deltas))))
2857 ;; (nil PROPERTY VALUE BEG . END)
2858 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2859 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2860 ;; (apply DELTA START END FUN . ARGS)
2861 ;; FIXME
2862 ;; All others return same elt
2863 (_ elt)))
2865 ;; (BEG . END) can adjust to the same positions, commonly when an
2866 ;; insertion was undone and they are out of region, for example:
2868 ;; buf pos:
2869 ;; 123456789 buffer-undo-list undo-deltas
2870 ;; --------- ---------------- -----------
2871 ;; [...]
2872 ;; abbaa (2 . 4) (2 . -2)
2873 ;; aaa ("bb" . 2) (2 . 2)
2874 ;; [...]
2876 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2877 ;; undo. Further adjustments to such an element should be the same as
2878 ;; for (TEXT . POSITION) elements. The options are:
2880 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2881 ;; analogous to marker insertion-type t.
2883 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2884 ;; marker insertion-type nil.
2886 ;; There was no strong reason to prefer one or the other, except that
2887 ;; the first is more consistent with prior undo in region behavior.
2888 (defun undo-adjust-beg-end (beg end deltas)
2889 "Return cons of adjustments to BEG and END by the undo DELTAS
2890 list."
2891 (let ((adj-beg (undo-adjust-pos beg deltas)))
2892 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2893 (cons adj-beg
2894 (max adj-beg (undo-adjust-pos end deltas t)))))
2896 (defun undo-adjust-pos (pos deltas &optional use-<)
2897 "Return adjustment of POS by the undo DELTAS list, comparing
2898 with < or <= based on USE-<."
2899 (dolist (d deltas pos)
2900 (when (if use-<
2901 (< (car d) pos)
2902 (<= (car d) pos))
2903 (setq pos
2904 ;; Don't allow pos to become less than the undo-delta
2905 ;; position. This edge case is described in the overview
2906 ;; comments.
2907 (max (car d) (- pos (cdr d)))))))
2909 ;; Return the first affected buffer position and the delta for an undo element
2910 ;; delta is defined as the change in subsequent buffer positions if we *did*
2911 ;; the undo.
2912 (defun undo-delta (undo-elt)
2913 (if (consp undo-elt)
2914 (cond ((stringp (car undo-elt))
2915 ;; (TEXT . POSITION)
2916 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2917 ((integerp (car undo-elt))
2918 ;; (BEGIN . END)
2919 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2921 '(0 . 0)))
2922 '(0 . 0)))
2924 ;;; Default undo-boundary addition
2926 ;; This section adds a new undo-boundary at either after a command is
2927 ;; called or in some cases on a timer called after a change is made in
2928 ;; any buffer.
2929 (defvar-local undo-auto--last-boundary-cause nil
2930 "Describe the cause of the last undo-boundary.
2932 If `explicit', the last boundary was caused by an explicit call to
2933 `undo-boundary', that is one not called by the code in this
2934 section.
2936 If it is equal to `timer', then the last boundary was inserted
2937 by `undo-auto--boundary-timer'.
2939 If it is equal to `command', then the last boundary was inserted
2940 automatically after a command, that is by the code defined in
2941 this section.
2943 If it is equal to a list, then the last boundary was inserted by
2944 an amalgamating command. The car of the list is the number of
2945 times an amalgamating command has been called, and the cdr are the
2946 buffers that were changed during the last command.")
2948 (defvar undo-auto-current-boundary-timer nil
2949 "Current timer which will run `undo-auto--boundary-timer' or nil.
2951 If set to non-nil, this will effectively disable the timer.")
2953 (defvar undo-auto--this-command-amalgamating nil
2954 "Non-nil if `this-command' should be amalgamated.
2955 This variable is set to nil by `undo-auto--boundaries' and is set
2956 by `undo-auto-amalgamate'." )
2958 (defun undo-auto--needs-boundary-p ()
2959 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2960 (car-safe buffer-undo-list))
2962 (defun undo-auto--last-boundary-amalgamating-number ()
2963 "Return the number of amalgamating last commands or nil.
2964 Amalgamating commands are, by default, either
2965 `self-insert-command' and `delete-char', but can be any command
2966 that calls `undo-auto-amalgamate'."
2967 (car-safe undo-auto--last-boundary-cause))
2969 (defun undo-auto--ensure-boundary (cause)
2970 "Add an `undo-boundary' to the current buffer if needed.
2971 REASON describes the reason that the boundary is being added; see
2972 `undo-auto--last-boundary' for more information."
2973 (when (and
2974 (undo-auto--needs-boundary-p))
2975 (let ((last-amalgamating
2976 (undo-auto--last-boundary-amalgamating-number)))
2977 (undo-boundary)
2978 (setq undo-auto--last-boundary-cause
2979 (if (eq 'amalgamate cause)
2980 (cons
2981 (if last-amalgamating (1+ last-amalgamating) 0)
2982 undo-auto--undoably-changed-buffers)
2983 cause)))))
2985 (defun undo-auto--boundaries (cause)
2986 "Check recently changed buffers and add a boundary if necessary.
2987 REASON describes the reason that the boundary is being added; see
2988 `undo-last-boundary' for more information."
2989 ;; (Bug #23785) All commands should ensure that there is an undo
2990 ;; boundary whether they have changed the current buffer or not.
2991 (when (eq cause 'command)
2992 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2993 (dolist (b undo-auto--undoably-changed-buffers)
2994 (when (buffer-live-p b)
2995 (with-current-buffer b
2996 (undo-auto--ensure-boundary cause))))
2997 (setq undo-auto--undoably-changed-buffers nil))
2999 (defun undo-auto--boundary-timer ()
3000 "Timer which will run `undo--auto-boundary-timer'."
3001 (setq undo-auto-current-boundary-timer nil)
3002 (undo-auto--boundaries 'timer))
3004 (defun undo-auto--boundary-ensure-timer ()
3005 "Ensure that the `undo-auto-boundary-timer' is set."
3006 (unless undo-auto-current-boundary-timer
3007 (setq undo-auto-current-boundary-timer
3008 (run-at-time 10 nil #'undo-auto--boundary-timer))))
3010 (defvar undo-auto--undoably-changed-buffers nil
3011 "List of buffers that have changed recently.
3013 This list is maintained by `undo-auto--undoable-change' and
3014 `undo-auto--boundaries' and can be affected by changes to their
3015 default values.")
3017 (defun undo-auto--add-boundary ()
3018 "Add an `undo-boundary' in appropriate buffers."
3019 (undo-auto--boundaries
3020 (let ((amal undo-auto--this-command-amalgamating))
3021 (setq undo-auto--this-command-amalgamating nil)
3022 (if amal
3023 'amalgamate
3024 'command))))
3026 (defun undo-auto-amalgamate ()
3027 "Amalgamate undo if necessary.
3028 This function can be called before an amalgamating command. It
3029 removes the previous `undo-boundary' if a series of such calls
3030 have been made. By default `self-insert-command' and
3031 `delete-char' are the only amalgamating commands, although this
3032 function could be called by any command wishing to have this
3033 behavior."
3034 (let ((last-amalgamating-count
3035 (undo-auto--last-boundary-amalgamating-number)))
3036 (setq undo-auto--this-command-amalgamating t)
3037 (when
3038 last-amalgamating-count
3040 (and
3041 (< last-amalgamating-count 20)
3042 (eq this-command last-command))
3043 ;; Amalgamate all buffers that have changed.
3044 (dolist (b (cdr undo-auto--last-boundary-cause))
3045 (when (buffer-live-p b)
3046 (with-current-buffer
3048 (when
3049 ;; The head of `buffer-undo-list' is nil.
3050 ;; `car-safe' doesn't work because
3051 ;; `buffer-undo-list' need not be a list!
3052 (and (listp buffer-undo-list)
3053 (not (car buffer-undo-list)))
3054 (setq buffer-undo-list
3055 (cdr buffer-undo-list))))))
3056 (setq undo-auto--last-boundary-cause 0)))))
3058 (defun undo-auto--undoable-change ()
3059 "Called after every undoable buffer change."
3060 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
3061 (undo-auto--boundary-ensure-timer))
3062 ;; End auto-boundary section
3064 (defun undo-amalgamate-change-group (handle)
3065 "Amalgamate changes in change-group since HANDLE.
3066 Remove all undo boundaries between the state of HANDLE and now.
3067 HANDLE is as returned by `prepare-change-group'."
3068 (dolist (elt handle)
3069 (with-current-buffer (car elt)
3070 (setq elt (cdr elt))
3071 (when (consp buffer-undo-list)
3072 (let ((old-car (car-safe elt))
3073 (old-cdr (cdr-safe elt)))
3074 (unwind-protect
3075 (progn
3076 ;; Temporarily truncate the undo log at ELT.
3077 (when (consp elt)
3078 (setcar elt t) (setcdr elt nil))
3079 (when
3080 (or (null elt) ;The undo-log was empty.
3081 ;; `elt' is still in the log: normal case.
3082 (eq elt (last buffer-undo-list))
3083 ;; `elt' is not in the log any more, but that's because
3084 ;; the log is "all new", so we should remove all
3085 ;; boundaries from it.
3086 (not (eq (last buffer-undo-list) (last old-cdr))))
3087 (cl-callf (lambda (x) (delq nil x))
3088 (if (car buffer-undo-list)
3089 buffer-undo-list
3090 ;; Preserve the undo-boundaries at either ends of the
3091 ;; change-groups.
3092 (cdr buffer-undo-list)))))
3093 ;; Reset the modified cons cell ELT to its original content.
3094 (when (consp elt)
3095 (setcar elt old-car)
3096 (setcdr elt old-cdr))))))))
3099 (defcustom undo-ask-before-discard nil
3100 "If non-nil ask about discarding undo info for the current command.
3101 Normally, Emacs discards the undo info for the current command if
3102 it exceeds `undo-outer-limit'. But if you set this option
3103 non-nil, it asks in the echo area whether to discard the info.
3104 If you answer no, there is a slight risk that Emacs might crash, so
3105 only do it if you really want to undo the command.
3107 This option is mainly intended for debugging. You have to be
3108 careful if you use it for other purposes. Garbage collection is
3109 inhibited while the question is asked, meaning that Emacs might
3110 leak memory. So you should make sure that you do not wait
3111 excessively long before answering the question."
3112 :type 'boolean
3113 :group 'undo
3114 :version "22.1")
3116 (defvar undo-extra-outer-limit nil
3117 "If non-nil, an extra level of size that's ok in an undo item.
3118 We don't ask the user about truncating the undo list until the
3119 current item gets bigger than this amount.
3121 This variable only matters if `undo-ask-before-discard' is non-nil.")
3122 (make-variable-buffer-local 'undo-extra-outer-limit)
3124 ;; When the first undo batch in an undo list is longer than
3125 ;; undo-outer-limit, this function gets called to warn the user that
3126 ;; the undo info for the current command was discarded. Garbage
3127 ;; collection is inhibited around the call, so it had better not do a
3128 ;; lot of consing.
3129 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3130 (defun undo-outer-limit-truncate (size)
3131 (if undo-ask-before-discard
3132 (when (or (null undo-extra-outer-limit)
3133 (> size undo-extra-outer-limit))
3134 ;; Don't ask the question again unless it gets even bigger.
3135 ;; This applies, in particular, if the user quits from the question.
3136 ;; Such a quit quits out of GC, but something else will call GC
3137 ;; again momentarily. It will call this function again,
3138 ;; but we don't want to ask the question again.
3139 (setq undo-extra-outer-limit (+ size 50000))
3140 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3141 (yes-or-no-p (format-message
3142 "Buffer `%s' undo info is %d bytes long; discard it? "
3143 (buffer-name) size)))
3144 (progn (setq buffer-undo-list nil)
3145 (setq undo-extra-outer-limit nil)
3147 nil))
3148 (display-warning '(undo discard-info)
3149 (concat
3150 (format-message
3151 "Buffer `%s' undo info was %d bytes long.\n"
3152 (buffer-name) size)
3153 "The undo info was discarded because it exceeded \
3154 `undo-outer-limit'.
3156 This is normal if you executed a command that made a huge change
3157 to the buffer. In that case, to prevent similar problems in the
3158 future, set `undo-outer-limit' to a value that is large enough to
3159 cover the maximum size of normal changes you expect a single
3160 command to make, but not so large that it might exceed the
3161 maximum memory allotted to Emacs.
3163 If you did not execute any such command, the situation is
3164 probably due to a bug and you should report it.
3166 You can disable the popping up of this buffer by adding the entry
3167 \(undo discard-info) to the user option `warning-suppress-types',
3168 which is defined in the `warnings' library.\n")
3169 :warning)
3170 (setq buffer-undo-list nil)
3173 (defcustom password-word-equivalents
3174 '("password" "passcode" "passphrase" "pass phrase"
3175 ; These are sorted according to the GNU en_US locale.
3176 "암호" ; ko
3177 "パスワード" ; ja
3178 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3179 "ពាក្យសម្ងាត់" ; km
3180 "adgangskode" ; da
3181 "contraseña" ; es
3182 "contrasenya" ; ca
3183 "geslo" ; sl
3184 "hasło" ; pl
3185 "heslo" ; cs, sk
3186 "iphasiwedi" ; zu
3187 "jelszó" ; hu
3188 "lösenord" ; sv
3189 "lozinka" ; hr, sr
3190 "mật khẩu" ; vi
3191 "mot de passe" ; fr
3192 "parola" ; tr
3193 "pasahitza" ; eu
3194 "passord" ; nb
3195 "passwort" ; de
3196 "pasvorto" ; eo
3197 "salasana" ; fi
3198 "senha" ; pt
3199 "slaptažodis" ; lt
3200 "wachtwoord" ; nl
3201 "كلمة السر" ; ar
3202 "ססמה" ; he
3203 "лозинка" ; sr
3204 "пароль" ; kk, ru, uk
3205 "गुप्तशब्द" ; mr
3206 "शब्दकूट" ; hi
3207 "પાસવર્ડ" ; gu
3208 "సంకేతపదము" ; te
3209 "ਪਾਸਵਰਡ" ; pa
3210 "ಗುಪ್ತಪದ" ; kn
3211 "கடவுச்சொல்" ; ta
3212 "അടയാളവാക്ക്" ; ml
3213 "গুপ্তশব্দ" ; as
3214 "পাসওয়ার্ড" ; bn_IN
3215 "රහස්පදය" ; si
3216 "密码" ; zh_CN
3217 "密碼" ; zh_TW
3219 "List of words equivalent to \"password\".
3220 This is used by Shell mode and other parts of Emacs to recognize
3221 password prompts, including prompts in languages other than
3222 English. Different case choices should not be assumed to be
3223 included; callers should bind `case-fold-search' to t."
3224 :type '(repeat string)
3225 :version "24.4"
3226 :group 'processes)
3228 (defvar shell-command-history nil
3229 "History list for some commands that read shell commands.
3231 Maximum length of the history list is determined by the value
3232 of `history-length', which see.")
3234 (defvar shell-command-switch (purecopy "-c")
3235 "Switch used to have the shell execute its command line argument.")
3237 (defvar shell-command-default-error-buffer nil
3238 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3239 This buffer is used when `shell-command' or `shell-command-on-region'
3240 is run interactively. A value of nil means that output to stderr and
3241 stdout will be intermixed in the output stream.")
3243 (declare-function mailcap-file-default-commands "mailcap" (files))
3244 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3246 (defun minibuffer-default-add-shell-commands ()
3247 "Return a list of all commands associated with the current file.
3248 This function is used to add all related commands retrieved by `mailcap'
3249 to the end of the list of defaults just after the default value."
3250 (interactive)
3251 (let* ((filename (if (listp minibuffer-default)
3252 (car minibuffer-default)
3253 minibuffer-default))
3254 (commands (and filename (require 'mailcap nil t)
3255 (mailcap-file-default-commands (list filename)))))
3256 (setq commands (mapcar (lambda (command)
3257 (concat command " " filename))
3258 commands))
3259 (if (listp minibuffer-default)
3260 (append minibuffer-default commands)
3261 (cons minibuffer-default commands))))
3263 (declare-function shell-completion-vars "shell" ())
3265 (defvar minibuffer-local-shell-command-map
3266 (let ((map (make-sparse-keymap)))
3267 (set-keymap-parent map minibuffer-local-map)
3268 (define-key map "\t" 'completion-at-point)
3269 map)
3270 "Keymap used for completing shell commands in minibuffer.")
3272 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3273 "Read a shell command from the minibuffer.
3274 The arguments are the same as the ones of `read-from-minibuffer',
3275 except READ and KEYMAP are missing and HIST defaults
3276 to `shell-command-history'."
3277 (require 'shell)
3278 (minibuffer-with-setup-hook
3279 (lambda ()
3280 (shell-completion-vars)
3281 (set (make-local-variable 'minibuffer-default-add-function)
3282 'minibuffer-default-add-shell-commands))
3283 (apply 'read-from-minibuffer prompt initial-contents
3284 minibuffer-local-shell-command-map
3286 (or hist 'shell-command-history)
3287 args)))
3289 (defcustom async-shell-command-buffer 'confirm-new-buffer
3290 "What to do when the output buffer is used by another shell command.
3291 This option specifies how to resolve the conflict where a new command
3292 wants to direct its output to the buffer `*Async Shell Command*',
3293 but this buffer is already taken by another running shell command.
3295 The value `confirm-kill-process' is used to ask for confirmation before
3296 killing the already running process and running a new process
3297 in the same buffer, `confirm-new-buffer' for confirmation before running
3298 the command in a new buffer with a name other than the default buffer name,
3299 `new-buffer' for doing the same without confirmation,
3300 `confirm-rename-buffer' for confirmation before renaming the existing
3301 output buffer and running a new command in the default buffer,
3302 `rename-buffer' for doing the same without confirmation."
3303 :type '(choice (const :tag "Confirm killing of running command"
3304 confirm-kill-process)
3305 (const :tag "Confirm creation of a new buffer"
3306 confirm-new-buffer)
3307 (const :tag "Create a new buffer"
3308 new-buffer)
3309 (const :tag "Confirm renaming of existing buffer"
3310 confirm-rename-buffer)
3311 (const :tag "Rename the existing buffer"
3312 rename-buffer))
3313 :group 'shell
3314 :version "24.3")
3316 (defcustom async-shell-command-display-buffer t
3317 "Whether to display the command buffer immediately.
3318 If t, display the buffer immediately; if nil, wait until there
3319 is output."
3320 :type '(choice (const :tag "Display buffer immediately"
3322 (const :tag "Display buffer on output"
3323 nil))
3324 :group 'shell
3325 :version "26.1")
3327 (defcustom shell-command-dont-erase-buffer nil
3328 "If non-nil, output buffer is not erased between shell commands.
3329 Also, a non-nil value sets the point in the output buffer
3330 once the command completes.
3331 The value `beg-last-out' sets point at the beginning of the output,
3332 `end-last-out' sets point at the end of the buffer, `save-point'
3333 restores the buffer position before the command."
3334 :type '(choice
3335 (const :tag "Erase buffer" nil)
3336 (const :tag "Set point to beginning of last output" beg-last-out)
3337 (const :tag "Set point to end of last output" end-last-out)
3338 (const :tag "Save point" save-point))
3339 :group 'shell
3340 :version "26.1")
3342 (defvar shell-command-saved-pos nil
3343 "Record of point positions in output buffers after command completion.
3344 The value is an alist whose elements are of the form (BUFFER . POS),
3345 where BUFFER is the output buffer, and POS is the point position
3346 in BUFFER once the command finishes.
3347 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
3349 (defun shell-command--save-pos-or-erase ()
3350 "Store a buffer position or erase the buffer.
3351 See `shell-command-dont-erase-buffer'."
3352 (let ((sym shell-command-dont-erase-buffer)
3353 pos)
3354 (setq buffer-read-only nil)
3355 ;; Setting buffer-read-only to nil doesn't suffice
3356 ;; if some text has a non-nil read-only property,
3357 ;; which comint sometimes adds for prompts.
3358 (setq pos
3359 (cond ((eq sym 'save-point) (point))
3360 ((eq sym 'beg-last-out) (point-max))
3361 ((not sym)
3362 (let ((inhibit-read-only t))
3363 (erase-buffer) nil))))
3364 (when pos
3365 (goto-char (point-max))
3366 (push (cons (current-buffer) pos)
3367 shell-command-saved-pos))))
3369 (defun shell-command--set-point-after-cmd (&optional buffer)
3370 "Set point in BUFFER after command complete.
3371 BUFFER is the output buffer of the command; if nil, then defaults
3372 to the current BUFFER.
3373 Set point to the `cdr' of the element in `shell-command-saved-pos'
3374 whose `car' is BUFFER."
3375 (when shell-command-dont-erase-buffer
3376 (let* ((sym shell-command-dont-erase-buffer)
3377 (buf (or buffer (current-buffer)))
3378 (pos (alist-get buf shell-command-saved-pos)))
3379 (setq shell-command-saved-pos
3380 (assq-delete-all buf shell-command-saved-pos))
3381 (when (buffer-live-p buf)
3382 (let ((win (car (get-buffer-window-list buf)))
3383 (pmax (with-current-buffer buf (point-max))))
3384 (unless (and pos (memq sym '(save-point beg-last-out)))
3385 (setq pos pmax))
3386 ;; Set point in the window displaying buf, if any; otherwise
3387 ;; display buf temporary in selected frame and set the point.
3388 (if win
3389 (set-window-point win pos)
3390 (save-window-excursion
3391 (let ((win (display-buffer
3393 '(nil (inhibit-switch-frame . t)))))
3394 (set-window-point win pos)))))))))
3396 (defun async-shell-command (command &optional output-buffer error-buffer)
3397 "Execute string COMMAND asynchronously in background.
3399 Like `shell-command', but adds `&' at the end of COMMAND
3400 to execute it asynchronously.
3402 The output appears in the buffer `*Async Shell Command*'.
3403 That buffer is in shell mode.
3405 You can configure `async-shell-command-buffer' to specify what to do
3406 when the `*Async Shell Command*' buffer is already taken by another
3407 running shell command. To run COMMAND without displaying the output
3408 in a window you can configure `display-buffer-alist' to use the action
3409 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3411 In Elisp, you will often be better served by calling `start-process'
3412 directly, since it offers more control and does not impose the use of
3413 a shell (with its need to quote arguments)."
3414 (interactive
3415 (list
3416 (read-shell-command "Async shell command: " nil nil
3417 (let ((filename
3418 (cond
3419 (buffer-file-name)
3420 ((eq major-mode 'dired-mode)
3421 (dired-get-filename nil t)))))
3422 (and filename (file-relative-name filename))))
3423 current-prefix-arg
3424 shell-command-default-error-buffer))
3425 (unless (string-match "&[ \t]*\\'" command)
3426 (setq command (concat command " &")))
3427 (shell-command command output-buffer error-buffer))
3429 (defun shell-command (command &optional output-buffer error-buffer)
3430 "Execute string COMMAND in inferior shell; display output, if any.
3431 With prefix argument, insert the COMMAND's output at point.
3433 Interactively, prompt for COMMAND in the minibuffer.
3435 If COMMAND ends in `&', execute it asynchronously.
3436 The output appears in the buffer `*Async Shell Command*'.
3437 That buffer is in shell mode. You can also use
3438 `async-shell-command' that automatically adds `&'.
3440 Otherwise, COMMAND is executed synchronously. The output appears in
3441 the buffer `*Shell Command Output*'. If the output is short enough to
3442 display in the echo area (which is determined by the variables
3443 `resize-mini-windows' and `max-mini-window-height'), it is shown
3444 there, but it is nonetheless available in buffer `*Shell Command
3445 Output*' even though that buffer is not automatically displayed.
3447 To specify a coding system for converting non-ASCII characters
3448 in the shell command output, use \\[universal-coding-system-argument] \
3449 before this command.
3451 Noninteractive callers can specify coding systems by binding
3452 `coding-system-for-read' and `coding-system-for-write'.
3454 The optional second argument OUTPUT-BUFFER, if non-nil,
3455 says to put the output in some other buffer.
3456 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3457 and insert the output there; a non-nil value of
3458 `shell-command-dont-erase-buffer' prevents the buffer from being
3459 erased. If OUTPUT-BUFFER is not a buffer and not nil, insert the
3460 output in current buffer after point leaving mark after it. This
3461 cannot be done asynchronously.
3463 If the command terminates without error, but generates output,
3464 and you did not specify \"insert it in the current buffer\",
3465 the output can be displayed in the echo area or in its buffer.
3466 If the output is short enough to display in the echo area
3467 \(determined by the variable `max-mini-window-height' if
3468 `resize-mini-windows' is non-nil), it is shown there.
3469 Otherwise, the buffer containing the output is displayed.
3471 If there is output and an error, and you did not specify \"insert it
3472 in the current buffer\", a message about the error goes at the end
3473 of the output.
3475 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3476 or buffer name to which to direct the command's standard error output.
3477 If it is nil, error output is mingled with regular output.
3478 In an interactive call, the variable `shell-command-default-error-buffer'
3479 specifies the value of ERROR-BUFFER.
3481 In Elisp, you will often be better served by calling `call-process' or
3482 `start-process' directly, since they offer more control and do not
3483 impose the use of a shell (with its need to quote arguments)."
3485 (interactive
3486 (list
3487 (read-shell-command "Shell command: " nil nil
3488 (let ((filename
3489 (cond
3490 (buffer-file-name)
3491 ((eq major-mode 'dired-mode)
3492 (dired-get-filename nil t)))))
3493 (and filename (file-relative-name filename))))
3494 current-prefix-arg
3495 shell-command-default-error-buffer))
3496 ;; Look for a handler in case default-directory is a remote file name.
3497 (let ((handler
3498 (find-file-name-handler (directory-file-name default-directory)
3499 'shell-command)))
3500 (if handler
3501 (funcall handler 'shell-command command output-buffer error-buffer)
3502 (if (and output-buffer
3503 (not (or (bufferp output-buffer) (stringp output-buffer))))
3504 ;; Output goes in current buffer.
3505 (let ((error-file
3506 (if error-buffer
3507 (make-temp-file
3508 (expand-file-name "scor"
3509 (or small-temporary-file-directory
3510 temporary-file-directory)))
3511 nil)))
3512 (barf-if-buffer-read-only)
3513 (push-mark nil t)
3514 ;; We do not use -f for csh; we will not support broken use of
3515 ;; .cshrcs. Even the BSD csh manual says to use
3516 ;; "if ($?prompt) exit" before things which are not useful
3517 ;; non-interactively. Besides, if someone wants their other
3518 ;; aliases for shell commands then they can still have them.
3519 (call-process shell-file-name nil
3520 (if error-file
3521 (list t error-file)
3523 nil shell-command-switch command)
3524 (when (and error-file (file-exists-p error-file))
3525 (if (< 0 (nth 7 (file-attributes error-file)))
3526 (with-current-buffer (get-buffer-create error-buffer)
3527 (let ((pos-from-end (- (point-max) (point))))
3528 (or (bobp)
3529 (insert "\f\n"))
3530 ;; Do no formatting while reading error file,
3531 ;; because that can run a shell command, and we
3532 ;; don't want that to cause an infinite recursion.
3533 (format-insert-file error-file nil)
3534 ;; Put point after the inserted errors.
3535 (goto-char (- (point-max) pos-from-end)))
3536 (display-buffer (current-buffer))))
3537 (delete-file error-file))
3538 ;; This is like exchange-point-and-mark, but doesn't
3539 ;; activate the mark. It is cleaner to avoid activation,
3540 ;; even though the command loop would deactivate the mark
3541 ;; because we inserted text.
3542 (goto-char (prog1 (mark t)
3543 (set-marker (mark-marker) (point)
3544 (current-buffer)))))
3545 ;; Output goes in a separate buffer.
3546 ;; Preserve the match data in case called from a program.
3547 ;; FIXME: It'd be ridiculous for an Elisp function to call
3548 ;; shell-command and assume that it won't mess the match-data!
3549 (save-match-data
3550 (if (string-match "[ \t]*&[ \t]*\\'" command)
3551 ;; Command ending with ampersand means asynchronous.
3552 (let* ((buffer (get-buffer-create
3553 (or output-buffer "*Async Shell Command*")))
3554 (bname (buffer-name buffer))
3555 (directory default-directory)
3556 proc)
3557 ;; Remove the ampersand.
3558 (setq command (substring command 0 (match-beginning 0)))
3559 ;; Ask the user what to do with already running process.
3560 (setq proc (get-buffer-process buffer))
3561 (when proc
3562 (cond
3563 ((eq async-shell-command-buffer 'confirm-kill-process)
3564 ;; If will kill a process, query first.
3565 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3566 (kill-process proc)
3567 (error "Shell command in progress")))
3568 ((eq async-shell-command-buffer 'confirm-new-buffer)
3569 ;; If will create a new buffer, query first.
3570 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3571 (setq buffer (generate-new-buffer bname))
3572 (error "Shell command in progress")))
3573 ((eq async-shell-command-buffer 'new-buffer)
3574 ;; It will create a new buffer.
3575 (setq buffer (generate-new-buffer bname)))
3576 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3577 ;; If will rename the buffer, query first.
3578 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3579 (progn
3580 (with-current-buffer buffer
3581 (rename-uniquely))
3582 (setq buffer (get-buffer-create bname)))
3583 (error "Shell command in progress")))
3584 ((eq async-shell-command-buffer 'rename-buffer)
3585 ;; It will rename the buffer.
3586 (with-current-buffer buffer
3587 (rename-uniquely))
3588 (setq buffer (get-buffer-create bname)))))
3589 (with-current-buffer buffer
3590 (shell-command--save-pos-or-erase)
3591 (setq default-directory directory)
3592 (setq proc (start-process "Shell" buffer shell-file-name
3593 shell-command-switch command))
3594 (setq mode-line-process '(":%s"))
3595 (require 'shell) (shell-mode)
3596 (set-process-sentinel proc 'shell-command-sentinel)
3597 ;; Use the comint filter for proper handling of
3598 ;; carriage motion (see comint-inhibit-carriage-motion).
3599 (set-process-filter proc 'comint-output-filter)
3600 (if async-shell-command-display-buffer
3601 ;; Display buffer immediately.
3602 (display-buffer buffer '(nil (allow-no-window . t)))
3603 ;; Defer displaying buffer until first process output.
3604 ;; Use disposable named advice so that the buffer is
3605 ;; displayed at most once per process lifetime.
3606 (let ((nonce (make-symbol "nonce")))
3607 (add-function :before (process-filter proc)
3608 (lambda (proc _string)
3609 (let ((buf (process-buffer proc)))
3610 (when (buffer-live-p buf)
3611 (remove-function (process-filter proc)
3612 nonce)
3613 (display-buffer buf))))
3614 `((name . ,nonce)))))))
3615 ;; Otherwise, command is executed synchronously.
3616 (shell-command-on-region (point) (point) command
3617 output-buffer nil error-buffer)))))))
3619 (defun display-message-or-buffer (message &optional buffer-name action frame)
3620 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3621 MESSAGE may be either a string or a buffer.
3623 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3624 for maximum height of the echo area, as defined by `max-mini-window-height'
3625 if `resize-mini-windows' is non-nil.
3627 Returns either the string shown in the echo area, or when a pop-up
3628 buffer is used, the window used to display it.
3630 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3631 name of the buffer used to display it in the case where a pop-up buffer
3632 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3633 string and it is displayed in the echo area, it is not specified whether
3634 the contents are inserted into the buffer anyway.
3636 Optional arguments ACTION and FRAME are as for `display-buffer',
3637 and are only used if a pop-up buffer is displayed."
3638 (cond ((and (stringp message) (not (string-match "\n" message)))
3639 ;; Trivial case where we can use the echo area
3640 (message "%s" message))
3641 ((and (stringp message)
3642 (= (string-match "\n" message) (1- (length message))))
3643 ;; Trivial case where we can just remove single trailing newline
3644 (message "%s" (substring message 0 (1- (length message)))))
3646 ;; General case
3647 (with-current-buffer
3648 (if (bufferp message)
3649 message
3650 (get-buffer-create (or buffer-name "*Message*")))
3652 (unless (bufferp message)
3653 (erase-buffer)
3654 (insert message))
3656 (let ((lines
3657 (if (= (buffer-size) 0)
3659 (count-screen-lines nil nil nil (minibuffer-window)))))
3660 (cond ((= lines 0))
3661 ((and (or (<= lines 1)
3662 (<= lines
3663 (if resize-mini-windows
3664 (cond ((floatp max-mini-window-height)
3665 (* (frame-height)
3666 max-mini-window-height))
3667 ((integerp max-mini-window-height)
3668 max-mini-window-height)
3671 1)))
3672 ;; Don't use the echo area if the output buffer is
3673 ;; already displayed in the selected frame.
3674 (not (get-buffer-window (current-buffer))))
3675 ;; Echo area
3676 (goto-char (point-max))
3677 (when (bolp)
3678 (backward-char 1))
3679 (message "%s" (buffer-substring (point-min) (point))))
3681 ;; Buffer
3682 (goto-char (point-min))
3683 (display-buffer (current-buffer) action frame))))))))
3686 ;; We have a sentinel to prevent insertion of a termination message
3687 ;; in the buffer itself, and to set the point in the buffer when
3688 ;; `shell-command-dont-erase-buffer' is non-nil.
3689 (defun shell-command-sentinel (process signal)
3690 (when (memq (process-status process) '(exit signal))
3691 (shell-command--set-point-after-cmd (process-buffer process))
3692 (message "%s: %s."
3693 (car (cdr (cdr (process-command process))))
3694 (substring signal 0 -1))))
3696 (defun shell-command-on-region (start end command
3697 &optional output-buffer replace
3698 error-buffer display-error-buffer
3699 region-noncontiguous-p)
3700 "Execute string COMMAND in inferior shell with region as input.
3701 Normally display output (if any) in temp buffer `*Shell Command Output*';
3702 Prefix arg means replace the region with it. Return the exit code of
3703 COMMAND.
3705 To specify a coding system for converting non-ASCII characters
3706 in the input and output to the shell command, use \\[universal-coding-system-argument]
3707 before this command. By default, the input (from the current buffer)
3708 is encoded using coding-system specified by `process-coding-system-alist',
3709 falling back to `default-process-coding-system' if no match for COMMAND
3710 is found in `process-coding-system-alist'.
3712 Noninteractive callers can specify coding systems by binding
3713 `coding-system-for-read' and `coding-system-for-write'.
3715 If the command generates output, the output may be displayed
3716 in the echo area or in a buffer.
3717 If the output is short enough to display in the echo area
3718 \(determined by the variable `max-mini-window-height' if
3719 `resize-mini-windows' is non-nil), it is shown there.
3720 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3721 The output is available in that buffer in both cases.
3723 If there is output and an error, a message about the error
3724 appears at the end of the output.
3726 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3727 command's output. If the value is a buffer or buffer name,
3728 erase that buffer and insert the output there; a non-nil value of
3729 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3730 If the value is nil, use the buffer `*Shell Command Output*'.
3731 Any other non-nil value means to insert the output in the
3732 current buffer after START.
3734 Optional fifth arg REPLACE, if non-nil, means to insert the
3735 output in place of text from START to END, putting point and mark
3736 around it.
3738 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3739 or buffer name to which to direct the command's standard error
3740 output. If nil, error output is mingled with regular output.
3741 When called interactively, `shell-command-default-error-buffer'
3742 is used for ERROR-BUFFER.
3744 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3745 display the error buffer if there were any errors. When called
3746 interactively, this is t."
3747 (interactive (let (string)
3748 (unless (mark)
3749 (user-error "The mark is not set now, so there is no region"))
3750 ;; Do this before calling region-beginning
3751 ;; and region-end, in case subprocess output
3752 ;; relocates them while we are in the minibuffer.
3753 (setq string (read-shell-command "Shell command on region: "))
3754 ;; call-interactively recognizes region-beginning and
3755 ;; region-end specially, leaving them in the history.
3756 (list (region-beginning) (region-end)
3757 string
3758 current-prefix-arg
3759 current-prefix-arg
3760 shell-command-default-error-buffer
3762 (region-noncontiguous-p))))
3763 (let ((error-file
3764 (if error-buffer
3765 (make-temp-file
3766 (expand-file-name "scor"
3767 (or small-temporary-file-directory
3768 temporary-file-directory)))
3769 nil))
3770 exit-status)
3771 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3772 (if region-noncontiguous-p
3773 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3774 output)
3775 (with-temp-buffer
3776 (insert input)
3777 (call-process-region (point-min) (point-max)
3778 shell-file-name t t
3779 nil shell-command-switch
3780 command)
3781 (setq output (split-string (buffer-string) "\n")))
3782 (goto-char start)
3783 (funcall region-insert-function output))
3784 (if (or replace
3785 (and output-buffer
3786 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3787 ;; Replace specified region with output from command.
3788 (let ((swap (and replace (< start end))))
3789 ;; Don't muck with mark unless REPLACE says we should.
3790 (goto-char start)
3791 (and replace (push-mark (point) 'nomsg))
3792 (setq exit-status
3793 (call-shell-region start end command replace
3794 (if error-file
3795 (list t error-file)
3796 t)))
3797 ;; It is rude to delete a buffer which the command is not using.
3798 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3799 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3800 ;; (kill-buffer shell-buffer)))
3801 ;; Don't muck with mark unless REPLACE says we should.
3802 (and replace swap (exchange-point-and-mark)))
3803 ;; No prefix argument: put the output in a temp buffer,
3804 ;; replacing its entire contents.
3805 (let ((buffer (get-buffer-create
3806 (or output-buffer "*Shell Command Output*"))))
3807 (unwind-protect
3808 (if (and (eq buffer (current-buffer))
3809 (or (not shell-command-dont-erase-buffer)
3810 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3811 (not (region-active-p)))))
3812 ;; If the input is the same buffer as the output,
3813 ;; delete everything but the specified region,
3814 ;; then replace that region with the output.
3815 (progn (setq buffer-read-only nil)
3816 (delete-region (max start end) (point-max))
3817 (delete-region (point-min) (min start end))
3818 (setq exit-status
3819 (call-process-region (point-min) (point-max)
3820 shell-file-name t
3821 (if error-file
3822 (list t error-file)
3824 nil shell-command-switch
3825 command)))
3826 ;; Clear the output buffer, then run the command with
3827 ;; output there.
3828 (let ((directory default-directory))
3829 (with-current-buffer buffer
3830 (if (not output-buffer)
3831 (setq default-directory directory))
3832 (shell-command--save-pos-or-erase)))
3833 (setq exit-status
3834 (call-shell-region start end command nil
3835 (if error-file
3836 (list buffer error-file)
3837 buffer))))
3838 ;; Report the output.
3839 (with-current-buffer buffer
3840 (setq mode-line-process
3841 (cond ((null exit-status)
3842 " - Error")
3843 ((stringp exit-status)
3844 (format " - Signal [%s]" exit-status))
3845 ((not (equal 0 exit-status))
3846 (format " - Exit [%d]" exit-status)))))
3847 (if (with-current-buffer buffer (> (point-max) (point-min)))
3848 ;; There's some output, display it
3849 (progn
3850 (display-message-or-buffer buffer)
3851 (shell-command--set-point-after-cmd buffer))
3852 ;; No output; error?
3853 (let ((output
3854 (if (and error-file
3855 (< 0 (nth 7 (file-attributes error-file))))
3856 (format "some error output%s"
3857 (if shell-command-default-error-buffer
3858 (format " to the \"%s\" buffer"
3859 shell-command-default-error-buffer)
3860 ""))
3861 "no output")))
3862 (cond ((null exit-status)
3863 (message "(Shell command failed with error)"))
3864 ((equal 0 exit-status)
3865 (message "(Shell command succeeded with %s)"
3866 output))
3867 ((stringp exit-status)
3868 (message "(Shell command killed by signal %s)"
3869 exit-status))
3871 (message "(Shell command failed with code %d and %s)"
3872 exit-status output))))
3873 ;; Don't kill: there might be useful info in the undo-log.
3874 ;; (kill-buffer buffer)
3875 )))))
3877 (when (and error-file (file-exists-p error-file))
3878 (if (< 0 (nth 7 (file-attributes error-file)))
3879 (with-current-buffer (get-buffer-create error-buffer)
3880 (let ((pos-from-end (- (point-max) (point))))
3881 (or (bobp)
3882 (insert "\f\n"))
3883 ;; Do no formatting while reading error file,
3884 ;; because that can run a shell command, and we
3885 ;; don't want that to cause an infinite recursion.
3886 (format-insert-file error-file nil)
3887 ;; Put point after the inserted errors.
3888 (goto-char (- (point-max) pos-from-end)))
3889 (and display-error-buffer
3890 (display-buffer (current-buffer)))))
3891 (delete-file error-file))
3892 exit-status))
3894 (defun shell-command-to-string (command)
3895 "Execute shell command COMMAND and return its output as a string."
3896 (with-output-to-string
3897 (with-current-buffer
3898 standard-output
3899 (shell-command command t))))
3901 (defun process-file (program &optional infile buffer display &rest args)
3902 "Process files synchronously in a separate process.
3903 Similar to `call-process', but may invoke a file handler based on
3904 `default-directory'. The current working directory of the
3905 subprocess is `default-directory'.
3907 File names in INFILE and BUFFER are handled normally, but file
3908 names in ARGS should be relative to `default-directory', as they
3909 are passed to the process verbatim. (This is a difference to
3910 `call-process' which does not support file handlers for INFILE
3911 and BUFFER.)
3913 Some file handlers might not support all variants, for example
3914 they might behave as if DISPLAY was nil, regardless of the actual
3915 value passed."
3916 (let ((fh (find-file-name-handler default-directory 'process-file))
3917 lc stderr-file)
3918 (unwind-protect
3919 (if fh (apply fh 'process-file program infile buffer display args)
3920 (when infile (setq lc (file-local-copy infile)))
3921 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3922 (make-temp-file "emacs")))
3923 (prog1
3924 (apply 'call-process program
3925 (or lc infile)
3926 (if stderr-file (list (car buffer) stderr-file) buffer)
3927 display args)
3928 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3929 (when stderr-file (delete-file stderr-file))
3930 (when lc (delete-file lc)))))
3932 (defvar process-file-side-effects t
3933 "Whether a call of `process-file' changes remote files.
3935 By default, this variable is always set to t, meaning that a
3936 call of `process-file' could potentially change any file on a
3937 remote host. When set to nil, a file handler could optimize
3938 its behavior with respect to remote file attribute caching.
3940 You should only ever change this variable with a let-binding;
3941 never with `setq'.")
3943 (defun start-file-process (name buffer program &rest program-args)
3944 "Start a program in a subprocess. Return the process object for it.
3946 Similar to `start-process', but may invoke a file handler based on
3947 `default-directory'. See Info node `(elisp)Magic File Names'.
3949 This handler ought to run PROGRAM, perhaps on the local host,
3950 perhaps on a remote host that corresponds to `default-directory'.
3951 In the latter case, the local part of `default-directory' becomes
3952 the working directory of the process.
3954 PROGRAM and PROGRAM-ARGS might be file names. They are not
3955 objects of file handler invocation. File handlers might not
3956 support pty association, if PROGRAM is nil."
3957 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3958 (if fh (apply fh 'start-file-process name buffer program program-args)
3959 (apply 'start-process name buffer program program-args))))
3961 ;;;; Process menu
3963 (defvar tabulated-list-format)
3964 (defvar tabulated-list-entries)
3965 (defvar tabulated-list-sort-key)
3966 (declare-function tabulated-list-init-header "tabulated-list" ())
3967 (declare-function tabulated-list-print "tabulated-list"
3968 (&optional remember-pos update))
3970 (defvar process-menu-query-only nil)
3972 (defvar process-menu-mode-map
3973 (let ((map (make-sparse-keymap)))
3974 (define-key map [?d] 'process-menu-delete-process)
3975 map))
3977 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3978 "Major mode for listing the processes called by Emacs."
3979 (setq tabulated-list-format [("Process" 15 t)
3980 ("PID" 7 t)
3981 ("Status" 7 t)
3982 ;; 25 is the length of the long standard buffer
3983 ;; name "*Async Shell Command*<10>" (bug#30016)
3984 ("Buffer" 25 t)
3985 ("TTY" 12 t)
3986 ("Command" 0 t)])
3987 (make-local-variable 'process-menu-query-only)
3988 (setq tabulated-list-sort-key (cons "Process" nil))
3989 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t))
3991 (defun process-menu-delete-process ()
3992 "Kill process at point in a `list-processes' buffer."
3993 (interactive)
3994 (let ((pos (point)))
3995 (delete-process (tabulated-list-get-id))
3996 (revert-buffer)
3997 (goto-char (min pos (point-max)))
3998 (if (eobp)
3999 (forward-line -1)
4000 (beginning-of-line))))
4002 (defun list-processes--refresh ()
4003 "Recompute the list of processes for the Process List buffer.
4004 Also, delete any process that is exited or signaled."
4005 (setq tabulated-list-entries nil)
4006 (dolist (p (process-list))
4007 (cond ((memq (process-status p) '(exit signal closed))
4008 (delete-process p))
4009 ((or (not process-menu-query-only)
4010 (process-query-on-exit-flag p))
4011 (let* ((buf (process-buffer p))
4012 (type (process-type p))
4013 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
4014 (name (process-name p))
4015 (status (symbol-name (process-status p)))
4016 (buf-label (if (buffer-live-p buf)
4017 `(,(buffer-name buf)
4018 face link
4019 help-echo ,(format-message
4020 "Visit buffer `%s'"
4021 (buffer-name buf))
4022 follow-link t
4023 process-buffer ,buf
4024 action process-menu-visit-buffer)
4025 "--"))
4026 (tty (or (process-tty-name p) "--"))
4027 (cmd
4028 (if (memq type '(network serial))
4029 (let ((contact (process-contact p t)))
4030 (if (eq type 'network)
4031 (format "(%s %s)"
4032 (if (plist-get contact :type)
4033 "datagram"
4034 "network")
4035 (if (plist-get contact :server)
4036 (format "server on %s"
4038 (plist-get contact :host)
4039 (plist-get contact :local)))
4040 (format "connection to %s"
4041 (plist-get contact :host))))
4042 (format "(serial port %s%s)"
4043 (or (plist-get contact :port) "?")
4044 (let ((speed (plist-get contact :speed)))
4045 (if speed
4046 (format " at %s b/s" speed)
4047 "")))))
4048 (mapconcat 'identity (process-command p) " "))))
4049 (push (list p (vector name pid status buf-label tty cmd))
4050 tabulated-list-entries)))))
4051 (tabulated-list-init-header))
4053 (defun process-menu-visit-buffer (button)
4054 (display-buffer (button-get button 'process-buffer)))
4056 (defun list-processes (&optional query-only buffer)
4057 "Display a list of all processes that are Emacs sub-processes.
4058 If optional argument QUERY-ONLY is non-nil, only processes with
4059 the query-on-exit flag set are listed.
4060 Any process listed as exited or signaled is actually eliminated
4061 after the listing is made.
4062 Optional argument BUFFER specifies a buffer to use, instead of
4063 \"*Process List*\".
4064 The return value is always nil.
4066 This function lists only processes that were launched by Emacs. To
4067 see other processes running on the system, use `list-system-processes'."
4068 (interactive)
4069 (or (fboundp 'process-list)
4070 (error "Asynchronous subprocesses are not supported on this system"))
4071 (unless (bufferp buffer)
4072 (setq buffer (get-buffer-create "*Process List*")))
4073 (with-current-buffer buffer
4074 (process-menu-mode)
4075 (setq process-menu-query-only query-only)
4076 (list-processes--refresh)
4077 (tabulated-list-print))
4078 (display-buffer buffer)
4079 nil)
4081 ;;;; Prefix commands
4083 (setq prefix-command--needs-update nil)
4084 (setq prefix-command--last-echo nil)
4086 (defun internal-echo-keystrokes-prefix ()
4087 ;; BEWARE: Called directly from C code.
4088 ;; If the return value is non-nil, it means we are in the middle of
4089 ;; a command with prefix, such as a command invoked with prefix-arg.
4090 (if (not prefix-command--needs-update)
4091 prefix-command--last-echo
4092 (setq prefix-command--last-echo
4093 (let ((strs nil))
4094 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4095 (lambda (fun) (push (funcall fun) strs)))
4096 (setq strs (delq nil strs))
4097 (when strs (mapconcat #'identity strs " "))))))
4099 (defvar prefix-command-echo-keystrokes-functions nil
4100 "Abnormal hook which constructs the description of the current prefix state.
4101 Each function is called with no argument, should return a string or nil.")
4103 (defun prefix-command-update ()
4104 "Update state of prefix commands.
4105 Call it whenever you change the \"prefix command state\"."
4106 (setq prefix-command--needs-update t))
4108 (defvar prefix-command-preserve-state-hook nil
4109 "Normal hook run when a command needs to preserve the prefix.")
4111 (defun prefix-command-preserve-state ()
4112 "Pass the current prefix command state to the next command.
4113 Should be called by all prefix commands.
4114 Runs `prefix-command-preserve-state-hook'."
4115 (run-hooks 'prefix-command-preserve-state-hook)
4116 ;; If the current command is a prefix command, we don't want the next (real)
4117 ;; command to have `last-command' set to, say, `universal-argument'.
4118 (setq this-command last-command)
4119 (setq real-this-command real-last-command)
4120 (prefix-command-update))
4122 (defun reset-this-command-lengths ()
4123 (declare (obsolete prefix-command-preserve-state "25.1"))
4124 nil)
4126 ;;;;; The main prefix command.
4128 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4130 (add-hook 'prefix-command-echo-keystrokes-functions
4131 #'universal-argument--description)
4132 (defun universal-argument--description ()
4133 (when prefix-arg
4134 (concat "C-u"
4135 (pcase prefix-arg
4136 (`(-) " -")
4137 (`(,(and (pred integerp) n))
4138 (let ((str ""))
4139 (while (and (> n 4) (= (mod n 4) 0))
4140 (setq str (concat str " C-u"))
4141 (setq n (/ n 4)))
4142 (if (= n 4) str (format " %s" prefix-arg))))
4143 (_ (format " %s" prefix-arg))))))
4145 (add-hook 'prefix-command-preserve-state-hook
4146 #'universal-argument--preserve)
4147 (defun universal-argument--preserve ()
4148 (setq prefix-arg current-prefix-arg))
4150 (defvar universal-argument-map
4151 (let ((map (make-sparse-keymap))
4152 (universal-argument-minus
4153 ;; For backward compatibility, minus with no modifiers is an ordinary
4154 ;; command if digits have already been entered.
4155 `(menu-item "" negative-argument
4156 :filter ,(lambda (cmd)
4157 (if (integerp prefix-arg) nil cmd)))))
4158 (define-key map [switch-frame]
4159 (lambda (e) (interactive "e")
4160 (handle-switch-frame e) (universal-argument--mode)))
4161 (define-key map [?\C-u] 'universal-argument-more)
4162 (define-key map [?-] universal-argument-minus)
4163 (define-key map [?0] 'digit-argument)
4164 (define-key map [?1] 'digit-argument)
4165 (define-key map [?2] 'digit-argument)
4166 (define-key map [?3] 'digit-argument)
4167 (define-key map [?4] 'digit-argument)
4168 (define-key map [?5] 'digit-argument)
4169 (define-key map [?6] 'digit-argument)
4170 (define-key map [?7] 'digit-argument)
4171 (define-key map [?8] 'digit-argument)
4172 (define-key map [?9] 'digit-argument)
4173 (define-key map [kp-0] 'digit-argument)
4174 (define-key map [kp-1] 'digit-argument)
4175 (define-key map [kp-2] 'digit-argument)
4176 (define-key map [kp-3] 'digit-argument)
4177 (define-key map [kp-4] 'digit-argument)
4178 (define-key map [kp-5] 'digit-argument)
4179 (define-key map [kp-6] 'digit-argument)
4180 (define-key map [kp-7] 'digit-argument)
4181 (define-key map [kp-8] 'digit-argument)
4182 (define-key map [kp-9] 'digit-argument)
4183 (define-key map [kp-subtract] universal-argument-minus)
4184 map)
4185 "Keymap used while processing \\[universal-argument].")
4187 (defun universal-argument--mode ()
4188 (prefix-command-update)
4189 (set-transient-map universal-argument-map nil))
4191 (defun universal-argument ()
4192 "Begin a numeric argument for the following command.
4193 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4194 \\[universal-argument] following the digits or minus sign ends the argument.
4195 \\[universal-argument] without digits or minus sign provides 4 as argument.
4196 Repeating \\[universal-argument] without digits or minus sign
4197 multiplies the argument by 4 each time.
4198 For some commands, just \\[universal-argument] by itself serves as a flag
4199 which is different in effect from any particular numeric argument.
4200 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4201 (interactive)
4202 (prefix-command-preserve-state)
4203 (setq prefix-arg (list 4))
4204 (universal-argument--mode))
4206 (defun universal-argument-more (arg)
4207 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4208 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4209 (interactive "P")
4210 (prefix-command-preserve-state)
4211 (setq prefix-arg (if (consp arg)
4212 (list (* 4 (car arg)))
4213 (if (eq arg '-)
4214 (list -4)
4215 arg)))
4216 (when (consp prefix-arg) (universal-argument--mode)))
4218 (defun negative-argument (arg)
4219 "Begin a negative numeric argument for the next command.
4220 \\[universal-argument] following digits or minus sign ends the argument."
4221 (interactive "P")
4222 (prefix-command-preserve-state)
4223 (setq prefix-arg (cond ((integerp arg) (- arg))
4224 ((eq arg '-) nil)
4225 (t '-)))
4226 (universal-argument--mode))
4228 (defun digit-argument (arg)
4229 "Part of the numeric argument for the next command.
4230 \\[universal-argument] following digits or minus sign ends the argument."
4231 (interactive "P")
4232 (prefix-command-preserve-state)
4233 (let* ((char (if (integerp last-command-event)
4234 last-command-event
4235 (get last-command-event 'ascii-character)))
4236 (digit (- (logand char ?\177) ?0)))
4237 (setq prefix-arg (cond ((integerp arg)
4238 (+ (* arg 10)
4239 (if (< arg 0) (- digit) digit)))
4240 ((eq arg '-)
4241 ;; Treat -0 as just -, so that -01 will work.
4242 (if (zerop digit) '- (- digit)))
4244 digit))))
4245 (universal-argument--mode))
4248 (defvar filter-buffer-substring-functions nil
4249 "This variable is a wrapper hook around `buffer-substring--filter'.
4250 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4251 (make-obsolete-variable 'filter-buffer-substring-functions
4252 'filter-buffer-substring-function "24.4")
4254 (defvar filter-buffer-substring-function #'buffer-substring--filter
4255 "Function to perform the filtering in `filter-buffer-substring'.
4256 The function is called with the same 3 arguments (BEG END DELETE)
4257 that `filter-buffer-substring' received. It should return the
4258 buffer substring between BEG and END, after filtering. If DELETE is
4259 non-nil, it should delete the text between BEG and END from the buffer.")
4261 (defvar buffer-substring-filters nil
4262 "List of filter functions for `buffer-substring--filter'.
4263 Each function must accept a single argument, a string, and return a string.
4264 The buffer substring is passed to the first function in the list,
4265 and the return value of each function is passed to the next.
4266 As a special convention, point is set to the start of the buffer text
4267 being operated on (i.e., the first argument of `buffer-substring--filter')
4268 before these functions are called.")
4269 (make-obsolete-variable 'buffer-substring-filters
4270 'filter-buffer-substring-function "24.1")
4272 (defun filter-buffer-substring (beg end &optional delete)
4273 "Return the buffer substring between BEG and END, after filtering.
4274 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4276 This calls the function that `filter-buffer-substring-function' specifies
4277 \(passing the same three arguments that it received) to do the work,
4278 and returns whatever it does. The default function does no filtering,
4279 unless a hook has been set.
4281 Use `filter-buffer-substring' instead of `buffer-substring',
4282 `buffer-substring-no-properties', or `delete-and-extract-region' when
4283 you want to allow filtering to take place. For example, major or minor
4284 modes can use `filter-buffer-substring-function' to extract characters
4285 that are special to a buffer, and should not be copied into other buffers."
4286 (funcall filter-buffer-substring-function beg end delete))
4288 (defun buffer-substring--filter (beg end &optional delete)
4289 "Default function to use for `filter-buffer-substring-function'.
4290 Its arguments and return value are as specified for `filter-buffer-substring'.
4291 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4292 \(see `with-wrapper-hook' for details about wrapper hooks),
4293 and the abnormal hook `buffer-substring-filters'.
4294 No filtering is done unless a hook says to."
4295 (subr--with-wrapper-hook-no-warnings
4296 filter-buffer-substring-functions (beg end delete)
4297 (cond
4298 ((or delete buffer-substring-filters)
4299 (save-excursion
4300 (goto-char beg)
4301 (let ((string (if delete (delete-and-extract-region beg end)
4302 (buffer-substring beg end))))
4303 (dolist (filter buffer-substring-filters)
4304 (setq string (funcall filter string)))
4305 string)))
4307 (buffer-substring beg end)))))
4310 ;;;; Window system cut and paste hooks.
4312 (defvar interprogram-cut-function #'gui-select-text
4313 "Function to call to make a killed region available to other programs.
4314 Most window systems provide a facility for cutting and pasting
4315 text between different programs, such as the clipboard on X and
4316 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4318 This variable holds a function that Emacs calls whenever text is
4319 put in the kill ring, to make the new kill available to other
4320 programs. The function takes one argument, TEXT, which is a
4321 string containing the text which should be made available.")
4323 (defvar interprogram-paste-function #'gui-selection-value
4324 "Function to call to get text cut from other programs.
4325 Most window systems provide a facility for cutting and pasting
4326 text between different programs, such as the clipboard on X and
4327 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4329 This variable holds a function that Emacs calls to obtain text
4330 that other programs have provided for pasting. The function is
4331 called with no arguments. If no other program has provided text
4332 to paste, the function should return nil (in which case the
4333 caller, usually `current-kill', should use the top of the Emacs
4334 kill ring). If another program has provided text to paste, the
4335 function should return that text as a string (in which case the
4336 caller should put this string in the kill ring as the latest
4337 kill).
4339 The function may also return a list of strings if the window
4340 system supports multiple selections. The first string will be
4341 used as the pasted text, but the other will be placed in the kill
4342 ring for easy access via `yank-pop'.
4344 Note that the function should return a string only if a program
4345 other than Emacs has provided a string for pasting; if Emacs
4346 provided the most recent string, the function should return nil.
4347 If it is difficult to tell whether Emacs or some other program
4348 provided the current string, it is probably good enough to return
4349 nil if the string is equal (according to `string=') to the last
4350 text Emacs provided.")
4354 ;;;; The kill ring data structure.
4356 (defvar kill-ring nil
4357 "List of killed text sequences.
4358 Since the kill ring is supposed to interact nicely with cut-and-paste
4359 facilities offered by window systems, use of this variable should
4360 interact nicely with `interprogram-cut-function' and
4361 `interprogram-paste-function'. The functions `kill-new',
4362 `kill-append', and `current-kill' are supposed to implement this
4363 interaction; you may want to use them instead of manipulating the kill
4364 ring directly.")
4366 (defcustom kill-ring-max 60
4367 "Maximum length of kill ring before oldest elements are thrown away."
4368 :type 'integer
4369 :group 'killing)
4371 (defvar kill-ring-yank-pointer nil
4372 "The tail of the kill ring whose car is the last thing yanked.")
4374 (defcustom save-interprogram-paste-before-kill nil
4375 "Save clipboard strings into kill ring before replacing them.
4376 When one selects something in another program to paste it into Emacs,
4377 but kills something in Emacs before actually pasting it,
4378 this selection is gone unless this variable is non-nil,
4379 in which case the other program's selection is saved in the `kill-ring'
4380 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4381 :type 'boolean
4382 :group 'killing
4383 :version "23.2")
4385 (defcustom kill-do-not-save-duplicates nil
4386 "Do not add a new string to `kill-ring' if it duplicates the last one.
4387 The comparison is done using `equal-including-properties'."
4388 :type 'boolean
4389 :group 'killing
4390 :version "23.2")
4392 (defun kill-new (string &optional replace)
4393 "Make STRING the latest kill in the kill ring.
4394 Set `kill-ring-yank-pointer' to point to it.
4395 If `interprogram-cut-function' is non-nil, apply it to STRING.
4396 Optional second argument REPLACE non-nil means that STRING will replace
4397 the front of the kill ring, rather than being added to the list.
4399 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4400 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4401 STRING.
4403 When the yank handler has a non-nil PARAM element, the original STRING
4404 argument is not used by `insert-for-yank'. However, since Lisp code
4405 may access and use elements from the kill ring directly, the STRING
4406 argument should still be a \"useful\" string for such uses."
4407 (unless (and kill-do-not-save-duplicates
4408 ;; Due to text properties such as 'yank-handler that
4409 ;; can alter the contents to yank, comparison using
4410 ;; `equal' is unsafe.
4411 (equal-including-properties string (car kill-ring)))
4412 (if (fboundp 'menu-bar-update-yank-menu)
4413 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4414 (when save-interprogram-paste-before-kill
4415 (let ((interprogram-paste (and interprogram-paste-function
4416 (funcall interprogram-paste-function))))
4417 (when interprogram-paste
4418 (dolist (s (if (listp interprogram-paste)
4419 (nreverse interprogram-paste)
4420 (list interprogram-paste)))
4421 (unless (and kill-do-not-save-duplicates
4422 (equal-including-properties s (car kill-ring)))
4423 (push s kill-ring))))))
4424 (unless (and kill-do-not-save-duplicates
4425 (equal-including-properties string (car kill-ring)))
4426 (if (and replace kill-ring)
4427 (setcar kill-ring string)
4428 (push string kill-ring)
4429 (if (> (length kill-ring) kill-ring-max)
4430 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4431 (setq kill-ring-yank-pointer kill-ring)
4432 (if interprogram-cut-function
4433 (funcall interprogram-cut-function string)))
4435 ;; It has been argued that this should work similar to `self-insert-command'
4436 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4437 (defcustom kill-append-merge-undo nil
4438 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4439 :type 'boolean
4440 :group 'killing
4441 :version "25.1")
4443 (defun kill-append (string before-p)
4444 "Append STRING to the end of the latest kill in the kill ring.
4445 If BEFORE-P is non-nil, prepend STRING to the kill.
4446 Also removes the last undo boundary in the current buffer,
4447 depending on `kill-append-merge-undo'.
4448 If `interprogram-cut-function' is set, pass the resulting kill to it."
4449 (let* ((cur (car kill-ring)))
4450 (kill-new (if before-p (concat string cur) (concat cur string))
4451 (or (= (length cur) 0)
4452 (equal nil (get-text-property 0 'yank-handler cur))))
4453 (when (and kill-append-merge-undo (not buffer-read-only))
4454 (let ((prev buffer-undo-list)
4455 (next (cdr buffer-undo-list)))
4456 ;; find the next undo boundary
4457 (while (car next)
4458 (pop next)
4459 (pop prev))
4460 ;; remove this undo boundary
4461 (when prev
4462 (setcdr prev (cdr next)))))))
4464 (defcustom yank-pop-change-selection nil
4465 "Whether rotating the kill ring changes the window system selection.
4466 If non-nil, whenever the kill ring is rotated (usually via the
4467 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4468 to copy the new kill to the window system selection."
4469 :type 'boolean
4470 :group 'killing
4471 :version "23.1")
4473 (defun current-kill (n &optional do-not-move)
4474 "Rotate the yanking point by N places, and then return that kill.
4475 If N is zero and `interprogram-paste-function' is set to a
4476 function that returns a string or a list of strings, and if that
4477 function doesn't return nil, then that string (or list) is added
4478 to the front of the kill ring and the string (or first string in
4479 the list) is returned as the latest kill.
4481 If N is not zero, and if `yank-pop-change-selection' is
4482 non-nil, use `interprogram-cut-function' to transfer the
4483 kill at the new yank point into the window system selection.
4485 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4486 move the yanking point; just return the Nth kill forward."
4488 (let ((interprogram-paste (and (= n 0)
4489 interprogram-paste-function
4490 (funcall interprogram-paste-function))))
4491 (if interprogram-paste
4492 (progn
4493 ;; Disable the interprogram cut function when we add the new
4494 ;; text to the kill ring, so Emacs doesn't try to own the
4495 ;; selection, with identical text.
4496 (let ((interprogram-cut-function nil))
4497 (if (listp interprogram-paste)
4498 (mapc 'kill-new (nreverse interprogram-paste))
4499 (kill-new interprogram-paste)))
4500 (car kill-ring))
4501 (or kill-ring (error "Kill ring is empty"))
4502 (let ((ARGth-kill-element
4503 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4504 (length kill-ring))
4505 kill-ring)))
4506 (unless do-not-move
4507 (setq kill-ring-yank-pointer ARGth-kill-element)
4508 (when (and yank-pop-change-selection
4509 (> n 0)
4510 interprogram-cut-function)
4511 (funcall interprogram-cut-function (car ARGth-kill-element))))
4512 (car ARGth-kill-element)))))
4516 ;;;; Commands for manipulating the kill ring.
4518 (defcustom kill-read-only-ok nil
4519 "Non-nil means don't signal an error for killing read-only text."
4520 :type 'boolean
4521 :group 'killing)
4523 (defun kill-region (beg end &optional region)
4524 "Kill (\"cut\") text between point and mark.
4525 This deletes the text from the buffer and saves it in the kill ring.
4526 The command \\[yank] can retrieve it from there.
4527 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4529 If you want to append the killed region to the last killed text,
4530 use \\[append-next-kill] before \\[kill-region].
4532 Any command that calls this function is a \"kill command\".
4533 If the previous command was also a kill command,
4534 the text killed this time appends to the text killed last time
4535 to make one entry in the kill ring.
4537 The killed text is filtered by `filter-buffer-substring' before it is
4538 saved in the kill ring, so the actual saved text might be different
4539 from what was killed.
4541 If the buffer is read-only, Emacs will beep and refrain from deleting
4542 the text, but put the text in the kill ring anyway. This means that
4543 you can use the killing commands to copy text from a read-only buffer.
4545 Lisp programs should use this function for killing text.
4546 (To delete text, use `delete-region'.)
4547 Supply two arguments, character positions BEG and END indicating the
4548 stretch of text to be killed. If the optional argument REGION is
4549 non-nil, the function ignores BEG and END, and kills the current
4550 region instead."
4551 ;; Pass mark first, then point, because the order matters when
4552 ;; calling `kill-append'.
4553 (interactive (list (mark) (point) 'region))
4554 (unless (and beg end)
4555 (user-error "The mark is not set now, so there is no region"))
4556 (condition-case nil
4557 (let ((string (if region
4558 (funcall region-extract-function 'delete)
4559 (filter-buffer-substring beg end 'delete))))
4560 (when string ;STRING is nil if BEG = END
4561 ;; Add that string to the kill ring, one way or another.
4562 (if (eq last-command 'kill-region)
4563 (kill-append string (< end beg))
4564 (kill-new string)))
4565 (when (or string (eq last-command 'kill-region))
4566 (setq this-command 'kill-region))
4567 (setq deactivate-mark t)
4568 nil)
4569 ((buffer-read-only text-read-only)
4570 ;; The code above failed because the buffer, or some of the characters
4571 ;; in the region, are read-only.
4572 ;; We should beep, in case the user just isn't aware of this.
4573 ;; However, there's no harm in putting
4574 ;; the region's text in the kill ring, anyway.
4575 (copy-region-as-kill beg end region)
4576 ;; Set this-command now, so it will be set even if we get an error.
4577 (setq this-command 'kill-region)
4578 ;; This should barf, if appropriate, and give us the correct error.
4579 (if kill-read-only-ok
4580 (progn (message "Read only text copied to kill ring") nil)
4581 ;; Signal an error if the buffer is read-only.
4582 (barf-if-buffer-read-only)
4583 ;; If the buffer isn't read-only, the text is.
4584 (signal 'text-read-only (list (current-buffer)))))))
4586 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4587 ;; to get two copies of the text when the user accidentally types M-w and
4588 ;; then corrects it with the intended C-w.
4589 (defun copy-region-as-kill (beg end &optional region)
4590 "Save the region as if killed, but don't kill it.
4591 In Transient Mark mode, deactivate the mark.
4592 If `interprogram-cut-function' is non-nil, also save the text for a window
4593 system cut and paste.
4595 The copied text is filtered by `filter-buffer-substring' before it is
4596 saved in the kill ring, so the actual saved text might be different
4597 from what was in the buffer.
4599 When called from Lisp, save in the kill ring the stretch of text
4600 between BEG and END, unless the optional argument REGION is
4601 non-nil, in which case ignore BEG and END, and save the current
4602 region instead.
4604 This command's old key binding has been given to `kill-ring-save'."
4605 ;; Pass mark first, then point, because the order matters when
4606 ;; calling `kill-append'.
4607 (interactive (list (mark) (point)
4608 (prefix-numeric-value current-prefix-arg)))
4609 (let ((str (if region
4610 (funcall region-extract-function nil)
4611 (filter-buffer-substring beg end))))
4612 (if (eq last-command 'kill-region)
4613 (kill-append str (< end beg))
4614 (kill-new str)))
4615 (setq deactivate-mark t)
4616 nil)
4618 (defun kill-ring-save (beg end &optional region)
4619 "Save the region as if killed, but don't kill it.
4620 In Transient Mark mode, deactivate the mark.
4621 If `interprogram-cut-function' is non-nil, also save the text for a window
4622 system cut and paste.
4624 If you want to append the killed line to the last killed text,
4625 use \\[append-next-kill] before \\[kill-ring-save].
4627 The copied text is filtered by `filter-buffer-substring' before it is
4628 saved in the kill ring, so the actual saved text might be different
4629 from what was in the buffer.
4631 When called from Lisp, save in the kill ring the stretch of text
4632 between BEG and END, unless the optional argument REGION is
4633 non-nil, in which case ignore BEG and END, and save the current
4634 region instead.
4636 This command is similar to `copy-region-as-kill', except that it gives
4637 visual feedback indicating the extent of the region being copied."
4638 ;; Pass mark first, then point, because the order matters when
4639 ;; calling `kill-append'.
4640 (interactive (list (mark) (point)
4641 (prefix-numeric-value current-prefix-arg)))
4642 (copy-region-as-kill beg end region)
4643 ;; This use of called-interactively-p is correct because the code it
4644 ;; controls just gives the user visual feedback.
4645 (if (called-interactively-p 'interactive)
4646 (indicate-copied-region)))
4648 (defun indicate-copied-region (&optional message-len)
4649 "Indicate that the region text has been copied interactively.
4650 If the mark is visible in the selected window, blink the cursor
4651 between point and mark if there is currently no active region
4652 highlighting.
4654 If the mark lies outside the selected window, display an
4655 informative message containing a sample of the copied text. The
4656 optional argument MESSAGE-LEN, if non-nil, specifies the length
4657 of this sample text; it defaults to 40."
4658 (let ((mark (mark t))
4659 (point (point))
4660 ;; Inhibit quitting so we can make a quit here
4661 ;; look like a C-g typed as a command.
4662 (inhibit-quit t))
4663 (if (pos-visible-in-window-p mark (selected-window))
4664 ;; Swap point-and-mark quickly so as to show the region that
4665 ;; was selected. Don't do it if the region is highlighted.
4666 (unless (and (region-active-p)
4667 (face-background 'region))
4668 ;; Swap point and mark.
4669 (set-marker (mark-marker) (point) (current-buffer))
4670 (goto-char mark)
4671 (sit-for blink-matching-delay)
4672 ;; Swap back.
4673 (set-marker (mark-marker) mark (current-buffer))
4674 (goto-char point)
4675 ;; If user quit, deactivate the mark
4676 ;; as C-g would as a command.
4677 (and quit-flag (region-active-p)
4678 (deactivate-mark)))
4679 (let ((len (min (abs (- mark point))
4680 (or message-len 40))))
4681 (if (< point mark)
4682 ;; Don't say "killed"; that is misleading.
4683 (message "Saved text until \"%s\""
4684 (buffer-substring-no-properties (- mark len) mark))
4685 (message "Saved text from \"%s\""
4686 (buffer-substring-no-properties mark (+ mark len))))))))
4688 (defun append-next-kill (&optional interactive)
4689 "Cause following command, if it kills, to add to previous kill.
4690 If the next command kills forward from point, the kill is
4691 appended to the previous killed text. If the command kills
4692 backward, the kill is prepended. Kill commands that act on the
4693 region, such as `kill-region', are regarded as killing forward if
4694 point is after mark, and killing backward if point is before
4695 mark.
4697 If the next command is not a kill command, `append-next-kill' has
4698 no effect.
4700 The argument is used for internal purposes; do not supply one."
4701 (interactive "p")
4702 ;; We don't use (interactive-p), since that breaks kbd macros.
4703 (if interactive
4704 (progn
4705 (setq this-command 'kill-region)
4706 (message "If the next command is a kill, it will append"))
4707 (setq last-command 'kill-region)))
4709 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4710 "Character set that matches bidirectional formatting control characters.")
4712 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4713 "Character set that matches any character except bidirectional controls.")
4715 (defun squeeze-bidi-context-1 (from to category replacement)
4716 "A subroutine of `squeeze-bidi-context'.
4717 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4718 (let ((pt (copy-marker from))
4719 (limit (copy-marker to))
4720 (old-pt 0)
4721 lim1)
4722 (setq lim1 limit)
4723 (goto-char pt)
4724 (while (< pt limit)
4725 (if (> pt old-pt)
4726 (move-marker lim1
4727 (save-excursion
4728 ;; L and R categories include embedding and
4729 ;; override controls, but we don't want to
4730 ;; replace them, because that might change
4731 ;; the visual order. Likewise with PDF and
4732 ;; isolate controls.
4733 (+ pt (skip-chars-forward
4734 bidi-directional-non-controls-chars
4735 limit)))))
4736 ;; Replace any run of non-RTL characters by a single LRM.
4737 (if (null (re-search-forward category lim1 t))
4738 ;; No more characters of CATEGORY, we are done.
4739 (setq pt limit)
4740 (replace-match replacement nil t)
4741 (move-marker pt (point)))
4742 (setq old-pt pt)
4743 ;; Skip directional controls, if any.
4744 (move-marker
4745 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4747 (defun squeeze-bidi-context (from to)
4748 "Replace characters between FROM and TO while keeping bidi context.
4750 This function replaces the region of text with as few characters
4751 as possible, while preserving the effect that region will have on
4752 bidirectional display before and after the region."
4753 (let ((start (set-marker (make-marker)
4754 (if (> from 0) from (+ (point-max) from))))
4755 (end (set-marker (make-marker) to))
4756 ;; This is for when they copy text with read-only text
4757 ;; properties.
4758 (inhibit-read-only t))
4759 (if (null (marker-position end))
4760 (setq end (point-max-marker)))
4761 ;; Replace each run of non-RTL characters with a single LRM.
4762 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4763 ;; Replace each run of non-LTR characters with a single RLM. Note
4764 ;; that the \cR category includes both the Arabic Letter (AL) and
4765 ;; R characters; here we ignore the distinction between them,
4766 ;; because that distinction only affects Arabic Number (AN)
4767 ;; characters, which are weak and don't affect the reordering.
4768 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4770 (defun line-substring-with-bidi-context (start end &optional no-properties)
4771 "Return buffer text between START and END with its bidi context.
4773 START and END are assumed to belong to the same physical line
4774 of buffer text. This function prepends and appends to the text
4775 between START and END bidi control characters that preserve the
4776 visual order of that text when it is inserted at some other place."
4777 (if (or (< start (point-min))
4778 (> end (point-max)))
4779 (signal 'args-out-of-range (list (current-buffer) start end)))
4780 (let ((buf (current-buffer))
4781 substr para-dir from to)
4782 (save-excursion
4783 (goto-char start)
4784 (setq para-dir (current-bidi-paragraph-direction))
4785 (setq from (line-beginning-position)
4786 to (line-end-position))
4787 (goto-char from)
4788 ;; If we don't have any mixed directional characters in the
4789 ;; entire line, we can just copy the substring without adding
4790 ;; any context.
4791 (if (or (looking-at-p "\\CR*$")
4792 (looking-at-p "\\CL*$"))
4793 (setq substr (if no-properties
4794 (buffer-substring-no-properties start end)
4795 (buffer-substring start end)))
4796 (setq substr
4797 (with-temp-buffer
4798 (if no-properties
4799 (insert-buffer-substring-no-properties buf from to)
4800 (insert-buffer-substring buf from to))
4801 (squeeze-bidi-context 1 (1+ (- start from)))
4802 (squeeze-bidi-context (- end to) nil)
4803 (buffer-substring 1 (point-max)))))
4805 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4806 ;; (1) force the string to have the same base embedding
4807 ;; direction as the paragraph direction at the source, no matter
4808 ;; what is the paragraph direction at destination; and (2) avoid
4809 ;; affecting the visual order of the surrounding text at
4810 ;; destination if there are characters of different
4811 ;; directionality there.
4812 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4813 substr "\x2069"))))
4815 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4816 "Return portion of current buffer between START and END with bidi context.
4818 This function works similar to `buffer-substring', but it prepends and
4819 appends to the text bidi directional control characters necessary to
4820 preserve the visual appearance of the text if it is inserted at another
4821 place. This is useful when the buffer substring includes bidirectional
4822 text and control characters that cause non-trivial reordering on display.
4823 If copied verbatim, such text can have a very different visual appearance,
4824 and can also change the visual appearance of the surrounding text at the
4825 destination of the copy.
4827 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4828 the text properties."
4829 (let (line-end substr)
4830 (if (or (< start (point-min))
4831 (> end (point-max)))
4832 (signal 'args-out-of-range (list (current-buffer) start end)))
4833 (save-excursion
4834 (goto-char start)
4835 (setq line-end (min end (line-end-position)))
4836 (while (< start end)
4837 (setq substr
4838 (concat substr
4839 (if substr "\n" "")
4840 (line-substring-with-bidi-context start line-end
4841 no-properties)))
4842 (forward-line 1)
4843 (setq start (point))
4844 (setq line-end (min end (line-end-position))))
4845 substr)))
4847 ;; Yanking.
4849 (defcustom yank-handled-properties
4850 '((font-lock-face . yank-handle-font-lock-face-property)
4851 (category . yank-handle-category-property))
4852 "List of special text property handling conditions for yanking.
4853 Each element should have the form (PROP . FUN), where PROP is a
4854 property symbol and FUN is a function. When the `yank' command
4855 inserts text into the buffer, it scans the inserted text for
4856 stretches of text that have `eq' values of the text property
4857 PROP; for each such stretch of text, FUN is called with three
4858 arguments: the property's value in that text, and the start and
4859 end positions of the text.
4861 This is done prior to removing the properties specified by
4862 `yank-excluded-properties'."
4863 :group 'killing
4864 :type '(repeat (cons (symbol :tag "property symbol")
4865 function))
4866 :version "24.3")
4868 ;; This is actually used in subr.el but defcustom does not work there.
4869 (defcustom yank-excluded-properties
4870 '(category field follow-link fontified font-lock-face help-echo
4871 intangible invisible keymap local-map mouse-face read-only
4872 yank-handler)
4873 "Text properties to discard when yanking.
4874 The value should be a list of text properties to discard or t,
4875 which means to discard all text properties.
4877 See also `yank-handled-properties'."
4878 :type '(choice (const :tag "All" t) (repeat symbol))
4879 :group 'killing
4880 :version "24.3")
4882 (defvar yank-window-start nil)
4883 (defvar yank-undo-function nil
4884 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4885 Function is called with two parameters, START and END corresponding to
4886 the value of the mark and point; it is guaranteed that START <= END.
4887 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4889 (defun yank-pop (&optional arg)
4890 "Replace just-yanked stretch of killed text with a different stretch.
4891 This command is allowed only immediately after a `yank' or a `yank-pop'.
4892 At such a time, the region contains a stretch of reinserted
4893 previously-killed text. `yank-pop' deletes that text and inserts in its
4894 place a different stretch of killed text.
4896 With no argument, the previous kill is inserted.
4897 With argument N, insert the Nth previous kill.
4898 If N is negative, this is a more recent kill.
4900 The sequence of kills wraps around, so that after the oldest one
4901 comes the newest one.
4903 This command honors the `yank-handled-properties' and
4904 `yank-excluded-properties' variables, and the `yank-handler' text
4905 property, in the way that `yank' does."
4906 (interactive "*p")
4907 (if (not (eq last-command 'yank))
4908 (user-error "Previous command was not a yank"))
4909 (setq this-command 'yank)
4910 (unless arg (setq arg 1))
4911 (let ((inhibit-read-only t)
4912 (before (< (point) (mark t))))
4913 (if before
4914 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4915 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4916 (setq yank-undo-function nil)
4917 (set-marker (mark-marker) (point) (current-buffer))
4918 (insert-for-yank (current-kill arg))
4919 ;; Set the window start back where it was in the yank command,
4920 ;; if possible.
4921 (set-window-start (selected-window) yank-window-start t)
4922 (if before
4923 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4924 ;; It is cleaner to avoid activation, even though the command
4925 ;; loop would deactivate the mark because we inserted text.
4926 (goto-char (prog1 (mark t)
4927 (set-marker (mark-marker) (point) (current-buffer))))))
4928 nil)
4930 (defun yank (&optional arg)
4931 "Reinsert (\"paste\") the last stretch of killed text.
4932 More precisely, reinsert the most recent kill, which is the
4933 stretch of killed text most recently killed OR yanked. Put point
4934 at the end, and set mark at the beginning without activating it.
4935 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4936 With argument N, reinsert the Nth most recent kill.
4938 This command honors the `yank-handled-properties' and
4939 `yank-excluded-properties' variables, and the `yank-handler' text
4940 property, as described below.
4942 Properties listed in `yank-handled-properties' are processed,
4943 then those listed in `yank-excluded-properties' are discarded.
4945 If STRING has a non-nil `yank-handler' property anywhere, the
4946 normal insert behavior is altered, and instead, for each contiguous
4947 segment of STRING that has a given value of the `yank-handler'
4948 property, that value is used as follows:
4950 The value of a `yank-handler' property must be a list of one to four
4951 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4952 FUNCTION, if non-nil, should be a function of one argument (the
4953 object to insert); FUNCTION is called instead of `insert'.
4954 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4955 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4956 PARAM may be a list of strings to insert as a rectangle). If PARAM
4957 is nil, then the current segment of STRING is used.
4958 If NOEXCLUDE is present and non-nil, the normal removal of
4959 `yank-excluded-properties' is not performed; instead FUNCTION is
4960 responsible for the removal. This may be necessary if FUNCTION
4961 adjusts point before or after inserting the object.
4962 UNDO, if present and non-nil, should be a function to be called
4963 by `yank-pop' to undo the insertion of the current PARAM. It is
4964 given two arguments, the start and end of the region. FUNCTION
4965 may set `yank-undo-function' to override UNDO.
4967 See also the command `yank-pop' (\\[yank-pop])."
4968 (interactive "*P")
4969 (setq yank-window-start (window-start))
4970 ;; If we don't get all the way thru, make last-command indicate that
4971 ;; for the following command.
4972 (setq this-command t)
4973 (push-mark)
4974 (insert-for-yank (current-kill (cond
4975 ((listp arg) 0)
4976 ((eq arg '-) -2)
4977 (t (1- arg)))))
4978 (if (consp arg)
4979 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4980 ;; It is cleaner to avoid activation, even though the command
4981 ;; loop would deactivate the mark because we inserted text.
4982 (goto-char (prog1 (mark t)
4983 (set-marker (mark-marker) (point) (current-buffer)))))
4984 ;; If we do get all the way thru, make this-command indicate that.
4985 (if (eq this-command t)
4986 (setq this-command 'yank))
4987 nil)
4989 (defun rotate-yank-pointer (arg)
4990 "Rotate the yanking point in the kill ring.
4991 With ARG, rotate that many kills forward (or backward, if negative)."
4992 (interactive "p")
4993 (current-kill arg))
4995 ;; Some kill commands.
4997 ;; Internal subroutine of delete-char
4998 (defun kill-forward-chars (arg)
4999 (if (listp arg) (setq arg (car arg)))
5000 (if (eq arg '-) (setq arg -1))
5001 (kill-region (point) (+ (point) arg)))
5003 ;; Internal subroutine of backward-delete-char
5004 (defun kill-backward-chars (arg)
5005 (if (listp arg) (setq arg (car arg)))
5006 (if (eq arg '-) (setq arg -1))
5007 (kill-region (point) (- (point) arg)))
5009 (defcustom backward-delete-char-untabify-method 'untabify
5010 "The method for untabifying when deleting backward.
5011 Can be `untabify' -- turn a tab to many spaces, then delete one space;
5012 `hungry' -- delete all whitespace, both tabs and spaces;
5013 `all' -- delete all whitespace, including tabs, spaces and newlines;
5014 nil -- just delete one character."
5015 :type '(choice (const untabify) (const hungry) (const all) (const nil))
5016 :version "20.3"
5017 :group 'killing)
5019 (defun backward-delete-char-untabify (arg &optional killp)
5020 "Delete characters backward, changing tabs into spaces.
5021 The exact behavior depends on `backward-delete-char-untabify-method'.
5022 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
5023 Interactively, ARG is the prefix arg (default 1)
5024 and KILLP is t if a prefix arg was specified."
5025 (interactive "*p\nP")
5026 (when (eq backward-delete-char-untabify-method 'untabify)
5027 (let ((count arg))
5028 (save-excursion
5029 (while (and (> count 0) (not (bobp)))
5030 (if (= (preceding-char) ?\t)
5031 (let ((col (current-column)))
5032 (forward-char -1)
5033 (setq col (- col (current-column)))
5034 (insert-char ?\s col)
5035 (delete-char 1)))
5036 (forward-char -1)
5037 (setq count (1- count))))))
5038 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
5039 ((eq backward-delete-char-untabify-method 'all)
5040 " \t\n\r")))
5041 (n (if skip
5042 (let* ((oldpt (point))
5043 (wh (- oldpt (save-excursion
5044 (skip-chars-backward skip)
5045 (constrain-to-field nil oldpt)))))
5046 (+ arg (if (zerop wh) 0 (1- wh))))
5047 arg)))
5048 ;; Avoid warning about delete-backward-char
5049 (with-no-warnings (delete-backward-char n killp))))
5051 (defun zap-to-char (arg char)
5052 "Kill up to and including ARGth occurrence of CHAR.
5053 Case is ignored if `case-fold-search' is non-nil in the current buffer.
5054 Goes backward if ARG is negative; error if CHAR not found."
5055 (interactive (list (prefix-numeric-value current-prefix-arg)
5056 (read-char "Zap to char: " t)))
5057 ;; Avoid "obsolete" warnings for translation-table-for-input.
5058 (with-no-warnings
5059 (if (char-table-p translation-table-for-input)
5060 (setq char (or (aref translation-table-for-input char) char))))
5061 (kill-region (point) (progn
5062 (search-forward (char-to-string char) nil nil arg)
5063 (point))))
5065 ;; kill-line and its subroutines.
5067 (defcustom kill-whole-line nil
5068 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
5069 :type 'boolean
5070 :group 'killing)
5072 (defun kill-line (&optional arg)
5073 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5074 With prefix argument ARG, kill that many lines from point.
5075 Negative arguments kill lines backward.
5076 With zero argument, kills the text before point on the current line.
5078 When calling from a program, nil means \"no arg\",
5079 a number counts as a prefix arg.
5081 To kill a whole line, when point is not at the beginning, type \
5082 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5084 If `show-trailing-whitespace' is non-nil, this command will just
5085 kill the rest of the current line, even if there are no nonblanks
5086 there.
5088 If option `kill-whole-line' is non-nil, then this command kills the whole line
5089 including its terminating newline, when used at the beginning of a line
5090 with no argument. As a consequence, you can always kill a whole line
5091 by typing \\[move-beginning-of-line] \\[kill-line].
5093 If you want to append the killed line to the last killed text,
5094 use \\[append-next-kill] before \\[kill-line].
5096 If the buffer is read-only, Emacs will beep and refrain from deleting
5097 the line, but put the line in the kill ring anyway. This means that
5098 you can use this command to copy text from a read-only buffer.
5099 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5100 even beep.)"
5101 (interactive "P")
5102 (kill-region (point)
5103 ;; It is better to move point to the other end of the kill
5104 ;; before killing. That way, in a read-only buffer, point
5105 ;; moves across the text that is copied to the kill ring.
5106 ;; The choice has no effect on undo now that undo records
5107 ;; the value of point from before the command was run.
5108 (progn
5109 (if arg
5110 (forward-visible-line (prefix-numeric-value arg))
5111 (if (eobp)
5112 (signal 'end-of-buffer nil))
5113 (let ((end
5114 (save-excursion
5115 (end-of-visible-line) (point))))
5116 (if (or (save-excursion
5117 ;; If trailing whitespace is visible,
5118 ;; don't treat it as nothing.
5119 (unless show-trailing-whitespace
5120 (skip-chars-forward " \t" end))
5121 (= (point) end))
5122 (and kill-whole-line (bolp)))
5123 (forward-visible-line 1)
5124 (goto-char end))))
5125 (point))))
5127 (defun kill-whole-line (&optional arg)
5128 "Kill current line.
5129 With prefix ARG, kill that many lines starting from the current line.
5130 If ARG is negative, kill backward. Also kill the preceding newline.
5131 \(This is meant to make \\[repeat] work well with negative arguments.)
5132 If ARG is zero, kill current line but exclude the trailing newline."
5133 (interactive "p")
5134 (or arg (setq arg 1))
5135 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5136 (signal 'end-of-buffer nil))
5137 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5138 (signal 'beginning-of-buffer nil))
5139 (unless (eq last-command 'kill-region)
5140 (kill-new "")
5141 (setq last-command 'kill-region))
5142 (cond ((zerop arg)
5143 ;; We need to kill in two steps, because the previous command
5144 ;; could have been a kill command, in which case the text
5145 ;; before point needs to be prepended to the current kill
5146 ;; ring entry and the text after point appended. Also, we
5147 ;; need to use save-excursion to avoid copying the same text
5148 ;; twice to the kill ring in read-only buffers.
5149 (save-excursion
5150 (kill-region (point) (progn (forward-visible-line 0) (point))))
5151 (kill-region (point) (progn (end-of-visible-line) (point))))
5152 ((< arg 0)
5153 (save-excursion
5154 (kill-region (point) (progn (end-of-visible-line) (point))))
5155 (kill-region (point)
5156 (progn (forward-visible-line (1+ arg))
5157 (unless (bobp) (backward-char))
5158 (point))))
5160 (save-excursion
5161 (kill-region (point) (progn (forward-visible-line 0) (point))))
5162 (kill-region (point)
5163 (progn (forward-visible-line arg) (point))))))
5165 (defun forward-visible-line (arg)
5166 "Move forward by ARG lines, ignoring currently invisible newlines only.
5167 If ARG is negative, move backward -ARG lines.
5168 If ARG is zero, move to the beginning of the current line."
5169 (condition-case nil
5170 (if (> arg 0)
5171 (progn
5172 (while (> arg 0)
5173 (or (zerop (forward-line 1))
5174 (signal 'end-of-buffer nil))
5175 ;; If the newline we just skipped is invisible,
5176 ;; don't count it.
5177 (let ((prop
5178 (get-char-property (1- (point)) 'invisible)))
5179 (if (if (eq buffer-invisibility-spec t)
5180 prop
5181 (or (memq prop buffer-invisibility-spec)
5182 (assq prop buffer-invisibility-spec)))
5183 (setq arg (1+ arg))))
5184 (setq arg (1- arg)))
5185 ;; If invisible text follows, and it is a number of complete lines,
5186 ;; skip it.
5187 (let ((opoint (point)))
5188 (while (and (not (eobp))
5189 (let ((prop
5190 (get-char-property (point) 'invisible)))
5191 (if (eq buffer-invisibility-spec t)
5192 prop
5193 (or (memq prop buffer-invisibility-spec)
5194 (assq prop buffer-invisibility-spec)))))
5195 (goto-char
5196 (if (get-text-property (point) 'invisible)
5197 (or (next-single-property-change (point) 'invisible)
5198 (point-max))
5199 (next-overlay-change (point)))))
5200 (unless (bolp)
5201 (goto-char opoint))))
5202 (let ((first t))
5203 (while (or first (<= arg 0))
5204 (if first
5205 (beginning-of-line)
5206 (or (zerop (forward-line -1))
5207 (signal 'beginning-of-buffer nil)))
5208 ;; If the newline we just moved to is invisible,
5209 ;; don't count it.
5210 (unless (bobp)
5211 (let ((prop
5212 (get-char-property (1- (point)) 'invisible)))
5213 (unless (if (eq buffer-invisibility-spec t)
5214 prop
5215 (or (memq prop buffer-invisibility-spec)
5216 (assq prop buffer-invisibility-spec)))
5217 (setq arg (1+ arg)))))
5218 (setq first nil))
5219 ;; If invisible text follows, and it is a number of complete lines,
5220 ;; skip it.
5221 (let ((opoint (point)))
5222 (while (and (not (bobp))
5223 (let ((prop
5224 (get-char-property (1- (point)) 'invisible)))
5225 (if (eq buffer-invisibility-spec t)
5226 prop
5227 (or (memq prop buffer-invisibility-spec)
5228 (assq prop buffer-invisibility-spec)))))
5229 (goto-char
5230 (if (get-text-property (1- (point)) 'invisible)
5231 (or (previous-single-property-change (point) 'invisible)
5232 (point-min))
5233 (previous-overlay-change (point)))))
5234 (unless (bolp)
5235 (goto-char opoint)))))
5236 ((beginning-of-buffer end-of-buffer)
5237 nil)))
5239 (defun end-of-visible-line ()
5240 "Move to end of current visible line."
5241 (end-of-line)
5242 ;; If the following character is currently invisible,
5243 ;; skip all characters with that same `invisible' property value,
5244 ;; then find the next newline.
5245 (while (and (not (eobp))
5246 (save-excursion
5247 (skip-chars-forward "^\n")
5248 (let ((prop
5249 (get-char-property (point) 'invisible)))
5250 (if (eq buffer-invisibility-spec t)
5251 prop
5252 (or (memq prop buffer-invisibility-spec)
5253 (assq prop buffer-invisibility-spec))))))
5254 (skip-chars-forward "^\n")
5255 (if (get-text-property (point) 'invisible)
5256 (goto-char (or (next-single-property-change (point) 'invisible)
5257 (point-max)))
5258 (goto-char (next-overlay-change (point))))
5259 (end-of-line)))
5261 (defun kill-current-buffer ()
5262 "Kill the current buffer.
5263 When called in the minibuffer, get out of the minibuffer
5264 using `abort-recursive-edit'.
5266 This is like `kill-this-buffer', but it doesn't have to be invoked
5267 via the menu bar, and pays no attention to the menu-bar's frame."
5268 (interactive)
5269 (let ((frame (selected-frame)))
5270 (if (and (frame-live-p frame)
5271 (not (window-minibuffer-p (frame-selected-window frame))))
5272 (kill-buffer (current-buffer))
5273 (abort-recursive-edit))))
5276 (defun insert-buffer (buffer)
5277 "Insert after point the contents of BUFFER.
5278 Puts mark after the inserted text.
5279 BUFFER may be a buffer or a buffer name."
5280 (declare (interactive-only insert-buffer-substring))
5281 (interactive
5282 (list
5283 (progn
5284 (barf-if-buffer-read-only)
5285 (read-buffer "Insert buffer: "
5286 (if (eq (selected-window) (next-window))
5287 (other-buffer (current-buffer))
5288 (window-buffer (next-window)))
5289 t))))
5290 (push-mark
5291 (save-excursion
5292 (insert-buffer-substring (get-buffer buffer))
5293 (point)))
5294 nil)
5296 (defun append-to-buffer (buffer start end)
5297 "Append to specified buffer the text of the region.
5298 It is inserted into that buffer before its point.
5300 When calling from a program, give three arguments:
5301 BUFFER (or buffer name), START and END.
5302 START and END specify the portion of the current buffer to be copied."
5303 (interactive
5304 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5305 (region-beginning) (region-end)))
5306 (let* ((oldbuf (current-buffer))
5307 (append-to (get-buffer-create buffer))
5308 (windows (get-buffer-window-list append-to t t))
5309 point)
5310 (save-excursion
5311 (with-current-buffer append-to
5312 (setq point (point))
5313 (barf-if-buffer-read-only)
5314 (insert-buffer-substring oldbuf start end)
5315 (dolist (window windows)
5316 (when (= (window-point window) point)
5317 (set-window-point window (point))))))))
5319 (defun prepend-to-buffer (buffer start end)
5320 "Prepend to specified buffer the text of the region.
5321 It is inserted into that buffer after its point.
5323 When calling from a program, give three arguments:
5324 BUFFER (or buffer name), START and END.
5325 START and END specify the portion of the current buffer to be copied."
5326 (interactive "BPrepend to buffer: \nr")
5327 (let ((oldbuf (current-buffer)))
5328 (with-current-buffer (get-buffer-create buffer)
5329 (barf-if-buffer-read-only)
5330 (save-excursion
5331 (insert-buffer-substring oldbuf start end)))))
5333 (defun copy-to-buffer (buffer start end)
5334 "Copy to specified buffer the text of the region.
5335 It is inserted into that buffer, replacing existing text there.
5337 When calling from a program, give three arguments:
5338 BUFFER (or buffer name), START and END.
5339 START and END specify the portion of the current buffer to be copied."
5340 (interactive "BCopy to buffer: \nr")
5341 (let ((oldbuf (current-buffer)))
5342 (with-current-buffer (get-buffer-create buffer)
5343 (barf-if-buffer-read-only)
5344 (erase-buffer)
5345 (save-excursion
5346 (insert-buffer-substring oldbuf start end)))))
5348 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5350 (defvar activate-mark-hook nil
5351 "Hook run when the mark becomes active.
5352 It is also run at the end of a command, if the mark is active and
5353 it is possible that the region may have changed.")
5355 (defvar deactivate-mark-hook nil
5356 "Hook run when the mark becomes inactive.")
5358 (defun mark (&optional force)
5359 "Return this buffer's mark value as integer, or nil if never set.
5361 In Transient Mark mode, this function signals an error if
5362 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5363 or the argument FORCE is non-nil, it disregards whether the mark
5364 is active, and returns an integer or nil in the usual way.
5366 If you are using this in an editing command, you are most likely making
5367 a mistake; see the documentation of `set-mark'."
5368 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5369 (marker-position (mark-marker))
5370 (signal 'mark-inactive nil)))
5372 ;; Behind display-selections-p.
5374 (defun deactivate-mark (&optional force)
5375 "Deactivate the mark.
5376 If Transient Mark mode is disabled, this function normally does
5377 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5379 Deactivating the mark sets `mark-active' to nil, updates the
5380 primary selection according to `select-active-regions', and runs
5381 `deactivate-mark-hook'.
5383 If Transient Mark mode was temporarily enabled, reset the value
5384 of the variable `transient-mark-mode'; if this causes Transient
5385 Mark mode to be disabled, don't change `mark-active' to nil or
5386 run `deactivate-mark-hook'."
5387 (when (or (region-active-p) force)
5388 (when (and (if (eq select-active-regions 'only)
5389 (eq (car-safe transient-mark-mode) 'only)
5390 select-active-regions)
5391 (region-active-p)
5392 (display-selections-p))
5393 ;; The var `saved-region-selection', if non-nil, is the text in
5394 ;; the region prior to the last command modifying the buffer.
5395 ;; Set the selection to that, or to the current region.
5396 (cond (saved-region-selection
5397 (if (gui-backend-selection-owner-p 'PRIMARY)
5398 (gui-set-selection 'PRIMARY saved-region-selection))
5399 (setq saved-region-selection nil))
5400 ;; If another program has acquired the selection, region
5401 ;; deactivation should not clobber it (Bug#11772).
5402 ((and (/= (region-beginning) (region-end))
5403 (or (gui-backend-selection-owner-p 'PRIMARY)
5404 (null (gui-backend-selection-exists-p 'PRIMARY))))
5405 (gui-set-selection 'PRIMARY
5406 (funcall region-extract-function nil)))))
5407 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5408 (cond
5409 ((eq (car-safe transient-mark-mode) 'only)
5410 (setq transient-mark-mode (cdr transient-mark-mode))
5411 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5412 (kill-local-variable 'transient-mark-mode)))
5413 ((eq transient-mark-mode 'lambda)
5414 (kill-local-variable 'transient-mark-mode)))
5415 (setq mark-active nil)
5416 (run-hooks 'deactivate-mark-hook)
5417 (redisplay--update-region-highlight (selected-window))))
5419 (defun activate-mark (&optional no-tmm)
5420 "Activate the mark.
5421 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5422 (when (mark t)
5423 (unless (region-active-p)
5424 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5425 (setq mark-active t)
5426 (unless (or transient-mark-mode no-tmm)
5427 (setq-local transient-mark-mode 'lambda))
5428 (run-hooks 'activate-mark-hook))))
5430 (defun set-mark (pos)
5431 "Set this buffer's mark to POS. Don't use this function!
5432 That is to say, don't use this function unless you want
5433 the user to see that the mark has moved, and you want the previous
5434 mark position to be lost.
5436 Normally, when a new mark is set, the old one should go on the stack.
5437 This is why most applications should use `push-mark', not `set-mark'.
5439 Novice Emacs Lisp programmers often try to use the mark for the wrong
5440 purposes. The mark saves a location for the user's convenience.
5441 Most editing commands should not alter the mark.
5442 To remember a location for internal use in the Lisp program,
5443 store it in a Lisp variable. Example:
5445 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5446 (if pos
5447 (progn
5448 (set-marker (mark-marker) pos (current-buffer))
5449 (activate-mark 'no-tmm))
5450 ;; Normally we never clear mark-active except in Transient Mark mode.
5451 ;; But when we actually clear out the mark value too, we must
5452 ;; clear mark-active in any mode.
5453 (deactivate-mark t)
5454 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5455 ;; it should never be nil if the mark is nil.
5456 (setq mark-active nil)
5457 (set-marker (mark-marker) nil)))
5459 (defun save-mark-and-excursion--save ()
5460 (cons
5461 (let ((mark (mark-marker)))
5462 (and (marker-position mark) (copy-marker mark)))
5463 mark-active))
5465 (defun save-mark-and-excursion--restore (saved-mark-info)
5466 (let ((saved-mark (car saved-mark-info))
5467 (omark (marker-position (mark-marker)))
5468 (nmark nil)
5469 (saved-mark-active (cdr saved-mark-info)))
5470 ;; Mark marker
5471 (if (null saved-mark)
5472 (set-marker (mark-marker) nil)
5473 (setf nmark (marker-position saved-mark))
5474 (set-marker (mark-marker) nmark)
5475 (set-marker saved-mark nil))
5476 ;; Mark active
5477 (let ((cur-mark-active mark-active))
5478 (setq mark-active saved-mark-active)
5479 ;; If mark is active now, and either was not active or was at a
5480 ;; different place, run the activate hook.
5481 (if saved-mark-active
5482 (when (or (not cur-mark-active)
5483 (not (eq omark nmark)))
5484 (run-hooks 'activate-mark-hook))
5485 ;; If mark has ceased to be active, run deactivate hook.
5486 (when cur-mark-active
5487 (run-hooks 'deactivate-mark-hook))))))
5489 (defmacro save-mark-and-excursion (&rest body)
5490 "Like `save-excursion', but also save and restore the mark state.
5491 This macro does what `save-excursion' did before Emacs 25.1."
5492 (declare (indent 0) (debug t))
5493 (let ((saved-marker-sym (make-symbol "saved-marker")))
5494 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5495 (unwind-protect
5496 (save-excursion ,@body)
5497 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5499 (defcustom use-empty-active-region nil
5500 "Whether \"region-aware\" commands should act on empty regions.
5501 If nil, region-aware commands treat the empty region as inactive.
5502 If non-nil, region-aware commands treat the region as active as
5503 long as the mark is active, even if the region is empty.
5505 Region-aware commands are those that act on the region if it is
5506 active and Transient Mark mode is enabled, and on the text near
5507 point otherwise."
5508 :type 'boolean
5509 :version "23.1"
5510 :group 'editing-basics)
5512 (defun use-region-p ()
5513 "Return t if the region is active and it is appropriate to act on it.
5514 This is used by commands that act specially on the region under
5515 Transient Mark mode.
5517 The return value is t if Transient Mark mode is enabled and the
5518 mark is active; furthermore, if `use-empty-active-region' is nil,
5519 the region must not be empty. Otherwise, the return value is nil.
5521 For some commands, it may be appropriate to ignore the value of
5522 `use-empty-active-region'; in that case, use `region-active-p'."
5523 (and (region-active-p)
5524 (or use-empty-active-region (> (region-end) (region-beginning)))))
5526 (defun region-active-p ()
5527 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5529 Some commands act specially on the region when Transient Mark
5530 mode is enabled. Usually, such commands should use
5531 `use-region-p' instead of this function, because `use-region-p'
5532 also checks the value of `use-empty-active-region'."
5533 (and transient-mark-mode mark-active
5534 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5535 ;; without the mark being set (e.g. bug#17324). We really should fix
5536 ;; that problem, but in the mean time, let's make sure we don't say the
5537 ;; region is active when there's no mark.
5538 (progn (cl-assert (mark)) t)))
5540 (defun region-bounds ()
5541 "Return the boundaries of the region as a pair of positions.
5542 Value is a list of cons cells of the form (START . END)."
5543 (funcall region-extract-function 'bounds))
5545 (defun region-noncontiguous-p ()
5546 "Return non-nil if the region contains several pieces.
5547 An example is a rectangular region handled as a list of
5548 separate contiguous regions for each line."
5549 (> (length (region-bounds)) 1))
5551 (defvar redisplay-unhighlight-region-function
5552 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5554 (defvar redisplay-highlight-region-function
5555 (lambda (start end window rol)
5556 (if (not (overlayp rol))
5557 (let ((nrol (make-overlay start end)))
5558 (funcall redisplay-unhighlight-region-function rol)
5559 (overlay-put nrol 'window window)
5560 (overlay-put nrol 'face 'region)
5561 ;; Normal priority so that a large region doesn't hide all the
5562 ;; overlays within it, but high secondary priority so that if it
5563 ;; ends/starts in the middle of a small overlay, that small overlay
5564 ;; won't hide the region's boundaries.
5565 (overlay-put nrol 'priority '(nil . 100))
5566 nrol)
5567 (unless (and (eq (overlay-buffer rol) (current-buffer))
5568 (eq (overlay-start rol) start)
5569 (eq (overlay-end rol) end))
5570 (move-overlay rol start end (current-buffer)))
5571 rol)))
5573 (defun redisplay--update-region-highlight (window)
5574 (let ((rol (window-parameter window 'internal-region-overlay)))
5575 (if (not (and (region-active-p)
5576 (or highlight-nonselected-windows
5577 (eq window (selected-window))
5578 (and (window-minibuffer-p)
5579 (eq window (minibuffer-selected-window))))))
5580 (funcall redisplay-unhighlight-region-function rol)
5581 (let* ((pt (window-point window))
5582 (mark (mark))
5583 (start (min pt mark))
5584 (end (max pt mark))
5585 (new
5586 (funcall redisplay-highlight-region-function
5587 start end window rol)))
5588 (unless (equal new rol)
5589 (set-window-parameter window 'internal-region-overlay
5590 new))))))
5592 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5593 "Hook run just before redisplay.
5594 It is called in each window that is to be redisplayed. It takes one argument,
5595 which is the window that will be redisplayed. When run, the `current-buffer'
5596 is set to the buffer displayed in that window.")
5598 (defun redisplay--pre-redisplay-functions (windows)
5599 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5600 (if (null windows)
5601 (with-current-buffer (window-buffer (selected-window))
5602 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5603 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5604 (with-current-buffer (window-buffer win)
5605 (run-hook-with-args 'pre-redisplay-functions win))))))
5607 (add-function :before pre-redisplay-function
5608 #'redisplay--pre-redisplay-functions)
5611 (defvar-local mark-ring nil
5612 "The list of former marks of the current buffer, most recent first.")
5613 (put 'mark-ring 'permanent-local t)
5615 (defcustom mark-ring-max 16
5616 "Maximum size of mark ring. Start discarding off end if gets this big."
5617 :type 'integer
5618 :group 'editing-basics)
5620 (defvar global-mark-ring nil
5621 "The list of saved global marks, most recent first.")
5623 (defcustom global-mark-ring-max 16
5624 "Maximum size of global mark ring. \
5625 Start discarding off end if gets this big."
5626 :type 'integer
5627 :group 'editing-basics)
5629 (defun pop-to-mark-command ()
5630 "Jump to mark, and pop a new position for mark off the ring.
5631 \(Does not affect global mark ring)."
5632 (interactive)
5633 (if (null (mark t))
5634 (user-error "No mark set in this buffer")
5635 (if (= (point) (mark t))
5636 (message "Mark popped"))
5637 (goto-char (mark t))
5638 (pop-mark)))
5640 (defun push-mark-command (arg &optional nomsg)
5641 "Set mark at where point is.
5642 If no prefix ARG and mark is already set there, just activate it.
5643 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5644 (interactive "P")
5645 (let ((mark (mark t)))
5646 (if (or arg (null mark) (/= mark (point)))
5647 (push-mark nil nomsg t)
5648 (activate-mark 'no-tmm)
5649 (unless nomsg
5650 (message "Mark activated")))))
5652 (defcustom set-mark-command-repeat-pop nil
5653 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5654 That means that C-u \\[set-mark-command] \\[set-mark-command]
5655 will pop the mark twice, and
5656 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5657 will pop the mark three times.
5659 A value of nil means \\[set-mark-command]'s behavior does not change
5660 after C-u \\[set-mark-command]."
5661 :type 'boolean
5662 :group 'editing-basics)
5664 (defun set-mark-command (arg)
5665 "Set the mark where point is, and activate it; or jump to the mark.
5666 Setting the mark also alters the region, which is the text
5667 between point and mark; this is the closest equivalent in
5668 Emacs to what some editors call the \"selection\".
5670 With no prefix argument, set the mark at point, and push the
5671 old mark position on local mark ring. Also push the new mark on
5672 global mark ring, if the previous mark was set in another buffer.
5674 When Transient Mark Mode is off, immediately repeating this
5675 command activates `transient-mark-mode' temporarily.
5677 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5678 jump to the mark, and set the mark from
5679 position popped off the local mark ring (this does not affect the global
5680 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5681 mark ring (see `pop-global-mark').
5683 If `set-mark-command-repeat-pop' is non-nil, repeating
5684 the \\[set-mark-command] command with no prefix argument pops the next position
5685 off the local (or global) mark ring and jumps there.
5687 With \\[universal-argument] \\[universal-argument] as prefix
5688 argument, unconditionally set mark where point is, even if
5689 `set-mark-command-repeat-pop' is non-nil.
5691 Novice Emacs Lisp programmers often try to use the mark for the wrong
5692 purposes. See the documentation of `set-mark' for more information."
5693 (interactive "P")
5694 (cond ((eq transient-mark-mode 'lambda)
5695 (kill-local-variable 'transient-mark-mode))
5696 ((eq (car-safe transient-mark-mode) 'only)
5697 (deactivate-mark)))
5698 (cond
5699 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5700 (push-mark-command nil))
5701 ((not (eq this-command 'set-mark-command))
5702 (if arg
5703 (pop-to-mark-command)
5704 (push-mark-command t)))
5705 ((and set-mark-command-repeat-pop
5706 (eq last-command 'pop-global-mark)
5707 (not arg))
5708 (setq this-command 'pop-global-mark)
5709 (pop-global-mark))
5710 ((or (and set-mark-command-repeat-pop
5711 (eq last-command 'pop-to-mark-command))
5712 arg)
5713 (setq this-command 'pop-to-mark-command)
5714 (pop-to-mark-command))
5715 ((eq last-command 'set-mark-command)
5716 (if (region-active-p)
5717 (progn
5718 (deactivate-mark)
5719 (message "Mark deactivated"))
5720 (activate-mark)
5721 (message "Mark activated")))
5723 (push-mark-command nil))))
5725 (defun push-mark (&optional location nomsg activate)
5726 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5727 If the last global mark pushed was not in the current buffer,
5728 also push LOCATION on the global mark ring.
5729 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5731 Novice Emacs Lisp programmers often try to use the mark for the wrong
5732 purposes. See the documentation of `set-mark' for more information.
5734 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5735 (unless (null (mark t))
5736 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5737 (when (> (length mark-ring) mark-ring-max)
5738 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5739 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5740 (set-marker (mark-marker) (or location (point)) (current-buffer))
5741 ;; Now push the mark on the global mark ring.
5742 (if (and global-mark-ring
5743 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5744 ;; The last global mark pushed was in this same buffer.
5745 ;; Don't push another one.
5747 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5748 (when (> (length global-mark-ring) global-mark-ring-max)
5749 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5750 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5751 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5752 (message "Mark set"))
5753 (if (or activate (not transient-mark-mode))
5754 (set-mark (mark t)))
5755 nil)
5757 (defun pop-mark ()
5758 "Pop off mark ring into the buffer's actual mark.
5759 Does not set point. Does nothing if mark ring is empty."
5760 (when mark-ring
5761 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5762 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5763 (move-marker (car mark-ring) nil)
5764 (if (null (mark t)) (ding))
5765 (setq mark-ring (cdr mark-ring)))
5766 (deactivate-mark))
5768 (define-obsolete-function-alias
5769 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5770 (defun exchange-point-and-mark (&optional arg)
5771 "Put the mark where point is now, and point where the mark is now.
5772 This command works even when the mark is not active,
5773 and it reactivates the mark.
5775 If Transient Mark mode is on, a prefix ARG deactivates the mark
5776 if it is active, and otherwise avoids reactivating it. If
5777 Transient Mark mode is off, a prefix ARG enables Transient Mark
5778 mode temporarily."
5779 (interactive "P")
5780 (let ((omark (mark t))
5781 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5782 (if (null omark)
5783 (user-error "No mark set in this buffer"))
5784 (set-mark (point))
5785 (goto-char omark)
5786 (cond (temp-highlight
5787 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5788 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5789 (not (or arg (region-active-p))))
5790 (deactivate-mark))
5791 (t (activate-mark)))
5792 nil))
5794 (defcustom shift-select-mode t
5795 "When non-nil, shifted motion keys activate the mark momentarily.
5797 While the mark is activated in this way, any shift-translated point
5798 motion key extends the region, and if Transient Mark mode was off, it
5799 is temporarily turned on. Furthermore, the mark will be deactivated
5800 by any subsequent point motion key that was not shift-translated, or
5801 by any action that normally deactivates the mark in Transient Mark mode.
5803 See `this-command-keys-shift-translated' for the meaning of
5804 shift-translation."
5805 :type 'boolean
5806 :group 'editing-basics)
5808 (defun handle-shift-selection ()
5809 "Activate/deactivate mark depending on invocation thru shift translation.
5810 This function is called by `call-interactively' when a command
5811 with a `^' character in its `interactive' spec is invoked, before
5812 running the command itself.
5814 If `shift-select-mode' is enabled and the command was invoked
5815 through shift translation, set the mark and activate the region
5816 temporarily, unless it was already set in this way. See
5817 `this-command-keys-shift-translated' for the meaning of shift
5818 translation.
5820 Otherwise, if the region has been activated temporarily,
5821 deactivate it, and restore the variable `transient-mark-mode' to
5822 its earlier value."
5823 (cond ((and shift-select-mode this-command-keys-shift-translated)
5824 (unless (and mark-active
5825 (eq (car-safe transient-mark-mode) 'only))
5826 (setq-local transient-mark-mode
5827 (cons 'only
5828 (unless (eq transient-mark-mode 'lambda)
5829 transient-mark-mode)))
5830 (push-mark nil nil t)))
5831 ((eq (car-safe transient-mark-mode) 'only)
5832 (setq transient-mark-mode (cdr transient-mark-mode))
5833 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5834 (kill-local-variable 'transient-mark-mode))
5835 (deactivate-mark))))
5837 (define-minor-mode transient-mark-mode
5838 "Toggle Transient Mark mode.
5839 With a prefix argument ARG, enable Transient Mark mode if ARG is
5840 positive, and disable it otherwise. If called from Lisp, enable
5841 Transient Mark mode if ARG is omitted or nil.
5843 Transient Mark mode is a global minor mode. When enabled, the
5844 region is highlighted with the `region' face whenever the mark
5845 is active. The mark is \"deactivated\" by changing the buffer,
5846 and after certain other operations that set the mark but whose
5847 main purpose is something else--for example, incremental search,
5848 \\[beginning-of-buffer], and \\[end-of-buffer].
5850 You can also deactivate the mark by typing \\[keyboard-quit] or
5851 \\[keyboard-escape-quit].
5853 Many commands change their behavior when Transient Mark mode is
5854 in effect and the mark is active, by acting on the region instead
5855 of their usual default part of the buffer's text. Examples of
5856 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5857 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5858 To see the documentation of commands which are sensitive to the
5859 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5860 or \"mark.*active\" at the prompt."
5861 :global t
5862 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5863 :variable (default-value 'transient-mark-mode))
5865 (defvar widen-automatically t
5866 "Non-nil means it is ok for commands to call `widen' when they want to.
5867 Some commands will do this in order to go to positions outside
5868 the current accessible part of the buffer.
5870 If `widen-automatically' is nil, these commands will do something else
5871 as a fallback, and won't change the buffer bounds.")
5873 (defvar non-essential nil
5874 "Whether the currently executing code is performing an essential task.
5875 This variable should be non-nil only when running code which should not
5876 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5877 user for a password when we are simply scanning a set of files in the
5878 background or displaying possible completions before the user even asked
5879 for it.")
5881 (defun pop-global-mark ()
5882 "Pop off global mark ring and jump to the top location."
5883 (interactive)
5884 ;; Pop entries which refer to non-existent buffers.
5885 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5886 (setq global-mark-ring (cdr global-mark-ring)))
5887 (or global-mark-ring
5888 (error "No global mark set"))
5889 (let* ((marker (car global-mark-ring))
5890 (buffer (marker-buffer marker))
5891 (position (marker-position marker)))
5892 (setq global-mark-ring (nconc (cdr global-mark-ring)
5893 (list (car global-mark-ring))))
5894 (set-buffer buffer)
5895 (or (and (>= position (point-min))
5896 (<= position (point-max)))
5897 (if widen-automatically
5898 (widen)
5899 (error "Global mark position is outside accessible part of buffer")))
5900 (goto-char position)
5901 (switch-to-buffer buffer)))
5903 (defcustom next-line-add-newlines nil
5904 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5905 :type 'boolean
5906 :version "21.1"
5907 :group 'editing-basics)
5909 (defun next-line (&optional arg try-vscroll)
5910 "Move cursor vertically down ARG lines.
5911 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5912 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5913 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5914 function will not vscroll.
5916 ARG defaults to 1.
5918 If there is no character in the target line exactly under the current column,
5919 the cursor is positioned after the character in that line which spans this
5920 column, or at the end of the line if it is not long enough.
5921 If there is no line in the buffer after this one, behavior depends on the
5922 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5923 to create a line, and moves the cursor to that line. Otherwise it moves the
5924 cursor to the end of the buffer.
5926 If the variable `line-move-visual' is non-nil, this command moves
5927 by display lines. Otherwise, it moves by buffer lines, without
5928 taking variable-width characters or continued lines into account.
5929 See \\[next-logical-line] for a command that always moves by buffer lines.
5931 The command \\[set-goal-column] can be used to create
5932 a semipermanent goal column for this command.
5933 Then instead of trying to move exactly vertically (or as close as possible),
5934 this command moves to the specified goal column (or as close as possible).
5935 The goal column is stored in the variable `goal-column', which is nil
5936 when there is no goal column. Note that setting `goal-column'
5937 overrides `line-move-visual' and causes this command to move by buffer
5938 lines rather than by display lines."
5939 (declare (interactive-only forward-line))
5940 (interactive "^p\np")
5941 (or arg (setq arg 1))
5942 (if (and next-line-add-newlines (= arg 1))
5943 (if (save-excursion (end-of-line) (eobp))
5944 ;; When adding a newline, don't expand an abbrev.
5945 (let ((abbrev-mode nil))
5946 (end-of-line)
5947 (insert (if use-hard-newlines hard-newline "\n")))
5948 (line-move arg nil nil try-vscroll))
5949 (if (called-interactively-p 'interactive)
5950 (condition-case err
5951 (line-move arg nil nil try-vscroll)
5952 ((beginning-of-buffer end-of-buffer)
5953 (signal (car err) (cdr err))))
5954 (line-move arg nil nil try-vscroll)))
5955 nil)
5957 (defun previous-line (&optional arg try-vscroll)
5958 "Move cursor vertically up ARG lines.
5959 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5960 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5961 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5962 function will not vscroll.
5964 ARG defaults to 1.
5966 If there is no character in the target line exactly over the current column,
5967 the cursor is positioned after the character in that line which spans this
5968 column, or at the end of the line if it is not long enough.
5970 If the variable `line-move-visual' is non-nil, this command moves
5971 by display lines. Otherwise, it moves by buffer lines, without
5972 taking variable-width characters or continued lines into account.
5973 See \\[previous-logical-line] for a command that always moves by buffer lines.
5975 The command \\[set-goal-column] can be used to create
5976 a semipermanent goal column for this command.
5977 Then instead of trying to move exactly vertically (or as close as possible),
5978 this command moves to the specified goal column (or as close as possible).
5979 The goal column is stored in the variable `goal-column', which is nil
5980 when there is no goal column. Note that setting `goal-column'
5981 overrides `line-move-visual' and causes this command to move by buffer
5982 lines rather than by display lines."
5983 (declare (interactive-only
5984 "use `forward-line' with negative argument instead."))
5985 (interactive "^p\np")
5986 (or arg (setq arg 1))
5987 (if (called-interactively-p 'interactive)
5988 (condition-case err
5989 (line-move (- arg) nil nil try-vscroll)
5990 ((beginning-of-buffer end-of-buffer)
5991 (signal (car err) (cdr err))))
5992 (line-move (- arg) nil nil try-vscroll))
5993 nil)
5995 (defcustom track-eol nil
5996 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5997 This means moving to the end of each line moved onto.
5998 The beginning of a blank line does not count as the end of a line.
5999 This has no effect when the variable `line-move-visual' is non-nil."
6000 :type 'boolean
6001 :group 'editing-basics)
6003 (defcustom goal-column nil
6004 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
6005 A non-nil setting overrides the variable `line-move-visual', which see."
6006 :type '(choice integer
6007 (const :tag "None" nil))
6008 :group 'editing-basics)
6009 (make-variable-buffer-local 'goal-column)
6011 (defvar temporary-goal-column 0
6012 "Current goal column for vertical motion.
6013 It is the column where point was at the start of the current run
6014 of vertical motion commands.
6016 When moving by visual lines via the function `line-move-visual', it is a cons
6017 cell (COL . HSCROLL), where COL is the x-position, in pixels,
6018 divided by the default column width, and HSCROLL is the number of
6019 columns by which window is scrolled from left margin.
6021 When the `track-eol' feature is doing its job, the value is
6022 `most-positive-fixnum'.")
6024 (defvar last--line-number-width 0
6025 "Last value of width used for displaying line numbers.
6026 Used internally by `line-move-visual'.")
6028 (defcustom line-move-ignore-invisible t
6029 "Non-nil means commands that move by lines ignore invisible newlines.
6030 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
6031 as if newlines that are invisible didn't exist, and count
6032 only visible newlines. Thus, moving across 2 newlines
6033 one of which is invisible will be counted as a one-line move.
6034 Also, a non-nil value causes invisible text to be ignored when
6035 counting columns for the purposes of keeping point in the same
6036 column by \\[next-line] and \\[previous-line].
6038 Outline mode sets this."
6039 :type 'boolean
6040 :group 'editing-basics)
6042 (defcustom line-move-visual t
6043 "When non-nil, `line-move' moves point by visual lines.
6044 This movement is based on where the cursor is displayed on the
6045 screen, instead of relying on buffer contents alone. It takes
6046 into account variable-width characters and line continuation.
6047 If nil, `line-move' moves point by logical lines.
6048 A non-nil setting of `goal-column' overrides the value of this variable
6049 and forces movement by logical lines.
6050 A window that is horizontally scrolled also forces movement by logical
6051 lines."
6052 :type 'boolean
6053 :group 'editing-basics
6054 :version "23.1")
6056 ;; Only used if display-graphic-p.
6057 (declare-function font-info "font.c" (name &optional frame))
6059 (defun default-font-height ()
6060 "Return the height in pixels of the current buffer's default face font.
6062 If the default font is remapped (see `face-remapping-alist'), the
6063 function returns the height of the remapped face."
6064 (let ((default-font (face-font 'default)))
6065 (cond
6066 ((and (display-multi-font-p)
6067 ;; Avoid calling font-info if the frame's default font was
6068 ;; not changed since the frame was created. That's because
6069 ;; font-info is expensive for some fonts, see bug #14838.
6070 (not (string= (frame-parameter nil 'font) default-font)))
6071 (aref (font-info default-font) 3))
6072 (t (frame-char-height)))))
6074 (defun default-font-width ()
6075 "Return the width in pixels of the current buffer's default face font.
6077 If the default font is remapped (see `face-remapping-alist'), the
6078 function returns the width of the remapped face."
6079 (let ((default-font (face-font 'default)))
6080 (cond
6081 ((and (display-multi-font-p)
6082 ;; Avoid calling font-info if the frame's default font was
6083 ;; not changed since the frame was created. That's because
6084 ;; font-info is expensive for some fonts, see bug #14838.
6085 (not (string= (frame-parameter nil 'font) default-font)))
6086 (let* ((info (font-info (face-font 'default)))
6087 (width (aref info 11)))
6088 (if (> width 0)
6089 width
6090 (aref info 10))))
6091 (t (frame-char-width)))))
6093 (defun default-line-height ()
6094 "Return the pixel height of current buffer's default-face text line.
6096 The value includes `line-spacing', if any, defined for the buffer
6097 or the frame."
6098 (let ((dfh (default-font-height))
6099 (lsp (if (display-graphic-p)
6100 (or line-spacing
6101 (default-value 'line-spacing)
6102 (frame-parameter nil 'line-spacing)
6104 0)))
6105 (if (floatp lsp)
6106 (setq lsp (truncate (* (frame-char-height) lsp))))
6107 (+ dfh lsp)))
6109 (defun window-screen-lines ()
6110 "Return the number of screen lines in the text area of the selected window.
6112 This is different from `window-text-height' in that this function counts
6113 lines in units of the height of the font used by the default face displayed
6114 in the window, not in units of the frame's default font, and also accounts
6115 for `line-spacing', if any, defined for the window's buffer or frame.
6117 The value is a floating-point number."
6118 (let ((edges (window-inside-pixel-edges))
6119 (dlh (default-line-height)))
6120 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
6122 ;; Returns non-nil if partial move was done.
6123 (defun line-move-partial (arg noerror &optional _to-end)
6124 (if (< arg 0)
6125 ;; Move backward (up).
6126 ;; If already vscrolled, reduce vscroll
6127 (let ((vs (window-vscroll nil t))
6128 (dlh (default-line-height)))
6129 (when (> vs dlh)
6130 (set-window-vscroll nil (- vs dlh) t)))
6132 ;; Move forward (down).
6133 (let* ((lh (window-line-height -1))
6134 (rowh (car lh))
6135 (vpos (nth 1 lh))
6136 (ypos (nth 2 lh))
6137 (rbot (nth 3 lh))
6138 (this-lh (window-line-height))
6139 (this-height (car this-lh))
6140 (this-ypos (nth 2 this-lh))
6141 (dlh (default-line-height))
6142 (wslines (window-screen-lines))
6143 (edges (window-inside-pixel-edges))
6144 (winh (- (nth 3 edges) (nth 1 edges) 1))
6145 py vs last-line)
6146 (if (> (mod wslines 1.0) 0.0)
6147 (setq wslines (round (+ wslines 0.5))))
6148 (when (or (null lh)
6149 (>= rbot dlh)
6150 (<= ypos (- dlh))
6151 (null this-lh)
6152 (<= this-ypos (- dlh)))
6153 (unless lh
6154 (let ((wend (pos-visible-in-window-p t nil t)))
6155 (setq rbot (nth 3 wend)
6156 rowh (nth 4 wend)
6157 vpos (nth 5 wend))))
6158 (unless this-lh
6159 (let ((wstart (pos-visible-in-window-p nil nil t)))
6160 (setq this-ypos (nth 2 wstart)
6161 this-height (nth 4 wstart))))
6162 (setq py
6163 (or (nth 1 this-lh)
6164 (let ((ppos (posn-at-point))
6165 col-row)
6166 (setq col-row (posn-actual-col-row ppos))
6167 (if col-row
6168 (- (cdr col-row) (window-vscroll))
6169 (cdr (posn-col-row ppos))))))
6170 ;; VPOS > 0 means the last line is only partially visible.
6171 ;; But if the part that is visible is at least as tall as the
6172 ;; default font, that means the line is actually fully
6173 ;; readable, and something like line-spacing is hidden. So in
6174 ;; that case we accept the last line in the window as still
6175 ;; visible, and consider the margin as starting one line
6176 ;; later.
6177 (if (and vpos (> vpos 0))
6178 (if (and rowh
6179 (>= rowh (default-font-height))
6180 (< rowh dlh))
6181 (setq last-line (min (- wslines scroll-margin) vpos))
6182 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6183 (cond
6184 ;; If last line of window is fully visible, and vscrolling
6185 ;; more would make this line invisible, move forward.
6186 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6187 (null this-height)
6188 (<= this-height dlh))
6189 (or (null rbot) (= rbot 0)))
6190 nil)
6191 ;; If cursor is not in the bottom scroll margin, and the
6192 ;; current line is not too tall, move forward.
6193 ((and (or (null this-height) (<= this-height winh))
6194 vpos
6195 (> vpos 0)
6196 (< py last-line))
6197 nil)
6198 ;; When already vscrolled, we vscroll some more if we can,
6199 ;; or clear vscroll and move forward at end of tall image.
6200 ((> vs 0)
6201 (when (or (and rbot (> rbot 0))
6202 (and this-height (> this-height dlh)))
6203 (set-window-vscroll nil (+ vs dlh) t)))
6204 ;; If cursor just entered the bottom scroll margin, move forward,
6205 ;; but also optionally vscroll one line so redisplay won't recenter.
6206 ((and vpos
6207 (> vpos 0)
6208 (= py last-line))
6209 ;; Don't vscroll if the partially-visible line at window
6210 ;; bottom is not too tall (a.k.a. "just one more text
6211 ;; line"): in that case, we do want redisplay to behave
6212 ;; normally, i.e. recenter or whatever.
6214 ;; Note: ROWH + RBOT from the value returned by
6215 ;; pos-visible-in-window-p give the total height of the
6216 ;; partially-visible glyph row at the end of the window. As
6217 ;; we are dealing with floats, we disregard sub-pixel
6218 ;; discrepancies between that and DLH.
6219 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6220 (set-window-vscroll nil dlh t))
6221 (line-move-1 arg noerror)
6223 ;; If there are lines above the last line, scroll-up one line.
6224 ((and vpos (> vpos 0))
6225 (scroll-up 1)
6227 ;; Finally, start vscroll.
6229 (set-window-vscroll nil dlh t)))))))
6232 ;; This is like line-move-1 except that it also performs
6233 ;; vertical scrolling of tall images if appropriate.
6234 ;; That is not really a clean thing to do, since it mixes
6235 ;; scrolling with cursor motion. But so far we don't have
6236 ;; a cleaner solution to the problem of making C-n do something
6237 ;; useful given a tall image.
6238 (defun line-move (arg &optional noerror _to-end try-vscroll)
6239 "Move forward ARG lines.
6240 If NOERROR, don't signal an error if we can't move ARG lines.
6241 TO-END is unused.
6242 TRY-VSCROLL controls whether to vscroll tall lines: if either
6243 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6244 not vscroll."
6245 (if noninteractive
6246 (line-move-1 arg noerror)
6247 (unless (and auto-window-vscroll try-vscroll
6248 ;; Only vscroll for single line moves
6249 (= (abs arg) 1)
6250 ;; Under scroll-conservatively, the display engine
6251 ;; does this better.
6252 (zerop scroll-conservatively)
6253 ;; But don't vscroll in a keyboard macro.
6254 (not defining-kbd-macro)
6255 (not executing-kbd-macro)
6256 (line-move-partial arg noerror))
6257 (set-window-vscroll nil 0 t)
6258 (if (and line-move-visual
6259 ;; Display-based column are incompatible with goal-column.
6260 (not goal-column)
6261 ;; When the text in the window is scrolled to the left,
6262 ;; display-based motion doesn't make sense (because each
6263 ;; logical line occupies exactly one screen line).
6264 (not (> (window-hscroll) 0))
6265 ;; Likewise when the text _was_ scrolled to the left
6266 ;; when the current run of vertical motion commands
6267 ;; started.
6268 (not (and (memq last-command
6269 `(next-line previous-line ,this-command))
6270 auto-hscroll-mode
6271 (numberp temporary-goal-column)
6272 (>= temporary-goal-column
6273 (- (window-width) hscroll-margin)))))
6274 (prog1 (line-move-visual arg noerror)
6275 ;; If we moved into a tall line, set vscroll to make
6276 ;; scrolling through tall images more smooth.
6277 (let ((lh (line-pixel-height))
6278 (edges (window-inside-pixel-edges))
6279 (dlh (default-line-height))
6280 winh)
6281 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6282 (if (and (< arg 0)
6283 (< (point) (window-start))
6284 (> lh winh))
6285 (set-window-vscroll
6287 (- lh dlh) t))))
6288 (line-move-1 arg noerror)))))
6290 ;; Display-based alternative to line-move-1.
6291 ;; Arg says how many lines to move. The value is t if we can move the
6292 ;; specified number of lines.
6293 (defun line-move-visual (arg &optional noerror)
6294 "Move ARG lines forward.
6295 If NOERROR, don't signal an error if we can't move that many lines."
6296 (let ((opoint (point))
6297 (hscroll (window-hscroll))
6298 (lnum-width (line-number-display-width t))
6299 target-hscroll)
6300 ;; Check if the previous command was a line-motion command, or if
6301 ;; we were called from some other command.
6302 (if (and (consp temporary-goal-column)
6303 (memq last-command `(next-line previous-line ,this-command)))
6304 ;; If so, there's no need to reset `temporary-goal-column',
6305 ;; but we may need to hscroll.
6306 (progn
6307 (if (or (/= (cdr temporary-goal-column) hscroll)
6308 (> (cdr temporary-goal-column) 0))
6309 (setq target-hscroll (cdr temporary-goal-column)))
6310 ;; Update the COLUMN part of temporary-goal-column if the
6311 ;; line-number display changed its width since the last
6312 ;; time.
6313 (setq temporary-goal-column
6314 (cons (+ (car temporary-goal-column)
6315 (/ (float (- lnum-width last--line-number-width))
6316 (frame-char-width)))
6317 (cdr temporary-goal-column)))
6318 (setq last--line-number-width lnum-width))
6319 ;; Otherwise, we should reset `temporary-goal-column'.
6320 (let ((posn (posn-at-point))
6321 x-pos)
6322 (cond
6323 ;; Handle the `overflow-newline-into-fringe' case
6324 ;; (left-fringe is for the R2L case):
6325 ((memq (nth 1 posn) '(right-fringe left-fringe))
6326 (setq temporary-goal-column (cons (window-width) hscroll)))
6327 ((car (posn-x-y posn))
6328 (setq x-pos (car (posn-x-y posn)))
6329 ;; In R2L lines, the X pixel coordinate is measured from the
6330 ;; left edge of the window, but columns are still counted
6331 ;; from the logical-order beginning of the line, i.e. from
6332 ;; the right edge in this case. We need to adjust for that.
6333 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6334 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6335 (setq temporary-goal-column
6336 (cons (/ (float x-pos)
6337 (frame-char-width))
6338 hscroll)))
6339 (executing-kbd-macro
6340 ;; When we move beyond the first/last character visible in
6341 ;; the window, posn-at-point will return nil, so we need to
6342 ;; approximate the goal column as below.
6343 (setq temporary-goal-column
6344 (mod (current-column) (window-text-width)))))))
6345 (if target-hscroll
6346 (set-window-hscroll (selected-window) target-hscroll))
6347 ;; vertical-motion can move more than it was asked to if it moves
6348 ;; across display strings with newlines. We don't want to ring
6349 ;; the bell and announce beginning/end of buffer in that case.
6350 (or (and (or (and (>= arg 0)
6351 (>= (vertical-motion
6352 (cons (or goal-column
6353 (if (consp temporary-goal-column)
6354 (car temporary-goal-column)
6355 temporary-goal-column))
6356 arg))
6357 arg))
6358 (and (< arg 0)
6359 (<= (vertical-motion
6360 (cons (or goal-column
6361 (if (consp temporary-goal-column)
6362 (car temporary-goal-column)
6363 temporary-goal-column))
6364 arg))
6365 arg)))
6366 (or (>= arg 0)
6367 (/= (point) opoint)
6368 ;; If the goal column lies on a display string,
6369 ;; `vertical-motion' advances the cursor to the end
6370 ;; of the string. For arg < 0, this can cause the
6371 ;; cursor to get stuck. (Bug#3020).
6372 (= (vertical-motion arg) arg)))
6373 (unless noerror
6374 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6375 nil)))))
6377 ;; This is the guts of next-line and previous-line.
6378 ;; Arg says how many lines to move.
6379 ;; The value is t if we can move the specified number of lines.
6380 (defun line-move-1 (arg &optional noerror _to-end)
6381 ;; Don't run any point-motion hooks, and disregard intangibility,
6382 ;; for intermediate positions.
6383 (let ((inhibit-point-motion-hooks t)
6384 (opoint (point))
6385 (orig-arg arg))
6386 (if (consp temporary-goal-column)
6387 (setq temporary-goal-column (+ (car temporary-goal-column)
6388 (cdr temporary-goal-column))))
6389 (unwind-protect
6390 (progn
6391 (if (not (memq last-command '(next-line previous-line)))
6392 (setq temporary-goal-column
6393 (if (and track-eol (eolp)
6394 ;; Don't count beg of empty line as end of line
6395 ;; unless we just did explicit end-of-line.
6396 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6397 most-positive-fixnum
6398 (current-column))))
6400 (if (not (or (integerp selective-display)
6401 line-move-ignore-invisible))
6402 ;; Use just newline characters.
6403 ;; Set ARG to 0 if we move as many lines as requested.
6404 (or (if (> arg 0)
6405 (progn (if (> arg 1) (forward-line (1- arg)))
6406 ;; This way of moving forward ARG lines
6407 ;; verifies that we have a newline after the last one.
6408 ;; It doesn't get confused by intangible text.
6409 (end-of-line)
6410 (if (zerop (forward-line 1))
6411 (setq arg 0)))
6412 (and (zerop (forward-line arg))
6413 (bolp)
6414 (setq arg 0)))
6415 (unless noerror
6416 (signal (if (< arg 0)
6417 'beginning-of-buffer
6418 'end-of-buffer)
6419 nil)))
6420 ;; Move by arg lines, but ignore invisible ones.
6421 (let (done)
6422 (while (and (> arg 0) (not done))
6423 ;; If the following character is currently invisible,
6424 ;; skip all characters with that same `invisible' property value.
6425 (while (and (not (eobp)) (invisible-p (point)))
6426 (goto-char (next-char-property-change (point))))
6427 ;; Move a line.
6428 ;; We don't use `end-of-line', since we want to escape
6429 ;; from field boundaries occurring exactly at point.
6430 (goto-char (constrain-to-field
6431 (let ((inhibit-field-text-motion t))
6432 (line-end-position))
6433 (point) t t
6434 'inhibit-line-move-field-capture))
6435 ;; If there's no invisibility here, move over the newline.
6436 (cond
6437 ((eobp)
6438 (if (not noerror)
6439 (signal 'end-of-buffer nil)
6440 (setq done t)))
6441 ((and (> arg 1) ;; Use vertical-motion for last move
6442 (not (integerp selective-display))
6443 (not (invisible-p (point))))
6444 ;; We avoid vertical-motion when possible
6445 ;; because that has to fontify.
6446 (forward-line 1))
6447 ;; Otherwise move a more sophisticated way.
6448 ((zerop (vertical-motion 1))
6449 (if (not noerror)
6450 (signal 'end-of-buffer nil)
6451 (setq done t))))
6452 (unless done
6453 (setq arg (1- arg))))
6454 ;; The logic of this is the same as the loop above,
6455 ;; it just goes in the other direction.
6456 (while (and (< arg 0) (not done))
6457 ;; For completely consistency with the forward-motion
6458 ;; case, we should call beginning-of-line here.
6459 ;; However, if point is inside a field and on a
6460 ;; continued line, the call to (vertical-motion -1)
6461 ;; below won't move us back far enough; then we return
6462 ;; to the same column in line-move-finish, and point
6463 ;; gets stuck -- cyd
6464 (forward-line 0)
6465 (cond
6466 ((bobp)
6467 (if (not noerror)
6468 (signal 'beginning-of-buffer nil)
6469 (setq done t)))
6470 ((and (< arg -1) ;; Use vertical-motion for last move
6471 (not (integerp selective-display))
6472 (not (invisible-p (1- (point)))))
6473 (forward-line -1))
6474 ((zerop (vertical-motion -1))
6475 (if (not noerror)
6476 (signal 'beginning-of-buffer nil)
6477 (setq done t))))
6478 (unless done
6479 (setq arg (1+ arg))
6480 (while (and ;; Don't move over previous invis lines
6481 ;; if our target is the middle of this line.
6482 (or (zerop (or goal-column temporary-goal-column))
6483 (< arg 0))
6484 (not (bobp)) (invisible-p (1- (point))))
6485 (goto-char (previous-char-property-change (point))))))))
6486 ;; This is the value the function returns.
6487 (= arg 0))
6489 (cond ((> arg 0)
6490 ;; If we did not move down as far as desired, at least go
6491 ;; to end of line. Be sure to call point-entered and
6492 ;; point-left-hooks.
6493 (let* ((npoint (prog1 (line-end-position)
6494 (goto-char opoint)))
6495 (inhibit-point-motion-hooks nil))
6496 (goto-char npoint)))
6497 ((< arg 0)
6498 ;; If we did not move up as far as desired,
6499 ;; at least go to beginning of line.
6500 (let* ((npoint (prog1 (line-beginning-position)
6501 (goto-char opoint)))
6502 (inhibit-point-motion-hooks nil))
6503 (goto-char npoint)))
6505 (line-move-finish (or goal-column temporary-goal-column)
6506 opoint (> orig-arg 0)))))))
6508 (defun line-move-finish (column opoint forward)
6509 (let ((repeat t))
6510 (while repeat
6511 ;; Set REPEAT to t to repeat the whole thing.
6512 (setq repeat nil)
6514 (let (new
6515 (old (point))
6516 (line-beg (line-beginning-position))
6517 (line-end
6518 ;; Compute the end of the line
6519 ;; ignoring effectively invisible newlines.
6520 (save-excursion
6521 ;; Like end-of-line but ignores fields.
6522 (skip-chars-forward "^\n")
6523 (while (and (not (eobp)) (invisible-p (point)))
6524 (goto-char (next-char-property-change (point)))
6525 (skip-chars-forward "^\n"))
6526 (point))))
6528 ;; Move to the desired column.
6529 (if (and line-move-visual
6530 (not (or truncate-lines truncate-partial-width-windows)))
6531 ;; Under line-move-visual, goal-column should be
6532 ;; interpreted in units of the frame's canonical character
6533 ;; width, which is exactly what vertical-motion does.
6534 (vertical-motion (cons column 0))
6535 (line-move-to-column (truncate column)))
6537 ;; Corner case: suppose we start out in a field boundary in
6538 ;; the middle of a continued line. When we get to
6539 ;; line-move-finish, point is at the start of a new *screen*
6540 ;; line but the same text line; then line-move-to-column would
6541 ;; move us backwards. Test using C-n with point on the "x" in
6542 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6543 (and forward
6544 (< (point) old)
6545 (goto-char old))
6547 (setq new (point))
6549 ;; Process intangibility within a line.
6550 ;; With inhibit-point-motion-hooks bound to nil, a call to
6551 ;; goto-char moves point past intangible text.
6553 ;; However, inhibit-point-motion-hooks controls both the
6554 ;; intangibility and the point-entered/point-left hooks. The
6555 ;; following hack avoids calling the point-* hooks
6556 ;; unnecessarily. Note that we move *forward* past intangible
6557 ;; text when the initial and final points are the same.
6558 (goto-char new)
6559 (let ((inhibit-point-motion-hooks nil))
6560 (goto-char new)
6562 ;; If intangibility moves us to a different (later) place
6563 ;; in the same line, use that as the destination.
6564 (if (<= (point) line-end)
6565 (setq new (point))
6566 ;; If that position is "too late",
6567 ;; try the previous allowable position.
6568 ;; See if it is ok.
6569 (backward-char)
6570 (if (if forward
6571 ;; If going forward, don't accept the previous
6572 ;; allowable position if it is before the target line.
6573 (< line-beg (point))
6574 ;; If going backward, don't accept the previous
6575 ;; allowable position if it is still after the target line.
6576 (<= (point) line-end))
6577 (setq new (point))
6578 ;; As a last resort, use the end of the line.
6579 (setq new line-end))))
6581 ;; Now move to the updated destination, processing fields
6582 ;; as well as intangibility.
6583 (goto-char opoint)
6584 (let ((inhibit-point-motion-hooks nil))
6585 (goto-char
6586 ;; Ignore field boundaries if the initial and final
6587 ;; positions have the same `field' property, even if the
6588 ;; fields are non-contiguous. This seems to be "nicer"
6589 ;; behavior in many situations.
6590 (if (eq (get-char-property new 'field)
6591 (get-char-property opoint 'field))
6593 (constrain-to-field new opoint t t
6594 'inhibit-line-move-field-capture))))
6596 ;; If all this moved us to a different line,
6597 ;; retry everything within that new line.
6598 (when (or (< (point) line-beg) (> (point) line-end))
6599 ;; Repeat the intangibility and field processing.
6600 (setq repeat t))))))
6602 (defun line-move-to-column (col)
6603 "Try to find column COL, considering invisibility.
6604 This function works only in certain cases,
6605 because what we really need is for `move-to-column'
6606 and `current-column' to be able to ignore invisible text."
6607 (if (zerop col)
6608 (beginning-of-line)
6609 (move-to-column col))
6611 (when (and line-move-ignore-invisible
6612 (not (bolp)) (invisible-p (1- (point))))
6613 (let ((normal-location (point))
6614 (normal-column (current-column)))
6615 ;; If the following character is currently invisible,
6616 ;; skip all characters with that same `invisible' property value.
6617 (while (and (not (eobp))
6618 (invisible-p (point)))
6619 (goto-char (next-char-property-change (point))))
6620 ;; Have we advanced to a larger column position?
6621 (if (> (current-column) normal-column)
6622 ;; We have made some progress towards the desired column.
6623 ;; See if we can make any further progress.
6624 (line-move-to-column (+ (current-column) (- col normal-column)))
6625 ;; Otherwise, go to the place we originally found
6626 ;; and move back over invisible text.
6627 ;; that will get us to the same place on the screen
6628 ;; but with a more reasonable buffer position.
6629 (goto-char normal-location)
6630 (let ((line-beg
6631 ;; We want the real line beginning, so it's consistent
6632 ;; with bolp below, otherwise we might infloop.
6633 (let ((inhibit-field-text-motion t))
6634 (line-beginning-position))))
6635 (while (and (not (bolp)) (invisible-p (1- (point))))
6636 (goto-char (previous-char-property-change (point) line-beg))))))))
6638 (defun move-end-of-line (arg)
6639 "Move point to end of current line as displayed.
6640 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6641 If point reaches the beginning or end of buffer, it stops there.
6643 To ignore the effects of the `intangible' text or overlay
6644 property, bind `inhibit-point-motion-hooks' to t.
6645 If there is an image in the current line, this function
6646 disregards newlines that are part of the text on which the image
6647 rests."
6648 (interactive "^p")
6649 (or arg (setq arg 1))
6650 (let (done)
6651 (while (not done)
6652 (let ((newpos
6653 (save-excursion
6654 (let ((goal-column 0)
6655 (line-move-visual nil))
6656 (and (line-move arg t)
6657 ;; With bidi reordering, we may not be at bol,
6658 ;; so make sure we are.
6659 (skip-chars-backward "^\n")
6660 (not (bobp))
6661 (progn
6662 (while (and (not (bobp)) (invisible-p (1- (point))))
6663 (goto-char (previous-single-char-property-change
6664 (point) 'invisible)))
6665 (backward-char 1)))
6666 (point)))))
6667 (goto-char newpos)
6668 (if (and (> (point) newpos)
6669 (eq (preceding-char) ?\n))
6670 (backward-char 1)
6671 (if (and (> (point) newpos) (not (eobp))
6672 (not (eq (following-char) ?\n)))
6673 ;; If we skipped something intangible and now we're not
6674 ;; really at eol, keep going.
6675 (setq arg 1)
6676 (setq done t)))))))
6678 (defun move-beginning-of-line (arg)
6679 "Move point to beginning of current line as displayed.
6680 \(If there's an image in the line, this disregards newlines
6681 which are part of the text that the image rests on.)
6683 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6684 If point reaches the beginning or end of buffer, it stops there.
6685 \(But if the buffer doesn't end in a newline, it stops at the
6686 beginning of the last line.)
6687 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6688 (interactive "^p")
6689 (or arg (setq arg 1))
6691 (let ((orig (point))
6692 first-vis first-vis-field-value)
6694 ;; Move by lines, if ARG is not 1 (the default).
6695 (if (/= arg 1)
6696 (let ((line-move-visual nil))
6697 (line-move (1- arg) t)))
6699 ;; Move to beginning-of-line, ignoring fields and invisible text.
6700 (skip-chars-backward "^\n")
6701 (while (and (not (bobp)) (invisible-p (1- (point))))
6702 (goto-char (previous-char-property-change (point)))
6703 (skip-chars-backward "^\n"))
6705 ;; Now find first visible char in the line.
6706 (while (and (< (point) orig) (invisible-p (point)))
6707 (goto-char (next-char-property-change (point) orig)))
6708 (setq first-vis (point))
6710 ;; See if fields would stop us from reaching FIRST-VIS.
6711 (setq first-vis-field-value
6712 (constrain-to-field first-vis orig (/= arg 1) t nil))
6714 (goto-char (if (/= first-vis-field-value first-vis)
6715 ;; If yes, obey them.
6716 first-vis-field-value
6717 ;; Otherwise, move to START with attention to fields.
6718 ;; (It is possible that fields never matter in this case.)
6719 (constrain-to-field (point) orig
6720 (/= arg 1) t nil)))))
6723 ;; Many people have said they rarely use this feature, and often type
6724 ;; it by accident. Maybe it shouldn't even be on a key.
6725 (put 'set-goal-column 'disabled t)
6727 (defun set-goal-column (arg)
6728 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6729 Those commands will move to this position in the line moved to
6730 rather than trying to keep the same horizontal position.
6731 With a non-nil argument ARG, clears out the goal column
6732 so that \\[next-line] and \\[previous-line] resume vertical motion.
6733 The goal column is stored in the variable `goal-column'.
6734 This is a buffer-local setting."
6735 (interactive "P")
6736 (if arg
6737 (progn
6738 (setq goal-column nil)
6739 (message "No goal column"))
6740 (setq goal-column (current-column))
6741 ;; The older method below can be erroneous if `set-goal-column' is bound
6742 ;; to a sequence containing %
6743 ;;(message (substitute-command-keys
6744 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6745 ;;goal-column)
6746 (message "%s"
6747 (concat
6748 (format "Goal column %d " goal-column)
6749 (substitute-command-keys
6750 "(use \\[set-goal-column] with an arg to unset it)")))
6753 nil)
6755 ;;; Editing based on visual lines, as opposed to logical lines.
6757 (defun end-of-visual-line (&optional n)
6758 "Move point to end of current visual line.
6759 With argument N not nil or 1, move forward N - 1 visual lines first.
6760 If point reaches the beginning or end of buffer, it stops there.
6761 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6762 (interactive "^p")
6763 (or n (setq n 1))
6764 (if (/= n 1)
6765 (let ((line-move-visual t))
6766 (line-move (1- n) t)))
6767 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6768 ;; constrain to field boundaries, so we don't either.
6769 (vertical-motion (cons (window-width) 0)))
6771 (defun beginning-of-visual-line (&optional n)
6772 "Move point to beginning of current visual line.
6773 With argument N not nil or 1, move forward N - 1 visual lines first.
6774 If point reaches the beginning or end of buffer, it stops there.
6775 \(But if the buffer doesn't end in a newline, it stops at the
6776 beginning of the last visual line.)
6777 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6778 (interactive "^p")
6779 (or n (setq n 1))
6780 (let ((opoint (point)))
6781 (if (/= n 1)
6782 (let ((line-move-visual t))
6783 (line-move (1- n) t)))
6784 (vertical-motion 0)
6785 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6786 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6788 (defun kill-visual-line (&optional arg)
6789 "Kill the rest of the visual line.
6790 With prefix argument ARG, kill that many visual lines from point.
6791 If ARG is negative, kill visual lines backward.
6792 If ARG is zero, kill the text before point on the current visual
6793 line.
6795 If you want to append the killed line to the last killed text,
6796 use \\[append-next-kill] before \\[kill-line].
6798 If the buffer is read-only, Emacs will beep and refrain from deleting
6799 the line, but put the line in the kill ring anyway. This means that
6800 you can use this command to copy text from a read-only buffer.
6801 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6802 even beep.)"
6803 (interactive "P")
6804 ;; Like in `kill-line', it's better to move point to the other end
6805 ;; of the kill before killing.
6806 (let ((opoint (point))
6807 (kill-whole-line (and kill-whole-line (bolp))))
6808 (if arg
6809 (vertical-motion (prefix-numeric-value arg))
6810 (end-of-visual-line 1)
6811 (if (= (point) opoint)
6812 (vertical-motion 1)
6813 ;; Skip any trailing whitespace at the end of the visual line.
6814 ;; We used to do this only if `show-trailing-whitespace' is
6815 ;; nil, but that's wrong; the correct thing would be to check
6816 ;; whether the trailing whitespace is highlighted. But, it's
6817 ;; OK to just do this unconditionally.
6818 (skip-chars-forward " \t")))
6819 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6820 (1+ (point))
6821 (point)))))
6823 (defun next-logical-line (&optional arg try-vscroll)
6824 "Move cursor vertically down ARG lines.
6825 This is identical to `next-line', except that it always moves
6826 by logical lines instead of visual lines, ignoring the value of
6827 the variable `line-move-visual'."
6828 (interactive "^p\np")
6829 (let ((line-move-visual nil))
6830 (with-no-warnings
6831 (next-line arg try-vscroll))))
6833 (defun previous-logical-line (&optional arg try-vscroll)
6834 "Move cursor vertically up ARG lines.
6835 This is identical to `previous-line', except that it always moves
6836 by logical lines instead of visual lines, ignoring the value of
6837 the variable `line-move-visual'."
6838 (interactive "^p\np")
6839 (let ((line-move-visual nil))
6840 (with-no-warnings
6841 (previous-line arg try-vscroll))))
6843 (defgroup visual-line nil
6844 "Editing based on visual lines."
6845 :group 'convenience
6846 :version "23.1")
6848 (defvar visual-line-mode-map
6849 (let ((map (make-sparse-keymap)))
6850 (define-key map [remap kill-line] 'kill-visual-line)
6851 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6852 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6853 ;; These keybindings interfere with xterm function keys. Are
6854 ;; there any other suitable bindings?
6855 ;; (define-key map "\M-[" 'previous-logical-line)
6856 ;; (define-key map "\M-]" 'next-logical-line)
6857 map))
6859 (defcustom visual-line-fringe-indicators '(nil nil)
6860 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6861 The value should be a list of the form (LEFT RIGHT), where LEFT
6862 and RIGHT are symbols representing the bitmaps to display, to
6863 indicate wrapped lines, in the left and right fringes respectively.
6864 See also `fringe-indicator-alist'.
6865 The default is not to display fringe indicators for wrapped lines.
6866 This variable does not affect fringe indicators displayed for
6867 other purposes."
6868 :type '(list (choice (const :tag "Hide left indicator" nil)
6869 (const :tag "Left curly arrow" left-curly-arrow)
6870 (symbol :tag "Other bitmap"))
6871 (choice (const :tag "Hide right indicator" nil)
6872 (const :tag "Right curly arrow" right-curly-arrow)
6873 (symbol :tag "Other bitmap")))
6874 :set (lambda (symbol value)
6875 (dolist (buf (buffer-list))
6876 (with-current-buffer buf
6877 (when (and (boundp 'visual-line-mode)
6878 (symbol-value 'visual-line-mode))
6879 (setq fringe-indicator-alist
6880 (cons (cons 'continuation value)
6881 (assq-delete-all
6882 'continuation
6883 (copy-tree fringe-indicator-alist)))))))
6884 (set-default symbol value)))
6886 (defvar visual-line--saved-state nil)
6888 (define-minor-mode visual-line-mode
6889 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6890 Interactively, with a prefix argument, enable
6891 Visual Line mode if the prefix argument is positive,
6892 and disable it otherwise. If called from Lisp, toggle
6893 the mode if ARG is `toggle', disable the mode if ARG is
6894 a non-positive integer, and enable the mode otherwise
6895 \(including if ARG is omitted or nil or a positive integer).
6897 When Visual Line mode is enabled, `word-wrap' is turned on in
6898 this buffer, and simple editing commands are redefined to act on
6899 visual lines, not logical lines. See Info node `Visual Line
6900 Mode' for details."
6901 :keymap visual-line-mode-map
6902 :group 'visual-line
6903 :lighter " Wrap"
6904 (if visual-line-mode
6905 (progn
6906 (set (make-local-variable 'visual-line--saved-state) nil)
6907 ;; Save the local values of some variables, to be restored if
6908 ;; visual-line-mode is turned off.
6909 (dolist (var '(line-move-visual truncate-lines
6910 truncate-partial-width-windows
6911 word-wrap fringe-indicator-alist))
6912 (if (local-variable-p var)
6913 (push (cons var (symbol-value var))
6914 visual-line--saved-state)))
6915 (set (make-local-variable 'line-move-visual) t)
6916 (set (make-local-variable 'truncate-partial-width-windows) nil)
6917 (setq truncate-lines nil
6918 word-wrap t
6919 fringe-indicator-alist
6920 (cons (cons 'continuation visual-line-fringe-indicators)
6921 fringe-indicator-alist)))
6922 (kill-local-variable 'line-move-visual)
6923 (kill-local-variable 'word-wrap)
6924 (kill-local-variable 'truncate-lines)
6925 (kill-local-variable 'truncate-partial-width-windows)
6926 (kill-local-variable 'fringe-indicator-alist)
6927 (dolist (saved visual-line--saved-state)
6928 (set (make-local-variable (car saved)) (cdr saved)))
6929 (kill-local-variable 'visual-line--saved-state)))
6931 (defun turn-on-visual-line-mode ()
6932 (visual-line-mode 1))
6934 (define-globalized-minor-mode global-visual-line-mode
6935 visual-line-mode turn-on-visual-line-mode)
6938 (defun transpose-chars (arg)
6939 "Interchange characters around point, moving forward one character.
6940 With prefix arg ARG, effect is to take character before point
6941 and drag it forward past ARG other characters (backward if ARG negative).
6942 If no argument and at end of line, the previous two chars are exchanged."
6943 (interactive "*P")
6944 (when (and (null arg) (eolp) (not (bobp))
6945 (not (get-text-property (1- (point)) 'read-only)))
6946 (forward-char -1))
6947 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6949 (defun transpose-words (arg)
6950 "Interchange words around point, leaving point at end of them.
6951 With prefix arg ARG, effect is to take word before or around point
6952 and drag it forward past ARG other words (backward if ARG negative).
6953 If ARG is zero, the words around or after point and around or after mark
6954 are interchanged."
6955 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6956 (interactive "*p")
6957 (transpose-subr 'forward-word arg))
6959 (defun transpose-sexps (arg)
6960 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6961 Unlike `transpose-words', point must be between the two sexps and not
6962 in the middle of a sexp to be transposed.
6963 With non-zero prefix arg ARG, effect is to take the sexp before point
6964 and drag it forward past ARG other sexps (backward if ARG is negative).
6965 If ARG is zero, the sexps ending at or after point and at or after mark
6966 are interchanged."
6967 (interactive "*p")
6968 (transpose-subr
6969 (lambda (arg)
6970 ;; Here we should try to simulate the behavior of
6971 ;; (cons (progn (forward-sexp x) (point))
6972 ;; (progn (forward-sexp (- x)) (point)))
6973 ;; Except that we don't want to rely on the second forward-sexp
6974 ;; putting us back to where we want to be, since forward-sexp-function
6975 ;; might do funny things like infix-precedence.
6976 (if (if (> arg 0)
6977 (looking-at "\\sw\\|\\s_")
6978 (and (not (bobp))
6979 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6980 ;; Jumping over a symbol. We might be inside it, mind you.
6981 (progn (funcall (if (> arg 0)
6982 'skip-syntax-backward 'skip-syntax-forward)
6983 "w_")
6984 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6985 ;; Otherwise, we're between sexps. Take a step back before jumping
6986 ;; to make sure we'll obey the same precedence no matter which direction
6987 ;; we're going.
6988 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6989 (cons (save-excursion (forward-sexp arg) (point))
6990 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6991 (not (zerop (funcall (if (> arg 0)
6992 'skip-syntax-forward
6993 'skip-syntax-backward)
6994 ".")))))
6995 (point)))))
6996 arg 'special))
6998 (defun transpose-lines (arg)
6999 "Exchange current line and previous line, leaving point after both.
7000 With argument ARG, takes previous line and moves it past ARG lines.
7001 With argument 0, interchanges line point is in with line mark is in."
7002 (interactive "*p")
7003 (transpose-subr (function
7004 (lambda (arg)
7005 (if (> arg 0)
7006 (progn
7007 ;; Move forward over ARG lines,
7008 ;; but create newlines if necessary.
7009 (setq arg (forward-line arg))
7010 (if (/= (preceding-char) ?\n)
7011 (setq arg (1+ arg)))
7012 (if (> arg 0)
7013 (newline arg)))
7014 (forward-line arg))))
7015 arg))
7017 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
7018 ;; which seems inconsistent with the ARG /= 0 case.
7019 ;; FIXME document SPECIAL.
7020 (defun transpose-subr (mover arg &optional special)
7021 "Subroutine to do the work of transposing objects.
7022 Works for lines, sentences, paragraphs, etc. MOVER is a function that
7023 moves forward by units of the given object (e.g. forward-sentence,
7024 forward-paragraph). If ARG is zero, exchanges the current object
7025 with the one containing mark. If ARG is an integer, moves the
7026 current object past ARG following (if ARG is positive) or
7027 preceding (if ARG is negative) objects, leaving point after the
7028 current object."
7029 (let ((aux (if special mover
7030 (lambda (x)
7031 (cons (progn (funcall mover x) (point))
7032 (progn (funcall mover (- x)) (point))))))
7033 pos1 pos2)
7034 (cond
7035 ((= arg 0)
7036 (save-excursion
7037 (setq pos1 (funcall aux 1))
7038 (goto-char (or (mark) (error "No mark set in this buffer")))
7039 (setq pos2 (funcall aux 1))
7040 (transpose-subr-1 pos1 pos2))
7041 (exchange-point-and-mark))
7042 ((> arg 0)
7043 (setq pos1 (funcall aux -1))
7044 (setq pos2 (funcall aux arg))
7045 (transpose-subr-1 pos1 pos2)
7046 (goto-char (car pos2)))
7048 (setq pos1 (funcall aux -1))
7049 (goto-char (car pos1))
7050 (setq pos2 (funcall aux arg))
7051 (transpose-subr-1 pos1 pos2)
7052 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
7054 (defun transpose-subr-1 (pos1 pos2)
7055 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
7056 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
7057 (when (> (car pos1) (car pos2))
7058 (let ((swap pos1))
7059 (setq pos1 pos2 pos2 swap)))
7060 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
7061 (atomic-change-group
7062 ;; This sequence of insertions attempts to preserve marker
7063 ;; positions at the start and end of the transposed objects.
7064 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
7065 (len1 (- (cdr pos1) (car pos1)))
7066 (len2 (length word))
7067 (boundary (make-marker)))
7068 (set-marker boundary (car pos2))
7069 (goto-char (cdr pos1))
7070 (insert-before-markers word)
7071 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
7072 (goto-char boundary)
7073 (insert word)
7074 (goto-char (+ boundary len1))
7075 (delete-region (point) (+ (point) len2))
7076 (set-marker boundary nil))))
7078 (defun backward-word (&optional arg)
7079 "Move backward until encountering the beginning of a word.
7080 With argument ARG, do this that many times.
7081 If ARG is omitted or nil, move point backward one word.
7083 The word boundaries are normally determined by the buffer's syntax
7084 table, but `find-word-boundary-function-table', such as set up
7085 by `subword-mode', can change that. If a Lisp program needs to
7086 move by words determined strictly by the syntax table, it should
7087 use `backward-word-strictly' instead."
7088 (interactive "^p")
7089 (forward-word (- (or arg 1))))
7091 (defun mark-word (&optional arg allow-extend)
7092 "Set mark ARG words away from point.
7093 The place mark goes is the same place \\[forward-word] would
7094 move to with the same argument.
7095 Interactively, if this command is repeated
7096 or (in Transient Mark mode) if the mark is active,
7097 it marks the next ARG words after the ones already marked."
7098 (interactive "P\np")
7099 (cond ((and allow-extend
7100 (or (and (eq last-command this-command) (mark t))
7101 (region-active-p)))
7102 (setq arg (if arg (prefix-numeric-value arg)
7103 (if (< (mark) (point)) -1 1)))
7104 (set-mark
7105 (save-excursion
7106 (goto-char (mark))
7107 (forward-word arg)
7108 (point))))
7110 (push-mark
7111 (save-excursion
7112 (forward-word (prefix-numeric-value arg))
7113 (point))
7114 nil t))))
7116 (defun kill-word (arg)
7117 "Kill characters forward until encountering the end of a word.
7118 With argument ARG, do this that many times."
7119 (interactive "p")
7120 (kill-region (point) (progn (forward-word arg) (point))))
7122 (defun backward-kill-word (arg)
7123 "Kill characters backward until encountering the beginning of a word.
7124 With argument ARG, do this that many times."
7125 (interactive "p")
7126 (kill-word (- arg)))
7128 (defun current-word (&optional strict really-word)
7129 "Return the word at or near point, as a string.
7130 The return value includes no text properties.
7132 If optional arg STRICT is non-nil, return nil unless point is
7133 within or adjacent to a word, otherwise look for a word within
7134 point's line. If there is no word anywhere on point's line, the
7135 value is nil regardless of STRICT.
7137 By default, this function treats as a single word any sequence of
7138 characters that have either word or symbol syntax. If optional
7139 arg REALLY-WORD is non-nil, only characters of word syntax can
7140 constitute a word."
7141 (save-excursion
7142 (let* ((oldpoint (point)) (start (point)) (end (point))
7143 (syntaxes (if really-word "w" "w_"))
7144 (not-syntaxes (concat "^" syntaxes)))
7145 (skip-syntax-backward syntaxes) (setq start (point))
7146 (goto-char oldpoint)
7147 (skip-syntax-forward syntaxes) (setq end (point))
7148 (when (and (eq start oldpoint) (eq end oldpoint)
7149 ;; Point is neither within nor adjacent to a word.
7150 (not strict))
7151 ;; Look for preceding word in same line.
7152 (skip-syntax-backward not-syntaxes (line-beginning-position))
7153 (if (bolp)
7154 ;; No preceding word in same line.
7155 ;; Look for following word in same line.
7156 (progn
7157 (skip-syntax-forward not-syntaxes (line-end-position))
7158 (setq start (point))
7159 (skip-syntax-forward syntaxes)
7160 (setq end (point)))
7161 (setq end (point))
7162 (skip-syntax-backward syntaxes)
7163 (setq start (point))))
7164 ;; If we found something nonempty, return it as a string.
7165 (unless (= start end)
7166 (buffer-substring-no-properties start end)))))
7168 (defcustom fill-prefix nil
7169 "String for filling to insert at front of new line, or nil for none."
7170 :type '(choice (const :tag "None" nil)
7171 string)
7172 :group 'fill)
7173 (make-variable-buffer-local 'fill-prefix)
7174 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7176 (defcustom auto-fill-inhibit-regexp nil
7177 "Regexp to match lines which should not be auto-filled."
7178 :type '(choice (const :tag "None" nil)
7179 regexp)
7180 :group 'fill)
7182 (defun do-auto-fill ()
7183 "The default value for `normal-auto-fill-function'.
7184 This is the default auto-fill function, some major modes use a different one.
7185 Returns t if it really did any work."
7186 (let (fc justify give-up
7187 (fill-prefix fill-prefix))
7188 (if (or (not (setq justify (current-justification)))
7189 (null (setq fc (current-fill-column)))
7190 (and (eq justify 'left)
7191 (<= (current-column) fc))
7192 (and auto-fill-inhibit-regexp
7193 (save-excursion (beginning-of-line)
7194 (looking-at auto-fill-inhibit-regexp))))
7195 nil ;; Auto-filling not required
7196 (if (memq justify '(full center right))
7197 (save-excursion (unjustify-current-line)))
7199 ;; Choose a fill-prefix automatically.
7200 (when (and adaptive-fill-mode
7201 (or (null fill-prefix) (string= fill-prefix "")))
7202 (let ((prefix
7203 (fill-context-prefix
7204 (save-excursion (fill-forward-paragraph -1) (point))
7205 (save-excursion (fill-forward-paragraph 1) (point)))))
7206 (and prefix (not (equal prefix ""))
7207 ;; Use auto-indentation rather than a guessed empty prefix.
7208 (not (and fill-indent-according-to-mode
7209 (string-match "\\`[ \t]*\\'" prefix)))
7210 (setq fill-prefix prefix))))
7212 (while (and (not give-up) (> (current-column) fc))
7213 ;; Determine where to split the line.
7214 (let ((fill-point
7215 (save-excursion
7216 (beginning-of-line)
7217 ;; Don't split earlier in the line than the length of the
7218 ;; fill prefix, since the resulting line would be longer.
7219 (when fill-prefix
7220 (move-to-column (string-width fill-prefix)))
7221 (let ((after-prefix (point)))
7222 (move-to-column (1+ fc))
7223 (fill-move-to-break-point after-prefix)
7224 (point)))))
7226 ;; See whether the place we found is any good.
7227 (if (save-excursion
7228 (goto-char fill-point)
7229 (or (bolp)
7230 ;; There is no use breaking at end of line.
7231 (save-excursion (skip-chars-forward " ") (eolp))
7232 ;; Don't split right after a comment starter
7233 ;; since we would just make another comment starter.
7234 (and comment-start-skip
7235 (let ((limit (point)))
7236 (beginning-of-line)
7237 (and (re-search-forward comment-start-skip
7238 limit t)
7239 (eq (point) limit))))))
7240 ;; No good place to break => stop trying.
7241 (setq give-up t)
7242 ;; Ok, we have a useful place to break the line. Do it.
7243 (let ((prev-column (current-column)))
7244 ;; If point is at the fill-point, do not `save-excursion'.
7245 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7246 ;; point will end up before it rather than after it.
7247 (if (save-excursion
7248 (skip-chars-backward " \t")
7249 (= (point) fill-point))
7250 (default-indent-new-line t)
7251 (save-excursion
7252 (goto-char fill-point)
7253 (default-indent-new-line t)))
7254 ;; Now do justification, if required
7255 (if (not (eq justify 'left))
7256 (save-excursion
7257 (end-of-line 0)
7258 (justify-current-line justify nil t)))
7259 ;; If making the new line didn't reduce the hpos of
7260 ;; the end of the line, then give up now;
7261 ;; trying again will not help.
7262 (if (>= (current-column) prev-column)
7263 (setq give-up t))))))
7264 ;; Justify last line.
7265 (justify-current-line justify t t)
7266 t)))
7268 (defvar comment-line-break-function 'comment-indent-new-line
7269 "Mode-specific function which line breaks and continues a comment.
7270 This function is called during auto-filling when a comment syntax
7271 is defined.
7272 The function should take a single optional argument, which is a flag
7273 indicating whether it should use soft newlines.")
7275 (defun default-indent-new-line (&optional soft)
7276 "Break line at point and indent.
7277 If a comment syntax is defined, call `comment-indent-new-line'.
7279 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7280 unless optional argument SOFT is non-nil."
7281 (interactive)
7282 (if comment-start
7283 (funcall comment-line-break-function soft)
7284 ;; Insert the newline before removing empty space so that markers
7285 ;; get preserved better.
7286 (if soft (insert-and-inherit ?\n) (newline 1))
7287 (save-excursion (forward-char -1) (delete-horizontal-space))
7288 (delete-horizontal-space)
7290 (if (and fill-prefix (not adaptive-fill-mode))
7291 ;; Blindly trust a non-adaptive fill-prefix.
7292 (progn
7293 (indent-to-left-margin)
7294 (insert-before-markers-and-inherit fill-prefix))
7296 (cond
7297 ;; If there's an adaptive prefix, use it unless we're inside
7298 ;; a comment and the prefix is not a comment starter.
7299 (fill-prefix
7300 (indent-to-left-margin)
7301 (insert-and-inherit fill-prefix))
7302 ;; If we're not inside a comment, just try to indent.
7303 (t (indent-according-to-mode))))))
7305 (defun internal-auto-fill ()
7306 "The function called by `self-insert-command' to perform auto-filling."
7307 (when (or (not comment-start)
7308 (not comment-auto-fill-only-comments)
7309 (nth 4 (syntax-ppss)))
7310 (funcall auto-fill-function)))
7312 (defvar normal-auto-fill-function 'do-auto-fill
7313 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7314 Some major modes set this.")
7316 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7317 ;; `functions' and `hooks' are usually unsafe to set, but setting
7318 ;; auto-fill-function to nil in a file-local setting is safe and
7319 ;; can be useful to prevent auto-filling.
7320 (put 'auto-fill-function 'safe-local-variable 'null)
7322 (define-minor-mode auto-fill-mode
7323 "Toggle automatic line breaking (Auto Fill mode).
7324 Interactively, with a prefix argument, enable
7325 Auto Fill mode if the prefix argument is positive,
7326 and disable it otherwise. If called from Lisp, toggle
7327 the mode if ARG is `toggle', disable the mode if ARG is
7328 a non-positive integer, and enable the mode otherwise
7329 \(including if ARG is omitted or nil or a positive integer).
7331 When Auto Fill mode is enabled, inserting a space at a column
7332 beyond `current-fill-column' automatically breaks the line at a
7333 previous space.
7335 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7336 non-nil.
7338 The value of `normal-auto-fill-function' specifies the function to use
7339 for `auto-fill-function' when turning Auto Fill mode on."
7340 :variable (auto-fill-function
7341 . (lambda (v) (setq auto-fill-function
7342 (if v normal-auto-fill-function)))))
7344 ;; This holds a document string used to document auto-fill-mode.
7345 (defun auto-fill-function ()
7346 "Automatically break line at a previous space, in insertion of text."
7347 nil)
7349 (defun turn-on-auto-fill ()
7350 "Unconditionally turn on Auto Fill mode."
7351 (auto-fill-mode 1))
7353 (defun turn-off-auto-fill ()
7354 "Unconditionally turn off Auto Fill mode."
7355 (auto-fill-mode -1))
7357 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7359 (defun set-fill-column (arg)
7360 "Set `fill-column' to specified argument.
7361 Use \\[universal-argument] followed by a number to specify a column.
7362 Just \\[universal-argument] as argument means to use the current column."
7363 (interactive
7364 (list (or current-prefix-arg
7365 ;; We used to use current-column silently, but C-x f is too easily
7366 ;; typed as a typo for C-x C-f, so we turned it into an error and
7367 ;; now an interactive prompt.
7368 (read-number "Set fill-column to: " (current-column)))))
7369 (if (consp arg)
7370 (setq arg (current-column)))
7371 (if (not (integerp arg))
7372 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7373 (error "set-fill-column requires an explicit argument")
7374 (message "Fill column set to %d (was %d)" arg fill-column)
7375 (setq fill-column arg)))
7377 (defun set-selective-display (arg)
7378 "Set `selective-display' to ARG; clear it if no arg.
7379 When the value of `selective-display' is a number > 0,
7380 lines whose indentation is >= that value are not displayed.
7381 The variable `selective-display' has a separate value for each buffer."
7382 (interactive "P")
7383 (if (eq selective-display t)
7384 (error "selective-display already in use for marked lines"))
7385 (let ((current-vpos
7386 (save-restriction
7387 (narrow-to-region (point-min) (point))
7388 (goto-char (window-start))
7389 (vertical-motion (window-height)))))
7390 (setq selective-display
7391 (and arg (prefix-numeric-value arg)))
7392 (recenter current-vpos))
7393 (set-window-start (selected-window) (window-start))
7394 (princ "selective-display set to " t)
7395 (prin1 selective-display t)
7396 (princ "." t))
7398 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7400 (defun toggle-truncate-lines (&optional arg)
7401 "Toggle truncating of long lines for the current buffer.
7402 When truncating is off, long lines are folded.
7403 With prefix argument ARG, truncate long lines if ARG is positive,
7404 otherwise fold them. Note that in side-by-side windows, this
7405 command has no effect if `truncate-partial-width-windows' is
7406 non-nil."
7407 (interactive "P")
7408 (setq truncate-lines
7409 (if (null arg)
7410 (not truncate-lines)
7411 (> (prefix-numeric-value arg) 0)))
7412 (force-mode-line-update)
7413 (unless truncate-lines
7414 (let ((buffer (current-buffer)))
7415 (walk-windows (lambda (window)
7416 (if (eq buffer (window-buffer window))
7417 (set-window-hscroll window 0)))
7418 nil t)))
7419 (message "Truncate long lines %s"
7420 (if truncate-lines "enabled" "disabled")))
7422 (defun toggle-word-wrap (&optional arg)
7423 "Toggle whether to use word-wrapping for continuation lines.
7424 With prefix argument ARG, wrap continuation lines at word boundaries
7425 if ARG is positive, otherwise wrap them at the right screen edge.
7426 This command toggles the value of `word-wrap'. It has no effect
7427 if long lines are truncated."
7428 (interactive "P")
7429 (setq word-wrap
7430 (if (null arg)
7431 (not word-wrap)
7432 (> (prefix-numeric-value arg) 0)))
7433 (force-mode-line-update)
7434 (message "Word wrapping %s"
7435 (if word-wrap "enabled" "disabled")))
7437 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7438 "The string displayed in the mode line when in overwrite mode.")
7439 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7440 "The string displayed in the mode line when in binary overwrite mode.")
7442 (define-minor-mode overwrite-mode
7443 "Toggle Overwrite mode.
7444 With a prefix argument ARG, enable Overwrite mode if ARG is
7445 positive, and disable it otherwise. If called from Lisp, enable
7446 the mode if ARG is omitted or nil.
7448 When Overwrite mode is enabled, printing characters typed in
7449 replace existing text on a one-for-one basis, rather than pushing
7450 it to the right. At the end of a line, such characters extend
7451 the line. Before a tab, such characters insert until the tab is
7452 filled in. \\[quoted-insert] still inserts characters in
7453 overwrite mode; this is supposed to make it easier to insert
7454 characters when necessary."
7455 :variable (overwrite-mode
7456 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7458 (define-minor-mode binary-overwrite-mode
7459 "Toggle Binary Overwrite mode.
7460 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7461 is positive, and disable it otherwise. If called from Lisp,
7462 enable the mode if ARG is omitted or nil.
7464 When Binary Overwrite mode is enabled, printing characters typed
7465 in replace existing text. Newlines are not treated specially, so
7466 typing at the end of a line joins the line to the next, with the
7467 typed character between them. Typing before a tab character
7468 simply replaces the tab with the character typed.
7469 \\[quoted-insert] replaces the text at the cursor, just as
7470 ordinary typing characters do.
7472 Note that Binary Overwrite mode is not its own minor mode; it is
7473 a specialization of overwrite mode, entered by setting the
7474 `overwrite-mode' variable to `overwrite-mode-binary'."
7475 :variable (overwrite-mode
7476 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7478 (define-minor-mode line-number-mode
7479 "Toggle line number display in the mode line (Line Number mode).
7480 With a prefix argument ARG, enable Line Number mode if ARG is
7481 positive, and disable it otherwise. If called from Lisp, enable
7482 the mode if ARG is omitted or nil.
7484 Line numbers do not appear for very large buffers and buffers
7485 with very long lines; see variables `line-number-display-limit'
7486 and `line-number-display-limit-width'."
7487 :init-value t :global t :group 'mode-line)
7489 (define-minor-mode column-number-mode
7490 "Toggle column number display in the mode line (Column Number mode).
7491 With a prefix argument ARG, enable Column Number mode if ARG is
7492 positive, and disable it otherwise.
7494 If called from Lisp, enable the mode if ARG is omitted or nil."
7495 :global t :group 'mode-line)
7497 (define-minor-mode size-indication-mode
7498 "Toggle buffer size display in the mode line (Size Indication mode).
7499 With a prefix argument ARG, enable Size Indication mode if ARG is
7500 positive, and disable it otherwise.
7502 If called from Lisp, enable the mode if ARG is omitted or nil."
7503 :global t :group 'mode-line)
7505 (define-minor-mode auto-save-mode
7506 "Toggle auto-saving in the current buffer (Auto Save mode).
7507 With a prefix argument ARG, enable Auto Save mode if ARG is
7508 positive, and disable it otherwise.
7510 If called from Lisp, enable the mode if ARG is omitted or nil."
7511 :variable ((and buffer-auto-save-file-name
7512 ;; If auto-save is off because buffer has shrunk,
7513 ;; then toggling should turn it on.
7514 (>= buffer-saved-size 0))
7515 . (lambda (val)
7516 (setq buffer-auto-save-file-name
7517 (cond
7518 ((null val) nil)
7519 ((and buffer-file-name auto-save-visited-file-name
7520 (not buffer-read-only))
7521 buffer-file-name)
7522 (t (make-auto-save-file-name))))))
7523 ;; If -1 was stored here, to temporarily turn off saving,
7524 ;; turn it back on.
7525 (and (< buffer-saved-size 0)
7526 (setq buffer-saved-size 0)))
7528 (defgroup paren-blinking nil
7529 "Blinking matching of parens and expressions."
7530 :prefix "blink-matching-"
7531 :group 'paren-matching)
7533 (defcustom blink-matching-paren t
7534 "Non-nil means show matching open-paren when close-paren is inserted.
7535 If t, highlight the paren. If `jump', briefly move cursor to its
7536 position. If `jump-offscreen', move cursor there even if the
7537 position is off screen. With any other non-nil value, the
7538 off-screen position of the opening paren will be shown in the
7539 echo area."
7540 :type '(choice
7541 (const :tag "Disable" nil)
7542 (const :tag "Highlight" t)
7543 (const :tag "Move cursor" jump)
7544 (const :tag "Move cursor, even if off screen" jump-offscreen))
7545 :group 'paren-blinking)
7547 (defcustom blink-matching-paren-on-screen t
7548 "Non-nil means show matching open-paren when it is on screen.
7549 If nil, don't show it (but the open-paren can still be shown
7550 in the echo area when it is off screen).
7552 This variable has no effect if `blink-matching-paren' is nil.
7553 \(In that case, the open-paren is never shown.)
7554 It is also ignored if `show-paren-mode' is enabled."
7555 :type 'boolean
7556 :group 'paren-blinking)
7558 (defcustom blink-matching-paren-distance (* 100 1024)
7559 "If non-nil, maximum distance to search backwards for matching open-paren.
7560 If nil, search stops at the beginning of the accessible portion of the buffer."
7561 :version "23.2" ; 25->100k
7562 :type '(choice (const nil) integer)
7563 :group 'paren-blinking)
7565 (defcustom blink-matching-delay 1
7566 "Time in seconds to delay after showing a matching paren."
7567 :type 'number
7568 :group 'paren-blinking)
7570 (defcustom blink-matching-paren-dont-ignore-comments nil
7571 "If nil, `blink-matching-paren' ignores comments.
7572 More precisely, when looking for the matching parenthesis,
7573 it skips the contents of comments that end before point."
7574 :type 'boolean
7575 :group 'paren-blinking)
7577 (defun blink-matching-check-mismatch (start end)
7578 "Return whether or not START...END are matching parens.
7579 END is the current point and START is the blink position.
7580 START might be nil if no matching starter was found.
7581 Returns non-nil if we find there is a mismatch."
7582 (let* ((end-syntax (syntax-after (1- end)))
7583 (matching-paren (and (consp end-syntax)
7584 (eq (syntax-class end-syntax) 5)
7585 (cdr end-syntax))))
7586 ;; For self-matched chars like " and $, we can't know when they're
7587 ;; mismatched or unmatched, so we can only do it for parens.
7588 (when matching-paren
7589 (not (and start
7591 (eq (char-after start) matching-paren)
7592 ;; The cdr might hold a new paren-class info rather than
7593 ;; a matching-char info, in which case the two CDRs
7594 ;; should match.
7595 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7597 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7598 "Function to check parentheses mismatches.
7599 The function takes two arguments (START and END) where START is the
7600 position just before the opening token and END is the position right after.
7601 START can be nil, if it was not found.
7602 The function should return non-nil if the two tokens do not match.")
7604 (defvar blink-matching--overlay
7605 (let ((ol (make-overlay (point) (point) nil t)))
7606 (overlay-put ol 'face 'show-paren-match)
7607 (delete-overlay ol)
7609 "Overlay used to highlight the matching paren.")
7611 (defun blink-matching-open ()
7612 "Momentarily highlight the beginning of the sexp before point."
7613 (interactive)
7614 (when (and (not (bobp))
7615 blink-matching-paren)
7616 (let* ((oldpos (point))
7617 (message-log-max nil) ; Don't log messages about paren matching.
7618 (blinkpos
7619 (save-excursion
7620 (save-restriction
7621 (if blink-matching-paren-distance
7622 (narrow-to-region
7623 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7624 (- (point) blink-matching-paren-distance))
7625 oldpos))
7626 (let ((parse-sexp-ignore-comments
7627 (and parse-sexp-ignore-comments
7628 (not blink-matching-paren-dont-ignore-comments))))
7629 (condition-case ()
7630 (progn
7631 (syntax-propertize (point))
7632 (forward-sexp -1)
7633 ;; backward-sexp skips backward over prefix chars,
7634 ;; so move back to the matching paren.
7635 (while (and (< (point) (1- oldpos))
7636 (let ((code (syntax-after (point))))
7637 (or (eq (syntax-class code) 6)
7638 (eq (logand 1048576 (car code))
7639 1048576))))
7640 (forward-char 1))
7641 (point))
7642 (error nil))))))
7643 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7644 (cond
7645 (mismatch
7646 (if blinkpos
7647 (if (minibufferp)
7648 (minibuffer-message "Mismatched parentheses")
7649 (message "Mismatched parentheses"))
7650 (if (minibufferp)
7651 (minibuffer-message "No matching parenthesis found")
7652 (message "No matching parenthesis found"))))
7653 ((not blinkpos) nil)
7654 ((or
7655 (eq blink-matching-paren 'jump-offscreen)
7656 (pos-visible-in-window-p blinkpos))
7657 ;; Matching open within window, temporarily move to or highlight
7658 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7659 ;; is non-nil.
7660 (and blink-matching-paren-on-screen
7661 (not show-paren-mode)
7662 (if (memq blink-matching-paren '(jump jump-offscreen))
7663 (save-excursion
7664 (goto-char blinkpos)
7665 (sit-for blink-matching-delay))
7666 (unwind-protect
7667 (progn
7668 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7669 (current-buffer))
7670 (sit-for blink-matching-delay))
7671 (delete-overlay blink-matching--overlay)))))
7673 (let ((open-paren-line-string
7674 (save-excursion
7675 (goto-char blinkpos)
7676 ;; Show what precedes the open in its line, if anything.
7677 (cond
7678 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7679 (buffer-substring (line-beginning-position)
7680 (1+ blinkpos)))
7681 ;; Show what follows the open in its line, if anything.
7682 ((save-excursion
7683 (forward-char 1)
7684 (skip-chars-forward " \t")
7685 (not (eolp)))
7686 (buffer-substring blinkpos
7687 (line-end-position)))
7688 ;; Otherwise show the previous nonblank line,
7689 ;; if there is one.
7690 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7691 (concat
7692 (buffer-substring (progn
7693 (skip-chars-backward "\n \t")
7694 (line-beginning-position))
7695 (progn (end-of-line)
7696 (skip-chars-backward " \t")
7697 (point)))
7698 ;; Replace the newline and other whitespace with `...'.
7699 "..."
7700 (buffer-substring blinkpos (1+ blinkpos))))
7701 ;; There is nothing to show except the char itself.
7702 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7703 (minibuffer-message
7704 "Matches %s"
7705 (substring-no-properties open-paren-line-string))))))))
7707 (defvar blink-paren-function 'blink-matching-open
7708 "Function called, if non-nil, whenever a close parenthesis is inserted.
7709 More precisely, a char with closeparen syntax is self-inserted.")
7711 (defun blink-paren-post-self-insert-function ()
7712 (when (and (eq (char-before) last-command-event) ; Sanity check.
7713 (memq (char-syntax last-command-event) '(?\) ?\$))
7714 blink-paren-function
7715 (not executing-kbd-macro)
7716 (not noninteractive)
7717 ;; Verify an even number of quoting characters precede the close.
7718 ;; FIXME: Also check if this parenthesis closes a comment as
7719 ;; can happen in Pascal and SML.
7720 (= 1 (logand 1 (- (point)
7721 (save-excursion
7722 (forward-char -1)
7723 (skip-syntax-backward "/\\")
7724 (point))))))
7725 (funcall blink-paren-function)))
7727 (put 'blink-paren-post-self-insert-function 'priority 100)
7729 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7730 ;; Most likely, this hook is nil, so this arg doesn't matter,
7731 ;; but I use it as a reminder that this function usually
7732 ;; likes to be run after others since it does
7733 ;; `sit-for'. That's also the reason it get a `priority' prop
7734 ;; of 100.
7735 'append)
7737 ;; This executes C-g typed while Emacs is waiting for a command.
7738 ;; Quitting out of a program does not go through here;
7739 ;; that happens in the maybe_quit function at the C code level.
7740 (defun keyboard-quit ()
7741 "Signal a `quit' condition.
7742 During execution of Lisp code, this character causes a quit directly.
7743 At top-level, as an editor command, this simply beeps."
7744 (interactive)
7745 ;; Avoid adding the region to the window selection.
7746 (setq saved-region-selection nil)
7747 (let (select-active-regions)
7748 (deactivate-mark))
7749 (if (fboundp 'kmacro-keyboard-quit)
7750 (kmacro-keyboard-quit))
7751 (when completion-in-region-mode
7752 (completion-in-region-mode -1))
7753 ;; Force the next redisplay cycle to remove the "Def" indicator from
7754 ;; all the mode lines.
7755 (if defining-kbd-macro
7756 (force-mode-line-update t))
7757 (setq defining-kbd-macro nil)
7758 (let ((debug-on-quit nil))
7759 (signal 'quit nil)))
7761 (defvar buffer-quit-function nil
7762 "Function to call to \"quit\" the current buffer, or nil if none.
7763 \\[keyboard-escape-quit] calls this function when its more local actions
7764 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7766 (defun keyboard-escape-quit ()
7767 "Exit the current \"mode\" (in a generalized sense of the word).
7768 This command can exit an interactive command such as `query-replace',
7769 can clear out a prefix argument or a region,
7770 can get out of the minibuffer or other recursive edit,
7771 cancel the use of the current buffer (for special-purpose buffers),
7772 or go back to just one window (by deleting all but the selected window)."
7773 (interactive)
7774 (cond ((eq last-command 'mode-exited) nil)
7775 ((region-active-p)
7776 (deactivate-mark))
7777 ((> (minibuffer-depth) 0)
7778 (abort-recursive-edit))
7779 (current-prefix-arg
7780 nil)
7781 ((> (recursion-depth) 0)
7782 (exit-recursive-edit))
7783 (buffer-quit-function
7784 (funcall buffer-quit-function))
7785 ((not (one-window-p t))
7786 (delete-other-windows))
7787 ((string-match "^ \\*" (buffer-name (current-buffer)))
7788 (bury-buffer))))
7790 (defun play-sound-file (file &optional volume device)
7791 "Play sound stored in FILE.
7792 VOLUME and DEVICE correspond to the keywords of the sound
7793 specification for `play-sound'."
7794 (interactive "fPlay sound file: ")
7795 (let ((sound (list :file file)))
7796 (if volume
7797 (plist-put sound :volume volume))
7798 (if device
7799 (plist-put sound :device device))
7800 (push 'sound sound)
7801 (play-sound sound)))
7804 (defcustom read-mail-command 'rmail
7805 "Your preference for a mail reading package.
7806 This is used by some keybindings which support reading mail.
7807 See also `mail-user-agent' concerning sending mail."
7808 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7809 (function-item :tag "Gnus" :format "%t\n" gnus)
7810 (function-item :tag "Emacs interface to MH"
7811 :format "%t\n" mh-rmail)
7812 (function :tag "Other"))
7813 :version "21.1"
7814 :group 'mail)
7816 (defcustom mail-user-agent 'message-user-agent
7817 "Your preference for a mail composition package.
7818 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7819 outgoing email message. This variable lets you specify which
7820 mail-sending package you prefer.
7822 Valid values include:
7824 `message-user-agent' -- use the Message package.
7825 See Info node `(message)'.
7826 `sendmail-user-agent' -- use the Mail package.
7827 See Info node `(emacs)Sending Mail'.
7828 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7829 See Info node `(mh-e)'.
7830 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7831 paraphernalia if Gnus is running, particularly
7832 the Gcc: header for archiving.
7834 Additional valid symbols may be available; check with the author of
7835 your package for details. The function should return non-nil if it
7836 succeeds.
7838 See also `read-mail-command' concerning reading mail."
7839 :type '(radio (function-item :tag "Message package"
7840 :format "%t\n"
7841 message-user-agent)
7842 (function-item :tag "Mail package"
7843 :format "%t\n"
7844 sendmail-user-agent)
7845 (function-item :tag "Emacs interface to MH"
7846 :format "%t\n"
7847 mh-e-user-agent)
7848 (function-item :tag "Message with full Gnus features"
7849 :format "%t\n"
7850 gnus-user-agent)
7851 (function :tag "Other"))
7852 :version "23.2" ; sendmail->message
7853 :group 'mail)
7855 (defcustom compose-mail-user-agent-warnings t
7856 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7857 If the value of `mail-user-agent' is the default, and the user
7858 appears to have customizations applying to the old default,
7859 `compose-mail' issues a warning."
7860 :type 'boolean
7861 :version "23.2"
7862 :group 'mail)
7864 (defun rfc822-goto-eoh ()
7865 "If the buffer starts with a mail header, move point to the header's end.
7866 Otherwise, moves to `point-min'.
7867 The end of the header is the start of the next line, if there is one,
7868 else the end of the last line. This function obeys RFC822."
7869 (goto-char (point-min))
7870 (when (re-search-forward
7871 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7872 (goto-char (match-beginning 0))))
7874 ;; Used by Rmail (e.g., rmail-forward).
7875 (defvar mail-encode-mml nil
7876 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7877 the outgoing message before sending it.")
7879 (defun compose-mail (&optional to subject other-headers continue
7880 switch-function yank-action send-actions
7881 return-action)
7882 "Start composing a mail message to send.
7883 This uses the user's chosen mail composition package
7884 as selected with the variable `mail-user-agent'.
7885 The optional arguments TO and SUBJECT specify recipients
7886 and the initial Subject field, respectively.
7888 OTHER-HEADERS is an alist specifying additional
7889 header fields. Elements look like (HEADER . VALUE) where both
7890 HEADER and VALUE are strings.
7892 CONTINUE, if non-nil, says to continue editing a message already
7893 being composed. Interactively, CONTINUE is the prefix argument.
7895 SWITCH-FUNCTION, if non-nil, is a function to use to
7896 switch to and display the buffer used for mail composition.
7898 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7899 to insert the raw text of the message being replied to.
7900 It has the form (FUNCTION . ARGS). The user agent will apply
7901 FUNCTION to ARGS, to insert the raw text of the original message.
7902 \(The user agent will also run `mail-citation-hook', *after* the
7903 original text has been inserted in this way.)
7905 SEND-ACTIONS is a list of actions to call when the message is sent.
7906 Each action has the form (FUNCTION . ARGS).
7908 RETURN-ACTION, if non-nil, is an action for returning to the
7909 caller. It has the form (FUNCTION . ARGS). The function is
7910 called after the mail has been sent or put aside, and the mail
7911 buffer buried."
7912 (interactive
7913 (list nil nil nil current-prefix-arg))
7915 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7916 ;; from sendmail-user-agent to message-user-agent. Some users may
7917 ;; encounter incompatibilities. This hack tries to detect problems
7918 ;; and warn about them.
7919 (and compose-mail-user-agent-warnings
7920 (eq mail-user-agent 'message-user-agent)
7921 (let (warn-vars)
7922 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7923 mail-citation-hook mail-archive-file-name
7924 mail-default-reply-to mail-mailing-lists
7925 mail-self-blind))
7926 (and (boundp var)
7927 (symbol-value var)
7928 (push var warn-vars)))
7929 (when warn-vars
7930 (display-warning 'mail
7931 (format-message "\
7932 The default mail mode is now Message mode.
7933 You have the following Mail mode variable%s customized:
7934 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7935 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7936 (if (> (length warn-vars) 1) "s" "")
7937 (mapconcat 'symbol-name
7938 warn-vars " "))))))
7940 (let ((function (get mail-user-agent 'composefunc)))
7941 (funcall function to subject other-headers continue switch-function
7942 yank-action send-actions return-action)))
7944 (defun compose-mail-other-window (&optional to subject other-headers continue
7945 yank-action send-actions
7946 return-action)
7947 "Like \\[compose-mail], but edit the outgoing message in another window."
7948 (interactive (list nil nil nil current-prefix-arg))
7949 (compose-mail to subject other-headers continue
7950 'switch-to-buffer-other-window yank-action send-actions
7951 return-action))
7953 (defun compose-mail-other-frame (&optional to subject other-headers continue
7954 yank-action send-actions
7955 return-action)
7956 "Like \\[compose-mail], but edit the outgoing message in another frame."
7957 (interactive (list nil nil nil current-prefix-arg))
7958 (compose-mail to subject other-headers continue
7959 'switch-to-buffer-other-frame yank-action send-actions
7960 return-action))
7963 (defvar set-variable-value-history nil
7964 "History of values entered with `set-variable'.
7966 Maximum length of the history list is determined by the value
7967 of `history-length', which see.")
7969 (defun set-variable (variable value &optional make-local)
7970 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7971 VARIABLE should be a user option variable name, a Lisp variable
7972 meant to be customized by users. You should enter VALUE in Lisp syntax,
7973 so if you want VALUE to be a string, you must surround it with doublequotes.
7974 VALUE is used literally, not evaluated.
7976 If VARIABLE has a `variable-interactive' property, that is used as if
7977 it were the arg to `interactive' (which see) to interactively read VALUE.
7979 If VARIABLE has been defined with `defcustom', then the type information
7980 in the definition is used to check that VALUE is valid.
7982 Note that this function is at heart equivalent to the basic `set' function.
7983 For a variable defined with `defcustom', it does not pay attention to
7984 any :set property that the variable might have (if you want that, use
7985 \\[customize-set-variable] instead).
7987 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7988 (interactive
7989 (let* ((default-var (variable-at-point))
7990 (var (if (custom-variable-p default-var)
7991 (read-variable (format "Set variable (default %s): " default-var)
7992 default-var)
7993 (read-variable "Set variable: ")))
7994 (minibuffer-help-form '(describe-variable var))
7995 (prop (get var 'variable-interactive))
7996 (obsolete (car (get var 'byte-obsolete-variable)))
7997 (prompt (format "Set %s %s to value: " var
7998 (cond ((local-variable-p var)
7999 "(buffer-local)")
8000 ((or current-prefix-arg
8001 (local-variable-if-set-p var))
8002 "buffer-locally")
8003 (t "globally"))))
8004 (val (progn
8005 (when obsolete
8006 (message (concat "`%S' is obsolete; "
8007 (if (symbolp obsolete) "use `%S' instead" "%s"))
8008 var obsolete)
8009 (sit-for 3))
8010 (if prop
8011 ;; Use VAR's `variable-interactive' property
8012 ;; as an interactive spec for prompting.
8013 (call-interactively `(lambda (arg)
8014 (interactive ,prop)
8015 arg))
8016 (read-from-minibuffer prompt nil
8017 read-expression-map t
8018 'set-variable-value-history
8019 (format "%S" (symbol-value var)))))))
8020 (list var val current-prefix-arg)))
8022 (and (custom-variable-p variable)
8023 (not (get variable 'custom-type))
8024 (custom-load-symbol variable))
8025 (let ((type (get variable 'custom-type)))
8026 (when type
8027 ;; Match with custom type.
8028 (require 'cus-edit)
8029 (setq type (widget-convert type))
8030 (unless (widget-apply type :match value)
8031 (user-error "Value `%S' does not match type %S of %S"
8032 value (car type) variable))))
8034 (if make-local
8035 (make-local-variable variable))
8037 (set variable value)
8039 ;; Force a thorough redisplay for the case that the variable
8040 ;; has an effect on the display, like `tab-width' has.
8041 (force-mode-line-update))
8043 ;; Define the major mode for lists of completions.
8045 (defvar completion-list-mode-map
8046 (let ((map (make-sparse-keymap)))
8047 (define-key map [mouse-2] 'choose-completion)
8048 (define-key map [follow-link] 'mouse-face)
8049 (define-key map [down-mouse-2] nil)
8050 (define-key map "\C-m" 'choose-completion)
8051 (define-key map "\e\e\e" 'delete-completion-window)
8052 (define-key map [left] 'previous-completion)
8053 (define-key map [right] 'next-completion)
8054 (define-key map [?\t] 'next-completion)
8055 (define-key map [backtab] 'previous-completion)
8056 (define-key map "q" 'quit-window)
8057 (define-key map "z" 'kill-current-buffer)
8058 map)
8059 "Local map for completion list buffers.")
8061 ;; Completion mode is suitable only for specially formatted data.
8062 (put 'completion-list-mode 'mode-class 'special)
8064 (defvar completion-reference-buffer nil
8065 "Record the buffer that was current when the completion list was requested.
8066 This is a local variable in the completion list buffer.
8067 Initial value is nil to avoid some compiler warnings.")
8069 (defvar completion-no-auto-exit nil
8070 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8071 This also applies to other functions such as `choose-completion'.")
8073 (defvar completion-base-position nil
8074 "Position of the base of the text corresponding to the shown completions.
8075 This variable is used in the *Completions* buffers.
8076 Its value is a list of the form (START END) where START is the place
8077 where the completion should be inserted and END (if non-nil) is the end
8078 of the text to replace. If END is nil, point is used instead.")
8080 (defvar completion-list-insert-choice-function #'completion--replace
8081 "Function to use to insert the text chosen in *Completions*.
8082 Called with three arguments (BEG END TEXT), it should replace the text
8083 between BEG and END with TEXT. Expected to be set buffer-locally
8084 in the *Completions* buffer.")
8086 (defvar completion-base-size nil
8087 "Number of chars before point not involved in completion.
8088 This is a local variable in the completion list buffer.
8089 It refers to the chars in the minibuffer if completing in the
8090 minibuffer, or in `completion-reference-buffer' otherwise.
8091 Only characters in the field at point are included.
8093 If nil, Emacs determines which part of the tail end of the
8094 buffer's text is involved in completion by comparing the text
8095 directly.")
8096 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8098 (defun delete-completion-window ()
8099 "Delete the completion list window.
8100 Go to the window from which completion was requested."
8101 (interactive)
8102 (let ((buf completion-reference-buffer))
8103 (if (one-window-p t)
8104 (if (window-dedicated-p) (delete-frame))
8105 (delete-window (selected-window))
8106 (if (get-buffer-window buf)
8107 (select-window (get-buffer-window buf))))))
8109 (defun previous-completion (n)
8110 "Move to the previous item in the completion list."
8111 (interactive "p")
8112 (next-completion (- n)))
8114 (defun next-completion (n)
8115 "Move to the next item in the completion list.
8116 With prefix argument N, move N items (negative N means move backward)."
8117 (interactive "p")
8118 (let ((beg (point-min)) (end (point-max)))
8119 (while (and (> n 0) (not (eobp)))
8120 ;; If in a completion, move to the end of it.
8121 (when (get-text-property (point) 'mouse-face)
8122 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8123 ;; Move to start of next one.
8124 (unless (get-text-property (point) 'mouse-face)
8125 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8126 (setq n (1- n)))
8127 (while (and (< n 0) (not (bobp)))
8128 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8129 ;; If in a completion, move to the start of it.
8130 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8131 (goto-char (previous-single-property-change
8132 (point) 'mouse-face nil beg)))
8133 ;; Move to end of the previous completion.
8134 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8135 (goto-char (previous-single-property-change
8136 (point) 'mouse-face nil beg)))
8137 ;; Move to the start of that one.
8138 (goto-char (previous-single-property-change
8139 (point) 'mouse-face nil beg))
8140 (setq n (1+ n))))))
8142 (defun choose-completion (&optional event)
8143 "Choose the completion at point.
8144 If EVENT, use EVENT's position to determine the starting position."
8145 (interactive (list last-nonmenu-event))
8146 ;; In case this is run via the mouse, give temporary modes such as
8147 ;; isearch a chance to turn off.
8148 (run-hooks 'mouse-leave-buffer-hook)
8149 (with-current-buffer (window-buffer (posn-window (event-start event)))
8150 (let ((buffer completion-reference-buffer)
8151 (base-size completion-base-size)
8152 (base-position completion-base-position)
8153 (insert-function completion-list-insert-choice-function)
8154 (choice
8155 (save-excursion
8156 (goto-char (posn-point (event-start event)))
8157 (let (beg end)
8158 (cond
8159 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8160 (setq end (point) beg (1+ (point))))
8161 ((and (not (bobp))
8162 (get-text-property (1- (point)) 'mouse-face))
8163 (setq end (1- (point)) beg (point)))
8164 (t (error "No completion here")))
8165 (setq beg (previous-single-property-change beg 'mouse-face))
8166 (setq end (or (next-single-property-change end 'mouse-face)
8167 (point-max)))
8168 (buffer-substring-no-properties beg end)))))
8170 (unless (buffer-live-p buffer)
8171 (error "Destination buffer is dead"))
8172 (quit-window nil (posn-window (event-start event)))
8174 (with-current-buffer buffer
8175 (choose-completion-string
8176 choice buffer
8177 (or base-position
8178 (when base-size
8179 ;; Someone's using old completion code that doesn't know
8180 ;; about base-position yet.
8181 (list (+ base-size (field-beginning))))
8182 ;; If all else fails, just guess.
8183 (list (choose-completion-guess-base-position choice)))
8184 insert-function)))))
8186 ;; Delete the longest partial match for STRING
8187 ;; that can be found before POINT.
8188 (defun choose-completion-guess-base-position (string)
8189 (save-excursion
8190 (let ((opoint (point))
8191 len)
8192 ;; Try moving back by the length of the string.
8193 (goto-char (max (- (point) (length string))
8194 (minibuffer-prompt-end)))
8195 ;; See how far back we were actually able to move. That is the
8196 ;; upper bound on how much we can match and delete.
8197 (setq len (- opoint (point)))
8198 (if completion-ignore-case
8199 (setq string (downcase string)))
8200 (while (and (> len 0)
8201 (let ((tail (buffer-substring (point) opoint)))
8202 (if completion-ignore-case
8203 (setq tail (downcase tail)))
8204 (not (string= tail (substring string 0 len)))))
8205 (setq len (1- len))
8206 (forward-char 1))
8207 (point))))
8209 (defun choose-completion-delete-max-match (string)
8210 (declare (obsolete choose-completion-guess-base-position "23.2"))
8211 (delete-region (choose-completion-guess-base-position string) (point)))
8213 (defvar choose-completion-string-functions nil
8214 "Functions that may override the normal insertion of a completion choice.
8215 These functions are called in order with three arguments:
8216 CHOICE - the string to insert in the buffer,
8217 BUFFER - the buffer in which the choice should be inserted,
8218 BASE-POSITION - where to insert the completion.
8220 If a function in the list returns non-nil, that function is supposed
8221 to have inserted the CHOICE in the BUFFER, and possibly exited
8222 the minibuffer; no further functions will be called.
8224 If all functions in the list return nil, that means to use
8225 the default method of inserting the completion in BUFFER.")
8227 (defun choose-completion-string (choice &optional
8228 buffer base-position insert-function)
8229 "Switch to BUFFER and insert the completion choice CHOICE.
8230 BASE-POSITION says where to insert the completion.
8231 INSERT-FUNCTION says how to insert the completion and falls
8232 back on `completion-list-insert-choice-function' when nil."
8234 ;; If BUFFER is the minibuffer, exit the minibuffer
8235 ;; unless it is reading a file name and CHOICE is a directory,
8236 ;; or completion-no-auto-exit is non-nil.
8238 ;; Some older code may call us passing `base-size' instead of
8239 ;; `base-position'. It's difficult to make any use of `base-size',
8240 ;; so we just ignore it.
8241 (unless (consp base-position)
8242 (message "Obsolete `base-size' passed to choose-completion-string")
8243 (setq base-position nil))
8245 (let* ((buffer (or buffer completion-reference-buffer))
8246 (mini-p (minibufferp buffer)))
8247 ;; If BUFFER is a minibuffer, barf unless it's the currently
8248 ;; active minibuffer.
8249 (if (and mini-p
8250 (not (and (active-minibuffer-window)
8251 (equal buffer
8252 (window-buffer (active-minibuffer-window))))))
8253 (error "Minibuffer is not active for completion")
8254 ;; Set buffer so buffer-local choose-completion-string-functions works.
8255 (set-buffer buffer)
8256 (unless (run-hook-with-args-until-success
8257 'choose-completion-string-functions
8258 ;; The fourth arg used to be `mini-p' but was useless
8259 ;; (since minibufferp can be used on the `buffer' arg)
8260 ;; and indeed unused. The last used to be `base-size', so we
8261 ;; keep it to try and avoid breaking old code.
8262 choice buffer base-position nil)
8263 ;; This remove-text-properties should be unnecessary since `choice'
8264 ;; comes from buffer-substring-no-properties.
8265 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8266 ;; Insert the completion into the buffer where it was requested.
8267 (funcall (or insert-function completion-list-insert-choice-function)
8268 (or (car base-position) (point))
8269 (or (cadr base-position) (point))
8270 choice)
8271 ;; Update point in the window that BUFFER is showing in.
8272 (let ((window (get-buffer-window buffer t)))
8273 (set-window-point window (point)))
8274 ;; If completing for the minibuffer, exit it with this choice.
8275 (and (not completion-no-auto-exit)
8276 (minibufferp buffer)
8277 minibuffer-completion-table
8278 ;; If this is reading a file name, and the file name chosen
8279 ;; is a directory, don't exit the minibuffer.
8280 (let* ((result (buffer-substring (field-beginning) (point)))
8281 (bounds
8282 (completion-boundaries result minibuffer-completion-table
8283 minibuffer-completion-predicate
8284 "")))
8285 (if (eq (car bounds) (length result))
8286 ;; The completion chosen leads to a new set of completions
8287 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8288 (let ((mini (active-minibuffer-window)))
8289 (select-window mini)
8290 (when minibuffer-auto-raise
8291 (raise-frame (window-frame mini))))
8292 (exit-minibuffer))))))))
8294 (define-derived-mode completion-list-mode nil "Completion List"
8295 "Major mode for buffers showing lists of possible completions.
8296 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8297 to select the completion near point.
8298 Or click to select one with the mouse.
8300 \\{completion-list-mode-map}"
8301 (set (make-local-variable 'completion-base-size) nil))
8303 (defun completion-list-mode-finish ()
8304 "Finish setup of the completions buffer.
8305 Called from `temp-buffer-show-hook'."
8306 (when (eq major-mode 'completion-list-mode)
8307 (setq buffer-read-only t)))
8309 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8312 ;; Variables and faces used in `completion-setup-function'.
8314 (defcustom completion-show-help t
8315 "Non-nil means show help message in *Completions* buffer."
8316 :type 'boolean
8317 :version "22.1"
8318 :group 'completion)
8320 ;; This function goes in completion-setup-hook, so that it is called
8321 ;; after the text of the completion list buffer is written.
8322 (defun completion-setup-function ()
8323 (let* ((mainbuf (current-buffer))
8324 (base-dir
8325 ;; FIXME: This is a bad hack. We try to set the default-directory
8326 ;; in the *Completions* buffer so that the relative file names
8327 ;; displayed there can be treated as valid file names, independently
8328 ;; from the completion context. But this suffers from many problems:
8329 ;; - It's not clear when the completions are file names. With some
8330 ;; completion tables (e.g. bzr revision specs), the listed
8331 ;; completions can mix file names and other things.
8332 ;; - It doesn't pay attention to possible quoting.
8333 ;; - With fancy completion styles, the code below will not always
8334 ;; find the right base directory.
8335 (if minibuffer-completing-file-name
8336 (file-name-as-directory
8337 (expand-file-name
8338 (buffer-substring (minibuffer-prompt-end)
8339 (- (point) (or completion-base-size 0))))))))
8340 (with-current-buffer standard-output
8341 (let ((base-size completion-base-size) ;Read before killing localvars.
8342 (base-position completion-base-position)
8343 (insert-fun completion-list-insert-choice-function))
8344 (completion-list-mode)
8345 (set (make-local-variable 'completion-base-size) base-size)
8346 (set (make-local-variable 'completion-base-position) base-position)
8347 (set (make-local-variable 'completion-list-insert-choice-function)
8348 insert-fun))
8349 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8350 (if base-dir (setq default-directory base-dir))
8351 ;; Maybe insert help string.
8352 (when completion-show-help
8353 (goto-char (point-min))
8354 (if (display-mouse-p)
8355 (insert "Click on a completion to select it.\n"))
8356 (insert (substitute-command-keys
8357 "In this buffer, type \\[choose-completion] to \
8358 select the completion near point.\n\n"))))))
8360 (add-hook 'completion-setup-hook 'completion-setup-function)
8362 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8363 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8365 (defun switch-to-completions ()
8366 "Select the completion list window."
8367 (interactive)
8368 (let ((window (or (get-buffer-window "*Completions*" 0)
8369 ;; Make sure we have a completions window.
8370 (progn (minibuffer-completion-help)
8371 (get-buffer-window "*Completions*" 0)))))
8372 (when window
8373 (select-window window)
8374 ;; In the new buffer, go to the first completion.
8375 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8376 (when (bobp)
8377 (next-completion 1)))))
8379 ;;; Support keyboard commands to turn on various modifiers.
8381 ;; These functions -- which are not commands -- each add one modifier
8382 ;; to the following event.
8384 (defun event-apply-alt-modifier (_ignore-prompt)
8385 "\\<function-key-map>Add the Alt modifier to the following event.
8386 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8387 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8388 (defun event-apply-super-modifier (_ignore-prompt)
8389 "\\<function-key-map>Add the Super modifier to the following event.
8390 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8391 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8392 (defun event-apply-hyper-modifier (_ignore-prompt)
8393 "\\<function-key-map>Add the Hyper modifier to the following event.
8394 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8395 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8396 (defun event-apply-shift-modifier (_ignore-prompt)
8397 "\\<function-key-map>Add the Shift modifier to the following event.
8398 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8399 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8400 (defun event-apply-control-modifier (_ignore-prompt)
8401 "\\<function-key-map>Add the Ctrl modifier to the following event.
8402 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8403 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8404 (defun event-apply-meta-modifier (_ignore-prompt)
8405 "\\<function-key-map>Add the Meta modifier to the following event.
8406 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8407 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8409 (defun event-apply-modifier (event symbol lshiftby prefix)
8410 "Apply a modifier flag to event EVENT.
8411 SYMBOL is the name of this modifier, as a symbol.
8412 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8413 PREFIX is the string that represents this modifier in an event type symbol."
8414 (if (numberp event)
8415 (cond ((eq symbol 'control)
8416 (if (and (<= (downcase event) ?z)
8417 (>= (downcase event) ?a))
8418 (- (downcase event) ?a -1)
8419 (if (and (<= (downcase event) ?Z)
8420 (>= (downcase event) ?A))
8421 (- (downcase event) ?A -1)
8422 (logior (lsh 1 lshiftby) event))))
8423 ((eq symbol 'shift)
8424 (if (and (<= (downcase event) ?z)
8425 (>= (downcase event) ?a))
8426 (upcase event)
8427 (logior (lsh 1 lshiftby) event)))
8429 (logior (lsh 1 lshiftby) event)))
8430 (if (memq symbol (event-modifiers event))
8431 event
8432 (let ((event-type (if (symbolp event) event (car event))))
8433 (setq event-type (intern (concat prefix (symbol-name event-type))))
8434 (if (symbolp event)
8435 event-type
8436 (cons event-type (cdr event)))))))
8438 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8439 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8440 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8441 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8442 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8443 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8445 ;;;; Keypad support.
8447 ;; Make the keypad keys act like ordinary typing keys. If people add
8448 ;; bindings for the function key symbols, then those bindings will
8449 ;; override these, so this shouldn't interfere with any existing
8450 ;; bindings.
8452 ;; Also tell read-char how to handle these keys.
8453 (mapc
8454 (lambda (keypad-normal)
8455 (let ((keypad (nth 0 keypad-normal))
8456 (normal (nth 1 keypad-normal)))
8457 (put keypad 'ascii-character normal)
8458 (define-key function-key-map (vector keypad) (vector normal))))
8459 ;; See also kp-keys bound in bindings.el.
8460 '((kp-space ?\s)
8461 (kp-tab ?\t)
8462 (kp-enter ?\r)
8463 (kp-separator ?,)
8464 (kp-equal ?=)
8465 ;; Do the same for various keys that are represented as symbols under
8466 ;; GUIs but naturally correspond to characters.
8467 (backspace 127)
8468 (delete 127)
8469 (tab ?\t)
8470 (linefeed ?\n)
8471 (clear ?\C-l)
8472 (return ?\C-m)
8473 (escape ?\e)
8476 ;;;;
8477 ;;;; forking a twin copy of a buffer.
8478 ;;;;
8480 (defvar clone-buffer-hook nil
8481 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8483 (defvar clone-indirect-buffer-hook nil
8484 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8486 (defun clone-process (process &optional newname)
8487 "Create a twin copy of PROCESS.
8488 If NEWNAME is nil, it defaults to PROCESS' name;
8489 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8490 If PROCESS is associated with a buffer, the new process will be associated
8491 with the current buffer instead.
8492 Returns nil if PROCESS has already terminated."
8493 (setq newname (or newname (process-name process)))
8494 (if (string-match "<[0-9]+>\\'" newname)
8495 (setq newname (substring newname 0 (match-beginning 0))))
8496 (when (memq (process-status process) '(run stop open))
8497 (let* ((process-connection-type (process-tty-name process))
8498 (new-process
8499 (if (memq (process-status process) '(open))
8500 (let ((args (process-contact process t)))
8501 (setq args (plist-put args :name newname))
8502 (setq args (plist-put args :buffer
8503 (if (process-buffer process)
8504 (current-buffer))))
8505 (apply 'make-network-process args))
8506 (apply 'start-process newname
8507 (if (process-buffer process) (current-buffer))
8508 (process-command process)))))
8509 (set-process-query-on-exit-flag
8510 new-process (process-query-on-exit-flag process))
8511 (set-process-inherit-coding-system-flag
8512 new-process (process-inherit-coding-system-flag process))
8513 (set-process-filter new-process (process-filter process))
8514 (set-process-sentinel new-process (process-sentinel process))
8515 (set-process-plist new-process (copy-sequence (process-plist process)))
8516 new-process)))
8518 ;; things to maybe add (currently partly covered by `funcall mode'):
8519 ;; - syntax-table
8520 ;; - overlays
8521 (defun clone-buffer (&optional newname display-flag)
8522 "Create and return a twin copy of the current buffer.
8523 Unlike an indirect buffer, the new buffer can be edited
8524 independently of the old one (if it is not read-only).
8525 NEWNAME is the name of the new buffer. It may be modified by
8526 adding or incrementing <N> at the end as necessary to create a
8527 unique buffer name. If nil, it defaults to the name of the
8528 current buffer, with the proper suffix. If DISPLAY-FLAG is
8529 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8530 clone a file-visiting buffer, or a buffer whose major mode symbol
8531 has a non-nil `no-clone' property, results in an error.
8533 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8534 current buffer with appropriate suffix. However, if a prefix
8535 argument is given, then the command prompts for NEWNAME in the
8536 minibuffer.
8538 This runs the normal hook `clone-buffer-hook' in the new buffer
8539 after it has been set up properly in other respects."
8540 (interactive
8541 (progn
8542 (if buffer-file-name
8543 (error "Cannot clone a file-visiting buffer"))
8544 (if (get major-mode 'no-clone)
8545 (error "Cannot clone a buffer in %s mode" mode-name))
8546 (list (if current-prefix-arg
8547 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8548 t)))
8549 (if buffer-file-name
8550 (error "Cannot clone a file-visiting buffer"))
8551 (if (get major-mode 'no-clone)
8552 (error "Cannot clone a buffer in %s mode" mode-name))
8553 (setq newname (or newname (buffer-name)))
8554 (if (string-match "<[0-9]+>\\'" newname)
8555 (setq newname (substring newname 0 (match-beginning 0))))
8556 (let ((buf (current-buffer))
8557 (ptmin (point-min))
8558 (ptmax (point-max))
8559 (pt (point))
8560 (mk (if mark-active (mark t)))
8561 (modified (buffer-modified-p))
8562 (mode major-mode)
8563 (lvars (buffer-local-variables))
8564 (process (get-buffer-process (current-buffer)))
8565 (new (generate-new-buffer (or newname (buffer-name)))))
8566 (save-restriction
8567 (widen)
8568 (with-current-buffer new
8569 (insert-buffer-substring buf)))
8570 (with-current-buffer new
8571 (narrow-to-region ptmin ptmax)
8572 (goto-char pt)
8573 (if mk (set-mark mk))
8574 (set-buffer-modified-p modified)
8576 ;; Clone the old buffer's process, if any.
8577 (when process (clone-process process))
8579 ;; Now set up the major mode.
8580 (funcall mode)
8582 ;; Set up other local variables.
8583 (mapc (lambda (v)
8584 (condition-case ()
8585 (if (symbolp v)
8586 (makunbound v)
8587 (set (make-local-variable (car v)) (cdr v)))
8588 (setting-constant nil))) ;E.g. for enable-multibyte-characters.
8589 lvars)
8591 (setq mark-ring (mapcar (lambda (mk) (copy-marker (marker-position mk)))
8592 mark-ring))
8594 ;; Run any hooks (typically set up by the major mode
8595 ;; for cloning to work properly).
8596 (run-hooks 'clone-buffer-hook))
8597 (if display-flag
8598 ;; Presumably the current buffer is shown in the selected frame, so
8599 ;; we want to display the clone elsewhere.
8600 (let ((same-window-regexps nil)
8601 (same-window-buffer-names))
8602 (pop-to-buffer new)))
8603 new))
8606 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8607 "Create an indirect buffer that is a twin copy of the current buffer.
8609 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8610 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8611 or if not called with a prefix arg, NEWNAME defaults to the current
8612 buffer's name. The name is modified by adding a `<N>' suffix to it
8613 or by incrementing the N in an existing suffix. Trying to clone a
8614 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8615 property results in an error.
8617 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8618 This is always done when called interactively.
8620 Optional third arg NORECORD non-nil means do not put this buffer at the
8621 front of the list of recently selected ones.
8623 Returns the newly created indirect buffer."
8624 (interactive
8625 (progn
8626 (if (get major-mode 'no-clone-indirect)
8627 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8628 (list (if current-prefix-arg
8629 (read-buffer "Name of indirect buffer: " (current-buffer)))
8630 t)))
8631 (if (get major-mode 'no-clone-indirect)
8632 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8633 (setq newname (or newname (buffer-name)))
8634 (if (string-match "<[0-9]+>\\'" newname)
8635 (setq newname (substring newname 0 (match-beginning 0))))
8636 (let* ((name (generate-new-buffer-name newname))
8637 (buffer (make-indirect-buffer (current-buffer) name t)))
8638 (with-current-buffer buffer
8639 (run-hooks 'clone-indirect-buffer-hook))
8640 (when display-flag
8641 (pop-to-buffer buffer nil norecord))
8642 buffer))
8645 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8646 "Like `clone-indirect-buffer' but display in another window."
8647 (interactive
8648 (progn
8649 (if (get major-mode 'no-clone-indirect)
8650 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8651 (list (if current-prefix-arg
8652 (read-buffer "Name of indirect buffer: " (current-buffer)))
8653 t)))
8654 (let ((pop-up-windows t))
8655 (clone-indirect-buffer newname display-flag norecord)))
8658 ;;; Handling of Backspace and Delete keys.
8660 (defcustom normal-erase-is-backspace 'maybe
8661 "Set the default behavior of the Delete and Backspace keys.
8663 If set to t, Delete key deletes forward and Backspace key deletes
8664 backward.
8666 If set to nil, both Delete and Backspace keys delete backward.
8668 If set to `maybe' (which is the default), Emacs automatically
8669 selects a behavior. On window systems, the behavior depends on
8670 the keyboard used. If the keyboard has both a Backspace key and
8671 a Delete key, and both are mapped to their usual meanings, the
8672 option's default value is set to t, so that Backspace can be used
8673 to delete backward, and Delete can be used to delete forward.
8675 If not running under a window system, customizing this option
8676 accomplishes a similar effect by mapping C-h, which is usually
8677 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8678 via `keyboard-translate'. The former functionality of C-h is
8679 available on the F1 key. You should probably not use this
8680 setting if you don't have both Backspace, Delete and F1 keys.
8682 Setting this variable with setq doesn't take effect. Programmatically,
8683 call `normal-erase-is-backspace-mode' (which see) instead."
8684 :type '(choice (const :tag "Off" nil)
8685 (const :tag "Maybe" maybe)
8686 (other :tag "On" t))
8687 :group 'editing-basics
8688 :version "21.1"
8689 :set (lambda (symbol value)
8690 ;; The fboundp is because of a problem with :set when
8691 ;; dumping Emacs. It doesn't really matter.
8692 (if (fboundp 'normal-erase-is-backspace-mode)
8693 (normal-erase-is-backspace-mode (or value 0))
8694 (set-default symbol value))))
8696 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8697 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8698 (unless frame (setq frame (selected-frame)))
8699 (with-selected-frame frame
8700 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8701 (normal-erase-is-backspace-mode
8702 (if (if (eq normal-erase-is-backspace 'maybe)
8703 (and (not noninteractive)
8704 (or (memq system-type '(ms-dos windows-nt))
8705 (memq window-system '(w32 ns))
8706 (and (memq window-system '(x))
8707 (fboundp 'x-backspace-delete-keys-p)
8708 (x-backspace-delete-keys-p))
8709 ;; If the terminal Emacs is running on has erase char
8710 ;; set to ^H, use the Backspace key for deleting
8711 ;; backward, and the Delete key for deleting forward.
8712 (and (null window-system)
8713 (eq tty-erase-char ?\^H))))
8714 normal-erase-is-backspace)
8715 1 0)))))
8717 (define-minor-mode normal-erase-is-backspace-mode
8718 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8719 With a prefix argument ARG, enable this feature if ARG is
8720 positive, and disable it otherwise. If called from Lisp, enable
8721 the mode if ARG is omitted or nil.
8723 On window systems, when this mode is on, Delete is mapped to C-d
8724 and Backspace is mapped to DEL; when this mode is off, both
8725 Delete and Backspace are mapped to DEL. (The remapping goes via
8726 `local-function-key-map', so binding Delete or Backspace in the
8727 global or local keymap will override that.)
8729 In addition, on window systems, the bindings of C-Delete, M-Delete,
8730 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8731 the global keymap in accordance with the functionality of Delete and
8732 Backspace. For example, if Delete is remapped to C-d, which deletes
8733 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8734 to DEL, which deletes backward, C-Delete is bound to
8735 `backward-kill-word'.
8737 If not running on a window system, a similar effect is accomplished by
8738 remapping C-h (normally produced by the Backspace key) and DEL via
8739 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8740 to C-d; if it's off, the keys are not remapped.
8742 When not running on a window system, and this mode is turned on, the
8743 former functionality of C-h is available on the F1 key. You should
8744 probably not turn on this mode on a text-only terminal if you don't
8745 have both Backspace, Delete and F1 keys.
8747 See also `normal-erase-is-backspace'."
8748 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8749 . (lambda (v)
8750 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8751 (if v 1 0))))
8752 (let ((enabled (eq 1 (terminal-parameter
8753 nil 'normal-erase-is-backspace))))
8755 (cond ((or (memq window-system '(x w32 ns pc))
8756 (memq system-type '(ms-dos windows-nt)))
8757 (let ((bindings
8758 `(([M-delete] [M-backspace])
8759 ([C-M-delete] [C-M-backspace])
8760 ([?\e C-delete] [?\e C-backspace]))))
8762 (if enabled
8763 (progn
8764 (define-key local-function-key-map [delete] [deletechar])
8765 (define-key local-function-key-map [kp-delete] [deletechar])
8766 (define-key local-function-key-map [backspace] [?\C-?])
8767 (dolist (b bindings)
8768 ;; Not sure if input-decode-map is really right, but
8769 ;; keyboard-translate-table (used below) only works
8770 ;; for integer events, and key-translation-table is
8771 ;; global (like the global-map, used earlier).
8772 (define-key input-decode-map (car b) nil)
8773 (define-key input-decode-map (cadr b) nil)))
8774 (define-key local-function-key-map [delete] [?\C-?])
8775 (define-key local-function-key-map [kp-delete] [?\C-?])
8776 (define-key local-function-key-map [backspace] [?\C-?])
8777 (dolist (b bindings)
8778 (define-key input-decode-map (car b) (cadr b))
8779 (define-key input-decode-map (cadr b) (car b))))))
8781 (if enabled
8782 (progn
8783 (keyboard-translate ?\C-h ?\C-?)
8784 (keyboard-translate ?\C-? ?\C-d))
8785 (keyboard-translate ?\C-h ?\C-h)
8786 (keyboard-translate ?\C-? ?\C-?))))
8788 (if (called-interactively-p 'interactive)
8789 (message "Delete key deletes %s"
8790 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8791 "forward" "backward")))))
8793 (defvar vis-mode-saved-buffer-invisibility-spec nil
8794 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8796 (define-minor-mode read-only-mode
8797 "Change whether the current buffer is read-only.
8798 With prefix argument ARG, make the buffer read-only if ARG is
8799 positive, otherwise make it writable. If buffer is read-only
8800 and `view-read-only' is non-nil, enter view mode.
8802 Do not call this from a Lisp program unless you really intend to
8803 do the same thing as the \\[read-only-mode] command, including
8804 possibly enabling or disabling View mode. Also, note that this
8805 command works by setting the variable `buffer-read-only', which
8806 does not affect read-only regions caused by text properties. To
8807 ignore read-only status in a Lisp program (whether due to text
8808 properties or buffer state), bind `inhibit-read-only' temporarily
8809 to a non-nil value."
8810 :variable buffer-read-only
8811 (cond
8812 ((and (not buffer-read-only) view-mode)
8813 (View-exit-and-edit)
8814 (make-local-variable 'view-read-only)
8815 (setq view-read-only t)) ; Must leave view mode.
8816 ((and buffer-read-only view-read-only
8817 ;; If view-mode is already active, `view-mode-enter' is a nop.
8818 (not view-mode)
8819 (not (eq (get major-mode 'mode-class) 'special)))
8820 (view-mode-enter))))
8822 (define-minor-mode visible-mode
8823 "Toggle making all invisible text temporarily visible (Visible mode).
8824 With a prefix argument ARG, enable Visible mode if ARG is
8825 positive, and disable it otherwise. If called from Lisp, enable
8826 the mode if ARG is omitted or nil.
8828 This mode works by saving the value of `buffer-invisibility-spec'
8829 and setting it to nil."
8830 :lighter " Vis"
8831 :group 'editing-basics
8832 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8833 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8834 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8835 (when visible-mode
8836 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8837 buffer-invisibility-spec)
8838 (setq buffer-invisibility-spec nil)))
8840 (defvar messages-buffer-mode-map
8841 (let ((map (make-sparse-keymap)))
8842 (set-keymap-parent map special-mode-map)
8843 (define-key map "g" nil) ; nothing to revert
8844 map))
8846 (define-derived-mode messages-buffer-mode special-mode "Messages"
8847 "Major mode used in the \"*Messages*\" buffer.")
8849 (defun messages-buffer ()
8850 "Return the \"*Messages*\" buffer.
8851 If it does not exist, create and it switch it to `messages-buffer-mode'."
8852 (or (get-buffer "*Messages*")
8853 (with-current-buffer (get-buffer-create "*Messages*")
8854 (messages-buffer-mode)
8855 (current-buffer))))
8858 ;; Minibuffer prompt stuff.
8860 ;;(defun minibuffer-prompt-modification (start end)
8861 ;; (error "You cannot modify the prompt"))
8864 ;;(defun minibuffer-prompt-insertion (start end)
8865 ;; (let ((inhibit-modification-hooks t))
8866 ;; (delete-region start end)
8867 ;; ;; Discard undo information for the text insertion itself
8868 ;; ;; and for the text deletion.above.
8869 ;; (when (consp buffer-undo-list)
8870 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8871 ;; (message "You cannot modify the prompt")))
8874 ;;(setq minibuffer-prompt-properties
8875 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8876 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8879 ;;;; Problematic external packages.
8881 ;; rms says this should be done by specifying symbols that define
8882 ;; versions together with bad values. This is therefore not as
8883 ;; flexible as it could be. See the thread:
8884 ;; https://lists.gnu.org/r/emacs-devel/2007-08/msg00300.html
8885 (defconst bad-packages-alist
8886 ;; Not sure exactly which semantic versions have problems.
8887 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8888 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8889 "The version of `semantic' loaded does not work in Emacs 22.
8890 It can cause constant high CPU load.
8891 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8892 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8893 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8894 ;; provided the `CUA-mode' feature. Since this is no longer true,
8895 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8896 (CUA-mode t nil
8897 "CUA-mode is now part of the standard GNU Emacs distribution,
8898 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8900 You have loaded an older version of CUA-mode which does not work
8901 correctly with this version of Emacs. You should remove the old
8902 version and use the one distributed with Emacs."))
8903 "Alist of packages known to cause problems in this version of Emacs.
8904 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8905 PACKAGE is either a regular expression to match file names, or a
8906 symbol (a feature name), like for `with-eval-after-load'.
8907 SYMBOL is either the name of a string variable, or t. Upon
8908 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8909 warning using STRING as the message.")
8911 (defun bad-package-check (package)
8912 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8913 (condition-case nil
8914 (let* ((list (assoc package bad-packages-alist))
8915 (symbol (nth 1 list)))
8916 (and list
8917 (boundp symbol)
8918 (or (eq symbol t)
8919 (and (stringp (setq symbol (eval symbol)))
8920 (string-match-p (nth 2 list) symbol)))
8921 (display-warning package (nth 3 list) :warning)))
8922 (error nil)))
8924 (dolist (elem bad-packages-alist)
8925 (let ((pkg (car elem)))
8926 (with-eval-after-load pkg
8927 (bad-package-check pkg))))
8930 ;;; Generic dispatcher commands
8932 ;; Macro `define-alternatives' is used to create generic commands.
8933 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8934 ;; that can have different alternative implementations where choosing
8935 ;; among them is exclusively a matter of user preference.
8937 ;; (define-alternatives COMMAND) creates a new interactive command
8938 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8939 ;; Typically, the user will not need to customize this variable; packages
8940 ;; wanting to add alternative implementations should use
8942 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8944 (defmacro define-alternatives (command &rest customizations)
8945 "Define the new command `COMMAND'.
8947 The argument `COMMAND' should be a symbol.
8949 Running `M-x COMMAND RET' for the first time prompts for which
8950 alternative to use and records the selected command as a custom
8951 variable.
8953 Running `C-u M-x COMMAND RET' prompts again for an alternative
8954 and overwrites the previous choice.
8956 The variable `COMMAND-alternatives' contains an alist with
8957 alternative implementations of COMMAND. `define-alternatives'
8958 does not have any effect until this variable is set.
8960 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8961 `defcustom' keywords and values to add to the declaration of
8962 `COMMAND-alternatives' (typically :group and :version)."
8963 (let* ((command-name (symbol-name command))
8964 (varalt-name (concat command-name "-alternatives"))
8965 (varalt-sym (intern varalt-name))
8966 (varimp-sym (intern (concat command-name "--implementation"))))
8967 `(progn
8969 (defcustom ,varalt-sym nil
8970 ,(format "Alist of alternative implementations for the `%s' command.
8972 Each entry must be a pair (ALTNAME . ALTFUN), where:
8973 ALTNAME - The name shown at user to describe the alternative implementation.
8974 ALTFUN - The function called to implement this alternative."
8975 command-name)
8976 :type '(alist :key-type string :value-type function)
8977 ,@customizations)
8979 (put ',varalt-sym 'definition-name ',command)
8980 (defvar ,varimp-sym nil "Internal use only.")
8982 (defun ,command (&optional arg)
8983 ,(format "Run generic command `%s'.
8984 If used for the first time, or with interactive ARG, ask the user which
8985 implementation to use for `%s'. The variable `%s'
8986 contains the list of implementations currently supported for this command."
8987 command-name command-name varalt-name)
8988 (interactive "P")
8989 (when (or arg (null ,varimp-sym))
8990 (let ((val (completing-read
8991 ,(format-message
8992 "Select implementation for command `%s': "
8993 command-name)
8994 ,varalt-sym nil t)))
8995 (unless (string-equal val "")
8996 (when (null ,varimp-sym)
8997 (message
8998 "Use C-u M-x %s RET`to select another implementation"
8999 ,command-name)
9000 (sit-for 3))
9001 (customize-save-variable ',varimp-sym
9002 (cdr (assoc-string val ,varalt-sym))))))
9003 (if ,varimp-sym
9004 (call-interactively ,varimp-sym)
9005 (message "%s" ,(format-message
9006 "No implementation selected for command `%s'"
9007 command-name)))))))
9010 ;;; Functions for changing capitalization that Do What I Mean
9011 (defun upcase-dwim (arg)
9012 "Upcase words in the region, if active; if not, upcase word at point.
9013 If the region is active, this function calls `upcase-region'.
9014 Otherwise, it calls `upcase-word', with prefix argument passed to it
9015 to upcase ARG words."
9016 (interactive "*p")
9017 (if (use-region-p)
9018 (upcase-region (region-beginning) (region-end) (region-noncontiguous-p))
9019 (upcase-word arg)))
9021 (defun downcase-dwim (arg)
9022 "Downcase words in the region, if active; if not, downcase word at point.
9023 If the region is active, this function calls `downcase-region'.
9024 Otherwise, it calls `downcase-word', with prefix argument passed to it
9025 to downcase ARG words."
9026 (interactive "*p")
9027 (if (use-region-p)
9028 (downcase-region (region-beginning) (region-end) (region-noncontiguous-p))
9029 (downcase-word arg)))
9031 (defun capitalize-dwim (arg)
9032 "Capitalize words in the region, if active; if not, capitalize word at point.
9033 If the region is active, this function calls `capitalize-region'.
9034 Otherwise, it calls `capitalize-word', with prefix argument passed to it
9035 to capitalize ARG words."
9036 (interactive "*p")
9037 (if (use-region-p)
9038 (capitalize-region (region-beginning) (region-end))
9039 (capitalize-word arg)))
9043 (provide 'simple)
9045 ;;; simple.el ends here