Add isearch-yank-symbol-or-char
[emacs.git] / lisp / simple.el
blob2101cfe83337d09b7e26b07b4a9fcdcf1cd81b8a
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].")
124 (make-variable-buffer-local 'next-error-last-buffer)
126 (defvar next-error-function nil
127 "Function to use to find the next error in the current buffer.
128 The function is called with 2 parameters:
129 ARG is an integer specifying by how many errors to move.
130 RESET is a boolean which, if non-nil, says to go back to the beginning
131 of the errors before moving.
132 Major modes providing compile-like functionality should set this variable
133 to indicate to `next-error' that this is a candidate buffer and how
134 to navigate in it.")
135 (make-variable-buffer-local 'next-error-function)
137 (defvar next-error-move-function nil
138 "Function to use to move to an error locus.
139 It takes two arguments, a buffer position in the error buffer
140 and a buffer position in the error locus buffer.
141 The buffer for the error locus should already be current.
142 nil means use goto-char using the second argument position.")
143 (make-variable-buffer-local 'next-error-move-function)
145 (defsubst next-error-buffer-p (buffer
146 &optional avoid-current
147 extra-test-inclusive
148 extra-test-exclusive)
149 "Return non-nil if BUFFER is a `next-error' capable buffer.
150 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
151 return nil.
153 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
154 BUFFER would not normally qualify. If it returns non-nil, BUFFER
155 is considered `next-error' capable, anyway, and the function
156 returns non-nil.
158 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
159 buffer would normally qualify. If it returns nil, BUFFER is
160 rejected, and the function returns nil."
161 (and (buffer-name buffer) ;First make sure it's live.
162 (not (and avoid-current (eq buffer (current-buffer))))
163 (with-current-buffer buffer
164 (if next-error-function ; This is the normal test.
165 ;; Optionally reject some buffers.
166 (if extra-test-exclusive
167 (funcall extra-test-exclusive)
169 ;; Optionally accept some other buffers.
170 (and extra-test-inclusive
171 (funcall extra-test-inclusive))))))
173 (defcustom next-error-find-buffer-function nil
174 "Function called to find a `next-error' capable buffer."
175 :type '(choice (const :tag "Single next-error capable buffer on selected frame"
176 next-error-buffer-on-selected-frame)
177 (const :tag "No default" nil)
178 (function :tag "Other function"))
179 :group 'next-error
180 :version "27.1")
182 (defun next-error-buffer-on-selected-frame (&optional avoid-current
183 extra-test-inclusive
184 extra-test-exclusive)
185 "Return a single visible next-error buffer on the selected frame."
186 (let ((window-buffers
187 (delete-dups
188 (delq nil (mapcar (lambda (w)
189 (if (next-error-buffer-p
190 (window-buffer w)
191 avoid-current
192 extra-test-inclusive extra-test-exclusive)
193 (window-buffer w)))
194 (window-list))))))
195 (if (eq (length window-buffers) 1)
196 (car window-buffers))))
198 (defun next-error-find-buffer (&optional avoid-current
199 extra-test-inclusive
200 extra-test-exclusive)
201 "Return a `next-error' capable buffer.
203 If AVOID-CURRENT is non-nil, treat the current buffer
204 as an absolute last resort only.
206 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
207 that normally would not qualify. If it returns t, the buffer
208 in question is treated as usable.
210 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
211 that would normally be considered usable. If it returns nil,
212 that buffer is rejected."
214 ;; 1. If a customizable function returns a buffer, use it.
215 (when next-error-find-buffer-function
216 (funcall next-error-find-buffer-function avoid-current
217 extra-test-inclusive
218 extra-test-exclusive))
219 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
220 (if (and next-error-last-buffer
221 (next-error-buffer-p next-error-last-buffer avoid-current
222 extra-test-inclusive extra-test-exclusive))
223 next-error-last-buffer)
224 ;; 3. If the current buffer is acceptable, choose it.
225 (if (next-error-buffer-p (current-buffer) avoid-current
226 extra-test-inclusive extra-test-exclusive)
227 (current-buffer))
228 ;; 4. Look for any acceptable buffer.
229 (let ((buffers (buffer-list)))
230 (while (and buffers
231 (not (next-error-buffer-p
232 (car buffers) avoid-current
233 extra-test-inclusive extra-test-exclusive)))
234 (setq buffers (cdr buffers)))
235 (car buffers))
236 ;; 5. Use the current buffer as a last resort if it qualifies,
237 ;; even despite AVOID-CURRENT.
238 (and avoid-current
239 (next-error-buffer-p (current-buffer) nil
240 extra-test-inclusive extra-test-exclusive)
241 (progn
242 (message "This is the only buffer with error message locations")
243 (current-buffer)))
244 ;; 6. Give up.
245 (error "No buffers contain error message locations")))
247 (defun next-error (&optional arg reset)
248 "Visit next `next-error' message and corresponding source code.
250 If all the error messages parsed so far have been processed already,
251 the message buffer is checked for new ones.
253 A prefix ARG specifies how many error messages to move;
254 negative means move back to previous error messages.
255 Just \\[universal-argument] as a prefix means reparse the error message buffer
256 and start at the first error.
258 The RESET argument specifies that we should restart from the beginning.
260 \\[next-error] normally uses the most recently started
261 compilation, grep, or occur buffer. It can also operate on any
262 buffer with output from the \\[compile], \\[grep] commands, or,
263 more generally, on any buffer in Compilation mode or with
264 Compilation Minor mode enabled, or any buffer in which
265 `next-error-function' is bound to an appropriate function.
266 To specify use of a particular buffer for error messages, type
267 \\[next-error] in that buffer when it is the only one displayed
268 in the current frame.
270 Once \\[next-error] has chosen the buffer for error messages, it
271 runs `next-error-hook' with `run-hooks', and stays with that buffer
272 until you use it in some other buffer which uses Compilation mode
273 or Compilation Minor mode.
275 To control which errors are matched, customize the variable
276 `compilation-error-regexp-alist'."
277 (interactive "P")
278 (if (consp arg) (setq reset t arg nil))
279 (let ((buffer (next-error-find-buffer)))
280 (when buffer
281 ;; We know here that next-error-function is a valid symbol we can funcall
282 (with-current-buffer buffer
283 ;; Allow next-error to be used from the next-error capable buffer.
284 (setq next-error-last-buffer buffer)
285 (funcall next-error-function (prefix-numeric-value arg) reset)
286 ;; Override possible change of next-error-last-buffer in next-error-function
287 (setq next-error-last-buffer buffer)
288 (setq-default next-error-last-buffer buffer)
289 (when next-error-recenter
290 (recenter next-error-recenter))
291 (message "%s error from %s"
292 (cond (reset "First")
293 ((eq (prefix-numeric-value arg) 0) "Current")
294 ((< (prefix-numeric-value arg) 0) "Previous")
295 (t "Next"))
296 next-error-last-buffer)
297 (run-hooks 'next-error-hook)))))
299 (defun next-error-internal ()
300 "Visit the source code corresponding to the `next-error' message at point."
301 (let ((buffer (current-buffer)))
302 ;; We know here that next-error-function is a valid symbol we can funcall
303 (with-current-buffer buffer
304 ;; Allow next-error to be used from the next-error capable buffer.
305 (setq next-error-last-buffer buffer)
306 (funcall next-error-function 0 nil)
307 ;; Override possible change of next-error-last-buffer in next-error-function
308 (setq next-error-last-buffer buffer)
309 (setq-default next-error-last-buffer buffer)
310 (when next-error-recenter
311 (recenter next-error-recenter))
312 (message "Current error from %s" next-error-last-buffer)
313 (run-hooks 'next-error-hook))))
315 (defun next-error-select-buffer (buffer)
316 "Select a `next-error' capable buffer and set it as the last used."
317 (interactive
318 (list (get-buffer
319 (read-buffer "Select next-error buffer: " nil nil
320 (lambda (b) (next-error-buffer-p (cdr b)))))))
321 (setq next-error-last-buffer buffer)
322 (setq-default next-error-last-buffer buffer))
324 (defalias 'goto-next-locus 'next-error)
325 (defalias 'next-match 'next-error)
327 (defun previous-error (&optional n)
328 "Visit previous `next-error' message and corresponding source code.
330 Prefix arg N says how many error messages to move backwards (or
331 forwards, if negative).
333 This operates on the output from the \\[compile] and \\[grep] commands."
334 (interactive "p")
335 (next-error (- (or n 1))))
337 (defun first-error (&optional n)
338 "Restart at the first error.
339 Visit corresponding source code.
340 With prefix arg N, visit the source code of the Nth error.
341 This operates on the output from the \\[compile] command, for instance."
342 (interactive "p")
343 (next-error n t))
345 (defun next-error-no-select (&optional n)
346 "Move point to the next error in the `next-error' buffer and highlight match.
347 Prefix arg N says how many error messages to move forwards (or
348 backwards, if negative).
349 Finds and highlights the source line like \\[next-error], but does not
350 select the source buffer."
351 (interactive "p")
352 (let ((next-error-highlight next-error-highlight-no-select))
353 (next-error n))
354 (pop-to-buffer next-error-last-buffer))
356 (defun previous-error-no-select (&optional n)
357 "Move point to the previous error in the `next-error' buffer and highlight match.
358 Prefix arg N says how many error messages to move backwards (or
359 forwards, if negative).
360 Finds and highlights the source line like \\[previous-error], but does not
361 select the source buffer."
362 (interactive "p")
363 (next-error-no-select (- (or n 1))))
365 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
366 (defvar next-error-follow-last-line nil)
368 (define-minor-mode next-error-follow-minor-mode
369 "Minor mode for compilation, occur and diff modes.
370 With a prefix argument ARG, enable mode if ARG is positive, and
371 disable it otherwise. If called from Lisp, enable mode if ARG is
372 omitted or nil.
373 When turned on, cursor motion in the compilation, grep, occur or diff
374 buffer causes automatic display of the corresponding source code location."
375 :group 'next-error :init-value nil :lighter " Fol"
376 (if (not next-error-follow-minor-mode)
377 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
378 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
379 (make-local-variable 'next-error-follow-last-line)))
381 ;; Used as a `post-command-hook' by `next-error-follow-mode'
382 ;; for the *Compilation* *grep* and *Occur* buffers.
383 (defun next-error-follow-mode-post-command-hook ()
384 (unless (equal next-error-follow-last-line (line-number-at-pos))
385 (setq next-error-follow-last-line (line-number-at-pos))
386 (condition-case nil
387 (let ((compilation-context-lines nil))
388 (setq compilation-current-error (point))
389 (next-error-no-select 0))
390 (error t))))
395 (defun fundamental-mode ()
396 "Major mode not specialized for anything in particular.
397 Other major modes are defined by comparison with this one."
398 (interactive)
399 (kill-all-local-variables)
400 (run-mode-hooks))
402 ;; Special major modes to view specially formatted data rather than files.
404 (defvar special-mode-map
405 (let ((map (make-sparse-keymap)))
406 (suppress-keymap map)
407 (define-key map "q" 'quit-window)
408 (define-key map " " 'scroll-up-command)
409 (define-key map [?\S-\ ] 'scroll-down-command)
410 (define-key map "\C-?" 'scroll-down-command)
411 (define-key map "?" 'describe-mode)
412 (define-key map "h" 'describe-mode)
413 (define-key map ">" 'end-of-buffer)
414 (define-key map "<" 'beginning-of-buffer)
415 (define-key map "g" 'revert-buffer)
416 map))
418 (put 'special-mode 'mode-class 'special)
419 (define-derived-mode special-mode nil "Special"
420 "Parent major mode from which special major modes should inherit."
421 (setq buffer-read-only t))
423 ;; Making and deleting lines.
425 (defvar self-insert-uses-region-functions nil
426 "Special hook to tell if `self-insert-command' will use the region.
427 It must be called via `run-hook-with-args-until-success' with no arguments.
429 If any function on this hook returns a non-nil value, `delete-selection-mode'
430 will act on that value (see `delete-selection-helper'), and will
431 usually delete the region. If all the functions on this hook return
432 nil, it is an indiction that `self-insert-command' needs the region
433 untouched by `delete-selection-mode', and will itself do whatever is
434 appropriate with the region.
435 Any function on `post-self-insert-hook' which act on the region should
436 add a function to this hook so that `delete-selection-mode' could
437 refrain from deleting the region before `post-self-insert-hook'
438 functions are called.
439 This hook is run by `delete-selection-uses-region-p', which see.")
441 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
442 "Propertized string representing a hard newline character.")
444 (defun newline (&optional arg interactive)
445 "Insert a newline, and move to left margin of the new line if it's blank.
446 If option `use-hard-newlines' is non-nil, the newline is marked with the
447 text-property `hard'.
448 With ARG, insert that many newlines.
450 If `electric-indent-mode' is enabled, this indents the final new line
451 that it adds, and reindents the preceding line. To just insert
452 a newline, use \\[electric-indent-just-newline].
454 Calls `auto-fill-function' if the current column number is greater
455 than the value of `fill-column' and ARG is nil.
456 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
457 (interactive "*P\np")
458 (barf-if-buffer-read-only)
459 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
460 ;; Set last-command-event to tell self-insert what to insert.
461 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
462 (beforepos (point))
463 (last-command-event ?\n)
464 ;; Don't auto-fill if we have a numeric argument.
465 (auto-fill-function (if arg nil auto-fill-function))
466 (arg (prefix-numeric-value arg))
467 (postproc
468 ;; Do the rest in post-self-insert-hook, because we want to do it
469 ;; *before* other functions on that hook.
470 (lambda ()
471 ;; Mark the newline(s) `hard'.
472 (if use-hard-newlines
473 (set-hard-newline-properties
474 (- (point) arg) (point)))
475 ;; If the newline leaves the previous line blank, and we
476 ;; have a left margin, delete that from the blank line.
477 (save-excursion
478 (goto-char beforepos)
479 (beginning-of-line)
480 (and (looking-at "[ \t]$")
481 (> (current-left-margin) 0)
482 (delete-region (point)
483 (line-end-position))))
484 ;; Indent the line after the newline, except in one case:
485 ;; when we added the newline at the beginning of a line which
486 ;; starts a page.
487 (or was-page-start
488 (move-to-left-margin nil t)))))
489 (if (not interactive)
490 ;; FIXME: For non-interactive uses, many calls actually
491 ;; just want (insert "\n"), so maybe we should do just
492 ;; that, so as to avoid the risk of filling or running
493 ;; abbrevs unexpectedly.
494 (let ((post-self-insert-hook (list postproc)))
495 (self-insert-command arg))
496 (unwind-protect
497 (progn
498 (add-hook 'post-self-insert-hook postproc nil t)
499 (self-insert-command arg))
500 ;; We first used let-binding to protect the hook, but that
501 ;; was naive since add-hook affects the symbol-default
502 ;; value of the variable, whereas the let-binding might
503 ;; only protect the buffer-local value.
504 (remove-hook 'post-self-insert-hook postproc t))))
505 nil)
507 (defun set-hard-newline-properties (from to)
508 (let ((sticky (get-text-property from 'rear-nonsticky)))
509 (put-text-property from to 'hard 't)
510 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
511 (if (and (listp sticky) (not (memq 'hard sticky)))
512 (put-text-property from (point) 'rear-nonsticky
513 (cons 'hard sticky)))))
515 (defun open-line (n)
516 "Insert a newline and leave point before it.
517 If there is a fill prefix and/or a `left-margin', insert them on
518 the new line if the line would have been blank.
519 With arg N, insert N newlines."
520 (interactive "*p")
521 (let* ((do-fill-prefix (and fill-prefix (bolp)))
522 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
523 (loc (point-marker))
524 ;; Don't expand an abbrev before point.
525 (abbrev-mode nil))
526 (newline n)
527 (goto-char loc)
528 (while (> n 0)
529 (cond ((bolp)
530 (if do-left-margin (indent-to (current-left-margin)))
531 (if do-fill-prefix (insert-and-inherit fill-prefix))))
532 (forward-line 1)
533 (setq n (1- n)))
534 (goto-char loc)
535 ;; Necessary in case a margin or prefix was inserted.
536 (end-of-line)))
538 (defun split-line (&optional arg)
539 "Split current line, moving portion beyond point vertically down.
540 If the current line starts with `fill-prefix', insert it on the new
541 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
543 When called from Lisp code, ARG may be a prefix string to copy."
544 (interactive "*P")
545 (skip-chars-forward " \t")
546 (let* ((col (current-column))
547 (pos (point))
548 ;; What prefix should we check for (nil means don't).
549 (prefix (cond ((stringp arg) arg)
550 (arg nil)
551 (t fill-prefix)))
552 ;; Does this line start with it?
553 (have-prfx (and prefix
554 (save-excursion
555 (beginning-of-line)
556 (looking-at (regexp-quote prefix))))))
557 (newline 1)
558 (if have-prfx (insert-and-inherit prefix))
559 (indent-to col 0)
560 (goto-char pos)))
562 (defun delete-indentation (&optional arg)
563 "Join this line to previous and fix up whitespace at join.
564 If there is a fill prefix, delete it from the beginning of this line.
565 With argument, join this line to following line."
566 (interactive "*P")
567 (beginning-of-line)
568 (if arg (forward-line 1))
569 (if (eq (preceding-char) ?\n)
570 (progn
571 (delete-region (point) (1- (point)))
572 ;; If the second line started with the fill prefix,
573 ;; delete the prefix.
574 (if (and fill-prefix
575 (<= (+ (point) (length fill-prefix)) (point-max))
576 (string= fill-prefix
577 (buffer-substring (point)
578 (+ (point) (length fill-prefix)))))
579 (delete-region (point) (+ (point) (length fill-prefix))))
580 (fixup-whitespace))))
582 (defalias 'join-line #'delete-indentation) ; easier to find
584 (defun delete-blank-lines ()
585 "On blank line, delete all surrounding blank lines, leaving just one.
586 On isolated blank line, delete that one.
587 On nonblank line, delete any immediately following blank lines."
588 (interactive "*")
589 (let (thisblank singleblank)
590 (save-excursion
591 (beginning-of-line)
592 (setq thisblank (looking-at "[ \t]*$"))
593 ;; Set singleblank if there is just one blank line here.
594 (setq singleblank
595 (and thisblank
596 (not (looking-at "[ \t]*\n[ \t]*$"))
597 (or (bobp)
598 (progn (forward-line -1)
599 (not (looking-at "[ \t]*$")))))))
600 ;; Delete preceding blank lines, and this one too if it's the only one.
601 (if thisblank
602 (progn
603 (beginning-of-line)
604 (if singleblank (forward-line 1))
605 (delete-region (point)
606 (if (re-search-backward "[^ \t\n]" nil t)
607 (progn (forward-line 1) (point))
608 (point-min)))))
609 ;; Delete following blank lines, unless the current line is blank
610 ;; and there are no following blank lines.
611 (if (not (and thisblank singleblank))
612 (save-excursion
613 (end-of-line)
614 (forward-line 1)
615 (delete-region (point)
616 (if (re-search-forward "[^ \t\n]" nil t)
617 (progn (beginning-of-line) (point))
618 (point-max)))))
619 ;; Handle the special case where point is followed by newline and eob.
620 ;; Delete the line, leaving point at eob.
621 (if (looking-at "^[ \t]*\n\\'")
622 (delete-region (point) (point-max)))))
624 (defcustom delete-trailing-lines t
625 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
626 Trailing lines are deleted only if `delete-trailing-whitespace'
627 is called on the entire buffer (rather than an active region)."
628 :type 'boolean
629 :group 'editing
630 :version "24.3")
632 (defun region-modifiable-p (start end)
633 "Return non-nil if the region contains no read-only text."
634 (and (not (get-text-property start 'read-only))
635 (eq end (next-single-property-change start 'read-only nil end))))
637 (defun delete-trailing-whitespace (&optional start end)
638 "Delete trailing whitespace between START and END.
639 If called interactively, START and END are the start/end of the
640 region if the mark is active, or of the buffer's accessible
641 portion if the mark is inactive.
643 This command deletes whitespace characters after the last
644 non-whitespace character in each line between START and END. It
645 does not consider formfeed characters to be whitespace.
647 If this command acts on the entire buffer (i.e. if called
648 interactively with the mark inactive, or called from Lisp with
649 END nil), it also deletes all trailing lines at the end of the
650 buffer if the variable `delete-trailing-lines' is non-nil."
651 (interactive (progn
652 (barf-if-buffer-read-only)
653 (if (use-region-p)
654 (list (region-beginning) (region-end))
655 (list nil nil))))
656 (save-match-data
657 (save-excursion
658 (let ((end-marker (and end (copy-marker end))))
659 (goto-char (or start (point-min)))
660 (with-syntax-table (make-syntax-table (syntax-table))
661 ;; Don't delete formfeeds, even if they are considered whitespace.
662 (modify-syntax-entry ?\f "_")
663 (while (re-search-forward "\\s-$" end-marker t)
664 (skip-syntax-backward "-" (line-beginning-position))
665 (let ((b (point)) (e (match-end 0)))
666 (when (region-modifiable-p b e)
667 (delete-region b e)))))
668 (if end
669 (set-marker end-marker nil)
670 ;; Delete trailing empty lines.
671 (and delete-trailing-lines
672 ;; Really the end of buffer.
673 (= (goto-char (point-max)) (1+ (buffer-size)))
674 (<= (skip-chars-backward "\n") -2)
675 (region-modifiable-p (1+ (point)) (point-max))
676 (delete-region (1+ (point)) (point-max)))))))
677 ;; Return nil for the benefit of `write-file-functions'.
678 nil)
680 (defun newline-and-indent ()
681 "Insert a newline, then indent according to major mode.
682 Indentation is done using the value of `indent-line-function'.
683 In programming language modes, this is the same as TAB.
684 In some text modes, where TAB inserts a tab, this command indents to the
685 column specified by the function `current-left-margin'."
686 (interactive "*")
687 (delete-horizontal-space t)
688 (newline nil t)
689 (indent-according-to-mode))
691 (defun reindent-then-newline-and-indent ()
692 "Reindent current line, insert newline, then indent the new line.
693 Indentation of both lines is done according to the current major mode,
694 which means calling the current value of `indent-line-function'.
695 In programming language modes, this is the same as TAB.
696 In some text modes, where TAB inserts a tab, this indents to the
697 column specified by the function `current-left-margin'."
698 (interactive "*")
699 (let ((pos (point)))
700 ;; Be careful to insert the newline before indenting the line.
701 ;; Otherwise, the indentation might be wrong.
702 (newline)
703 (save-excursion
704 (goto-char pos)
705 ;; We are at EOL before the call to indent-according-to-mode, and
706 ;; after it we usually are as well, but not always. We tried to
707 ;; address it with `save-excursion' but that uses a normal marker
708 ;; whereas we need `move after insertion', so we do the save/restore
709 ;; by hand.
710 (setq pos (copy-marker pos t))
711 (indent-according-to-mode)
712 (goto-char pos)
713 ;; Remove the trailing white-space after indentation because
714 ;; indentation may introduce the whitespace.
715 (delete-horizontal-space t))
716 (indent-according-to-mode)))
718 (defcustom read-quoted-char-radix 8
719 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
720 Legitimate radix values are 8, 10 and 16."
721 :type '(choice (const 8) (const 10) (const 16))
722 :group 'editing-basics)
724 (defun read-quoted-char (&optional prompt)
725 "Like `read-char', but do not allow quitting.
726 Also, if the first character read is an octal digit,
727 we read any number of octal digits and return the
728 specified character code. Any nondigit terminates the sequence.
729 If the terminator is RET, it is discarded;
730 any other terminator is used itself as input.
732 The optional argument PROMPT specifies a string to use to prompt the user.
733 The variable `read-quoted-char-radix' controls which radix to use
734 for numeric input."
735 (let ((message-log-max nil)
736 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
737 help-event-list)))
738 done (first t) (code 0) char translated)
739 (while (not done)
740 (let ((inhibit-quit first)
741 ;; Don't let C-h or other help chars get the help
742 ;; message--only help function keys. See bug#16617.
743 (help-char nil)
744 (help-event-list help-events)
745 (help-form
746 "Type the special character you want to use,
747 or the octal character code.
748 RET terminates the character code and is discarded;
749 any other non-digit terminates the character code and is then used as input."))
750 (setq char (read-event (and prompt (format "%s-" prompt)) t))
751 (if inhibit-quit (setq quit-flag nil)))
752 ;; Translate TAB key into control-I ASCII character, and so on.
753 ;; Note: `read-char' does it using the `ascii-character' property.
754 ;; We tried using read-key instead, but that disables the keystroke
755 ;; echo produced by 'C-q', see bug#24635.
756 (let ((translation (lookup-key local-function-key-map (vector char))))
757 (setq translated (if (arrayp translation)
758 (aref translation 0)
759 char)))
760 (if (integerp translated)
761 (setq translated (char-resolve-modifiers translated)))
762 (cond ((null translated))
763 ((not (integerp translated))
764 (setq unread-command-events (list char)
765 done t))
766 ((/= (logand translated ?\M-\^@) 0)
767 ;; Turn a meta-character into a character with the 0200 bit set.
768 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
769 done t))
770 ((and (<= ?0 translated)
771 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
772 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
773 (and prompt (setq prompt (message "%s %c" prompt translated))))
774 ((and (<= ?a (downcase translated))
775 (< (downcase translated)
776 (+ ?a -10 (min 36 read-quoted-char-radix))))
777 (setq code (+ (* code read-quoted-char-radix)
778 (+ 10 (- (downcase translated) ?a))))
779 (and prompt (setq prompt (message "%s %c" prompt translated))))
780 ((and (not first) (eq translated ?\C-m))
781 (setq done t))
782 ((not first)
783 (setq unread-command-events (list char)
784 done t))
785 (t (setq code translated
786 done t)))
787 (setq first nil))
788 code))
790 (defun quoted-insert (arg)
791 "Read next input character and insert it.
792 This is useful for inserting control characters.
793 With argument, insert ARG copies of the character.
795 If the first character you type after this command is an octal digit,
796 you should type a sequence of octal digits which specify a character code.
797 Any nondigit terminates the sequence. If the terminator is a RET,
798 it is discarded; any other terminator is used itself as input.
799 The variable `read-quoted-char-radix' specifies the radix for this feature;
800 set it to 10 or 16 to use decimal or hex instead of octal.
802 In overwrite mode, this function inserts the character anyway, and
803 does not handle octal digits specially. This means that if you use
804 overwrite as your normal editing mode, you can use this function to
805 insert characters when necessary.
807 In binary overwrite mode, this function does overwrite, and octal
808 digits are interpreted as a character code. This is intended to be
809 useful for editing binary files."
810 (interactive "*p")
811 (let* ((char
812 ;; Avoid "obsolete" warnings for translation-table-for-input.
813 (with-no-warnings
814 (let (translation-table-for-input input-method-function)
815 (if (or (not overwrite-mode)
816 (eq overwrite-mode 'overwrite-mode-binary))
817 (read-quoted-char)
818 (read-char))))))
819 ;; This used to assume character codes 0240 - 0377 stand for
820 ;; characters in some single-byte character set, and converted them
821 ;; to Emacs characters. But in 23.1 this feature is deprecated
822 ;; in favor of inserting the corresponding Unicode characters.
823 ;; (if (and enable-multibyte-characters
824 ;; (>= char ?\240)
825 ;; (<= char ?\377))
826 ;; (setq char (unibyte-char-to-multibyte char)))
827 (unless (characterp char)
828 (user-error "%s is not a valid character"
829 (key-description (vector char))))
830 (if (> arg 0)
831 (if (eq overwrite-mode 'overwrite-mode-binary)
832 (delete-char arg)))
833 (while (> arg 0)
834 (insert-and-inherit char)
835 (setq arg (1- arg)))))
837 (defun forward-to-indentation (&optional arg)
838 "Move forward ARG lines and position at first nonblank character."
839 (interactive "^p")
840 (forward-line (or arg 1))
841 (skip-chars-forward " \t"))
843 (defun backward-to-indentation (&optional arg)
844 "Move backward ARG lines and position at first nonblank character."
845 (interactive "^p")
846 (forward-line (- (or arg 1)))
847 (skip-chars-forward " \t"))
849 (defun back-to-indentation ()
850 "Move point to the first non-whitespace character on this line."
851 (interactive "^")
852 (beginning-of-line 1)
853 (skip-syntax-forward " " (line-end-position))
854 ;; Move back over chars that have whitespace syntax but have the p flag.
855 (backward-prefix-chars))
857 (defun fixup-whitespace ()
858 "Fixup white space between objects around point.
859 Leave one space or none, according to the context."
860 (interactive "*")
861 (save-excursion
862 (delete-horizontal-space)
863 (if (or (looking-at "^\\|$\\|\\s)")
864 (save-excursion (forward-char -1)
865 (looking-at "$\\|\\s(\\|\\s'")))
867 (insert ?\s))))
869 (defun delete-horizontal-space (&optional backward-only)
870 "Delete all spaces and tabs around point.
871 If BACKWARD-ONLY is non-nil, only delete them before point."
872 (interactive "*P")
873 (let ((orig-pos (point)))
874 (delete-region
875 (if backward-only
876 orig-pos
877 (progn
878 (skip-chars-forward " \t")
879 (constrain-to-field nil orig-pos t)))
880 (progn
881 (skip-chars-backward " \t")
882 (constrain-to-field nil orig-pos)))))
884 (defun just-one-space (&optional n)
885 "Delete all spaces and tabs around point, leaving one space (or N spaces).
886 If N is negative, delete newlines as well, leaving -N spaces.
887 See also `cycle-spacing'."
888 (interactive "*p")
889 (cycle-spacing n nil 'single-shot))
891 (defvar cycle-spacing--context nil
892 "Store context used in consecutive calls to `cycle-spacing' command.
893 The first time `cycle-spacing' runs, it saves in this variable:
894 its N argument, the original point position, and the original spacing
895 around point.")
897 (defun cycle-spacing (&optional n preserve-nl-back mode)
898 "Manipulate whitespace around point in a smart way.
899 In interactive use, this function behaves differently in successive
900 consecutive calls.
902 The first call in a sequence acts like `just-one-space'.
903 It deletes all spaces and tabs around point, leaving one space
904 \(or N spaces). N is the prefix argument. If N is negative,
905 it deletes newlines as well, leaving -N spaces.
906 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
908 The second call in a sequence deletes all spaces.
910 The third call in a sequence restores the original whitespace (and point).
912 If MODE is `single-shot', it only performs the first step in the sequence.
913 If MODE is `fast' and the first step would not result in any change
914 \(i.e., there are exactly (abs N) spaces around point),
915 the function goes straight to the second step.
917 Repeatedly calling the function with different values of N starts a
918 new sequence each time."
919 (interactive "*p")
920 (let ((orig-pos (point))
921 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
922 (num (abs (or n 1))))
923 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
924 (constrain-to-field nil orig-pos)
925 (cond
926 ;; Command run for the first time, single-shot mode or different argument
927 ((or (eq 'single-shot mode)
928 (not (equal last-command this-command))
929 (not cycle-spacing--context)
930 (not (eq (car cycle-spacing--context) n)))
931 (let* ((start (point))
932 (num (- num (skip-chars-forward " " (+ num (point)))))
933 (mid (point))
934 (end (progn
935 (skip-chars-forward skip-characters)
936 (constrain-to-field nil orig-pos t))))
937 (setq cycle-spacing--context ;; Save for later.
938 ;; Special handling for case where there was no space at all.
939 (unless (= start end)
940 (cons n (cons orig-pos (buffer-substring start (point))))))
941 ;; If this run causes no change in buffer content, delete all spaces,
942 ;; otherwise delete all excess spaces.
943 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
944 start mid) end)
945 (insert (make-string num ?\s))))
947 ;; Command run for the second time.
948 ((not (equal orig-pos (point)))
949 (delete-region (point) orig-pos))
951 ;; Command run for the third time.
953 (insert (cddr cycle-spacing--context))
954 (goto-char (cadr cycle-spacing--context))
955 (setq cycle-spacing--context nil)))))
957 (defun beginning-of-buffer (&optional arg)
958 "Move point to the beginning of the buffer.
959 With numeric arg N, put point N/10 of the way from the beginning.
960 If the buffer is narrowed, this command uses the beginning of the
961 accessible part of the buffer.
963 Push mark at previous position, unless either a \\[universal-argument] prefix
964 is supplied, or Transient Mark mode is enabled and the mark is active."
965 (declare (interactive-only "use `(goto-char (point-min))' instead."))
966 (interactive "^P")
967 (or (consp arg)
968 (region-active-p)
969 (push-mark))
970 (let ((size (- (point-max) (point-min))))
971 (goto-char (if (and arg (not (consp arg)))
972 (+ (point-min)
973 (if (> size 10000)
974 ;; Avoid overflow for large buffer sizes!
975 (* (prefix-numeric-value arg)
976 (/ size 10))
977 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
978 (point-min))))
979 (if (and arg (not (consp arg))) (forward-line 1)))
981 (defun end-of-buffer (&optional arg)
982 "Move point to the end of the buffer.
983 With numeric arg N, put point N/10 of the way from the end.
984 If the buffer is narrowed, this command uses the end of the
985 accessible part of the buffer.
987 Push mark at previous position, unless either a \\[universal-argument] prefix
988 is supplied, or Transient Mark mode is enabled and the mark is active."
989 (declare (interactive-only "use `(goto-char (point-max))' instead."))
990 (interactive "^P")
991 (or (consp arg) (region-active-p) (push-mark))
992 (let ((size (- (point-max) (point-min))))
993 (goto-char (if (and arg (not (consp arg)))
994 (- (point-max)
995 (if (> size 10000)
996 ;; Avoid overflow for large buffer sizes!
997 (* (prefix-numeric-value arg)
998 (/ size 10))
999 (/ (* size (prefix-numeric-value arg)) 10)))
1000 (point-max))))
1001 ;; If we went to a place in the middle of the buffer,
1002 ;; adjust it to the beginning of a line.
1003 (cond ((and arg (not (consp arg))) (forward-line 1))
1004 ((and (eq (current-buffer) (window-buffer))
1005 (> (point) (window-end nil t)))
1006 ;; If the end of the buffer is not already on the screen,
1007 ;; then scroll specially to put it near, but not at, the bottom.
1008 (overlay-recenter (point))
1009 (recenter -3))))
1011 (defcustom delete-active-region t
1012 "Whether single-char deletion commands delete an active region.
1013 This has an effect only if Transient Mark mode is enabled, and
1014 affects `delete-forward-char' and `delete-backward-char', though
1015 not `delete-char'.
1017 If the value is the symbol `kill', the active region is killed
1018 instead of deleted."
1019 :type '(choice (const :tag "Delete active region" t)
1020 (const :tag "Kill active region" kill)
1021 (const :tag "Do ordinary deletion" nil))
1022 :group 'killing
1023 :version "24.1")
1025 (defvar region-extract-function
1026 (lambda (method)
1027 (when (region-beginning)
1028 (cond
1029 ((eq method 'bounds)
1030 (list (cons (region-beginning) (region-end))))
1031 ((eq method 'delete-only)
1032 (delete-region (region-beginning) (region-end)))
1034 (filter-buffer-substring (region-beginning) (region-end) method)))))
1035 "Function to get the region's content.
1036 Called with one argument METHOD.
1037 If METHOD is `delete-only', then delete the region; the return value
1038 is undefined. If METHOD is nil, then return the content as a string.
1039 If METHOD is `bounds', then return the boundaries of the region
1040 as a list of cons cells of the form (START . END).
1041 If METHOD is anything else, delete the region and return its content
1042 as a string, after filtering it with `filter-buffer-substring', which
1043 is called with METHOD as its 3rd argument.")
1045 (defvar region-insert-function
1046 (lambda (lines)
1047 (let ((first t))
1048 (while lines
1049 (or first
1050 (insert ?\n))
1051 (insert-for-yank (car lines))
1052 (setq lines (cdr lines)
1053 first nil))))
1054 "Function to insert the region's content.
1055 Called with one argument LINES.
1056 Insert the region as a list of lines.")
1058 (defun delete-backward-char (n &optional killflag)
1059 "Delete the previous N characters (following if N is negative).
1060 If Transient Mark mode is enabled, the mark is active, and N is 1,
1061 delete the text in the region and deactivate the mark instead.
1062 To disable this, set option `delete-active-region' to nil.
1064 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1065 kill ring) instead of delete. Interactively, N is the prefix
1066 arg, and KILLFLAG is set if N is explicitly specified.
1068 When killing, the killed text is filtered by
1069 `filter-buffer-substring' before it is saved in the kill ring, so
1070 the actual saved text might be different from what was killed.
1072 In Overwrite mode, single character backward deletion may replace
1073 tabs with spaces so as to back over columns, unless point is at
1074 the end of the line."
1075 (declare (interactive-only delete-char))
1076 (interactive "p\nP")
1077 (unless (integerp n)
1078 (signal 'wrong-type-argument (list 'integerp n)))
1079 (cond ((and (use-region-p)
1080 delete-active-region
1081 (= n 1))
1082 ;; If a region is active, kill or delete it.
1083 (if (eq delete-active-region 'kill)
1084 (kill-region (region-beginning) (region-end) 'region)
1085 (funcall region-extract-function 'delete-only)))
1086 ;; In Overwrite mode, maybe untabify while deleting
1087 ((null (or (null overwrite-mode)
1088 (<= n 0)
1089 (memq (char-before) '(?\t ?\n))
1090 (eobp)
1091 (eq (char-after) ?\n)))
1092 (let ((ocol (current-column)))
1093 (delete-char (- n) killflag)
1094 (save-excursion
1095 (insert-char ?\s (- ocol (current-column)) nil))))
1096 ;; Otherwise, do simple deletion.
1097 (t (delete-char (- n) killflag))))
1099 (defun delete-forward-char (n &optional killflag)
1100 "Delete the following N characters (previous if N is negative).
1101 If Transient Mark mode is enabled, the mark is active, and N is 1,
1102 delete the text in the region and deactivate the mark instead.
1103 To disable this, set variable `delete-active-region' to nil.
1105 Optional second arg KILLFLAG non-nil means to kill (save in kill
1106 ring) instead of delete. Interactively, N is the prefix arg, and
1107 KILLFLAG is set if N was explicitly specified.
1109 When killing, the killed text is filtered by
1110 `filter-buffer-substring' before it is saved in the kill ring, so
1111 the actual saved text might be different from what was killed."
1112 (declare (interactive-only delete-char))
1113 (interactive "p\nP")
1114 (unless (integerp n)
1115 (signal 'wrong-type-argument (list 'integerp n)))
1116 (cond ((and (use-region-p)
1117 delete-active-region
1118 (= n 1))
1119 ;; If a region is active, kill or delete it.
1120 (if (eq delete-active-region 'kill)
1121 (kill-region (region-beginning) (region-end) 'region)
1122 (funcall region-extract-function 'delete-only)))
1124 ;; Otherwise, do simple deletion.
1125 (t (delete-char n killflag))))
1127 (defun mark-whole-buffer ()
1128 "Put point at beginning and mark at end of buffer.
1129 If narrowing is in effect, only uses the accessible part of the buffer.
1130 You probably should not use this function in Lisp programs;
1131 it is usually a mistake for a Lisp function to use any subroutine
1132 that uses or sets the mark."
1133 (declare (interactive-only t))
1134 (interactive)
1135 (push-mark)
1136 (push-mark (point-max) nil t)
1137 ;; This is really `point-min' in most cases, but if we're in the
1138 ;; minibuffer, this is at the end of the prompt.
1139 (goto-char (minibuffer-prompt-end)))
1142 ;; Counting lines, one way or another.
1144 (defun goto-line (line &optional buffer)
1145 "Go to LINE, counting from line 1 at beginning of buffer.
1146 If called interactively, a numeric prefix argument specifies
1147 LINE; without a numeric prefix argument, read LINE from the
1148 minibuffer.
1150 If optional argument BUFFER is non-nil, switch to that buffer and
1151 move to line LINE there. If called interactively with \\[universal-argument]
1152 as argument, BUFFER is the most recently selected other buffer.
1154 Prior to moving point, this function sets the mark (without
1155 activating it), unless Transient Mark mode is enabled and the
1156 mark is already active.
1158 This function is usually the wrong thing to use in a Lisp program.
1159 What you probably want instead is something like:
1160 (goto-char (point-min))
1161 (forward-line (1- N))
1162 If at all possible, an even better solution is to use char counts
1163 rather than line counts."
1164 (declare (interactive-only forward-line))
1165 (interactive
1166 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1167 (list (prefix-numeric-value current-prefix-arg))
1168 ;; Look for a default, a number in the buffer at point.
1169 (let* ((default
1170 (save-excursion
1171 (skip-chars-backward "0-9")
1172 (if (looking-at "[0-9]")
1173 (string-to-number
1174 (buffer-substring-no-properties
1175 (point)
1176 (progn (skip-chars-forward "0-9")
1177 (point)))))))
1178 ;; Decide if we're switching buffers.
1179 (buffer
1180 (if (consp current-prefix-arg)
1181 (other-buffer (current-buffer) t)))
1182 (buffer-prompt
1183 (if buffer
1184 (concat " in " (buffer-name buffer))
1185 "")))
1186 ;; Read the argument, offering that number (if any) as default.
1187 (list (read-number (format "Goto line%s: " buffer-prompt)
1188 (list default (line-number-at-pos)))
1189 buffer))))
1190 ;; Switch to the desired buffer, one way or another.
1191 (if buffer
1192 (let ((window (get-buffer-window buffer)))
1193 (if window (select-window window)
1194 (switch-to-buffer-other-window buffer))))
1195 ;; Leave mark at previous position
1196 (or (region-active-p) (push-mark))
1197 ;; Move to the specified line number in that buffer.
1198 (save-restriction
1199 (widen)
1200 (goto-char (point-min))
1201 (if (eq selective-display t)
1202 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1203 (forward-line (1- line)))))
1205 (defun count-words-region (start end &optional arg)
1206 "Count the number of words in the region.
1207 If called interactively, print a message reporting the number of
1208 lines, words, and characters in the region (whether or not the
1209 region is active); with prefix ARG, report for the entire buffer
1210 rather than the region.
1212 If called from Lisp, return the number of words between positions
1213 START and END."
1214 (interactive (if current-prefix-arg
1215 (list nil nil current-prefix-arg)
1216 (list (region-beginning) (region-end) nil)))
1217 (cond ((not (called-interactively-p 'any))
1218 (count-words start end))
1219 (arg
1220 (count-words--buffer-message))
1222 (count-words--message "Region" start end))))
1224 (defun count-words (start end)
1225 "Count words between START and END.
1226 If called interactively, START and END are normally the start and
1227 end of the buffer; but if the region is active, START and END are
1228 the start and end of the region. Print a message reporting the
1229 number of lines, words, and chars.
1231 If called from Lisp, return the number of words between START and
1232 END, without printing any message."
1233 (interactive (list nil nil))
1234 (cond ((not (called-interactively-p 'any))
1235 (let ((words 0))
1236 (save-excursion
1237 (save-restriction
1238 (narrow-to-region start end)
1239 (goto-char (point-min))
1240 (while (forward-word-strictly 1)
1241 (setq words (1+ words)))))
1242 words))
1243 ((use-region-p)
1244 (call-interactively 'count-words-region))
1246 (count-words--buffer-message))))
1248 (defun count-words--buffer-message ()
1249 (count-words--message
1250 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1251 (point-min) (point-max)))
1253 (defun count-words--message (str start end)
1254 (let ((lines (count-lines start end))
1255 (words (count-words start end))
1256 (chars (- end start)))
1257 (message "%s has %d line%s, %d word%s, and %d character%s."
1259 lines (if (= lines 1) "" "s")
1260 words (if (= words 1) "" "s")
1261 chars (if (= chars 1) "" "s"))))
1263 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1265 (defun what-line ()
1266 "Print the current buffer line number and narrowed line number of point."
1267 (interactive)
1268 (let ((start (point-min))
1269 (n (line-number-at-pos)))
1270 (if (= start 1)
1271 (message "Line %d" n)
1272 (save-excursion
1273 (save-restriction
1274 (widen)
1275 (message "line %d (narrowed line %d)"
1276 (+ n (line-number-at-pos start) -1) n))))))
1278 (defun count-lines (start end)
1279 "Return number of lines between START and END.
1280 This is usually the number of newlines between them,
1281 but can be one more if START is not equal to END
1282 and the greater of them is not at the start of a line."
1283 (save-excursion
1284 (save-restriction
1285 (narrow-to-region start end)
1286 (goto-char (point-min))
1287 (if (eq selective-display t)
1288 (save-match-data
1289 (let ((done 0))
1290 (while (re-search-forward "[\n\C-m]" nil t 40)
1291 (setq done (+ 40 done)))
1292 (while (re-search-forward "[\n\C-m]" nil t 1)
1293 (setq done (+ 1 done)))
1294 (goto-char (point-max))
1295 (if (and (/= start end)
1296 (not (bolp)))
1297 (1+ done)
1298 done)))
1299 (- (buffer-size) (forward-line (buffer-size)))))))
1301 (defun line-number-at-pos (&optional pos absolute)
1302 "Return buffer line number at position POS.
1303 If POS is nil, use current buffer location.
1305 If ABSOLUTE is nil, the default, counting starts
1306 at (point-min), so the value refers to the contents of the
1307 accessible portion of the (potentially narrowed) buffer. If
1308 ABSOLUTE is non-nil, ignore any narrowing and return the
1309 absolute line number."
1310 (save-restriction
1311 (when absolute
1312 (widen))
1313 (let ((opoint (or pos (point))) start)
1314 (save-excursion
1315 (goto-char (point-min))
1316 (setq start (point))
1317 (goto-char opoint)
1318 (forward-line 0)
1319 (1+ (count-lines start (point)))))))
1321 (defun what-cursor-position (&optional detail)
1322 "Print info on cursor position (on screen and within buffer).
1323 Also describe the character after point, and give its character code
1324 in octal, decimal and hex.
1326 For a non-ASCII multibyte character, also give its encoding in the
1327 buffer's selected coding system if the coding system encodes the
1328 character safely. If the character is encoded into one byte, that
1329 code is shown in hex. If the character is encoded into more than one
1330 byte, just \"...\" is shown.
1332 In addition, with prefix argument, show details about that character
1333 in *Help* buffer. See also the command `describe-char'."
1334 (interactive "P")
1335 (let* ((char (following-char))
1336 (bidi-fixer
1337 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1338 ;; start a directional embedding, which could completely
1339 ;; disrupt the rest of the line (e.g., RLO will display the
1340 ;; rest of the line right-to-left). So we put an invisible
1341 ;; PDF character after these characters, to end the
1342 ;; embedding, which eliminates any effects on the rest of
1343 ;; the line. For RLE and RLO we also append an invisible
1344 ;; LRM, to avoid reordering the following numerical
1345 ;; characters. For LRI/RLI/FSI we append a PDI.
1346 (cond ((memq char '(?\x202a ?\x202d))
1347 (propertize (string ?\x202c) 'invisible t))
1348 ((memq char '(?\x202b ?\x202e))
1349 (propertize (string ?\x202c ?\x200e) 'invisible t))
1350 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1351 (propertize (string ?\x2069) 'invisible t))
1352 ;; Strong right-to-left characters cause reordering of
1353 ;; the following numerical characters which show the
1354 ;; codepoint, so append LRM to countermand that.
1355 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1356 (propertize (string ?\x200e) 'invisible t))
1358 "")))
1359 (beg (point-min))
1360 (end (point-max))
1361 (pos (point))
1362 (total (buffer-size))
1363 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1364 (hscroll (if (= (window-hscroll) 0)
1366 (format " Hscroll=%d" (window-hscroll))))
1367 (col (current-column)))
1368 (if (= pos end)
1369 (if (or (/= beg 1) (/= end (1+ total)))
1370 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1371 pos total percent beg end col hscroll)
1372 (message "point=%d of %d (EOB) column=%d%s"
1373 pos total col hscroll))
1374 (let ((coding buffer-file-coding-system)
1375 encoded encoding-msg display-prop under-display)
1376 (if (or (not coding)
1377 (eq (coding-system-type coding) t))
1378 (setq coding (default-value 'buffer-file-coding-system)))
1379 (if (eq (char-charset char) 'eight-bit)
1380 (setq encoding-msg
1381 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1382 ;; Check if the character is displayed with some `display'
1383 ;; text property. In that case, set under-display to the
1384 ;; buffer substring covered by that property.
1385 (setq display-prop (get-char-property pos 'display))
1386 (if display-prop
1387 (let ((to (or (next-single-char-property-change pos 'display)
1388 (point-max))))
1389 (if (< to (+ pos 4))
1390 (setq under-display "")
1391 (setq under-display "..."
1392 to (+ pos 4)))
1393 (setq under-display
1394 (concat (buffer-substring-no-properties pos to)
1395 under-display)))
1396 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1397 (setq encoding-msg
1398 (if display-prop
1399 (if (not (stringp display-prop))
1400 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1401 char char char under-display)
1402 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1403 char char char under-display display-prop))
1404 (if encoded
1405 (format "(%d, #o%o, #x%x, file %s)"
1406 char char char
1407 (if (> (length encoded) 1)
1408 "..."
1409 (encoded-string-description encoded coding)))
1410 (format "(%d, #o%o, #x%x)" char char char)))))
1411 (if detail
1412 ;; We show the detailed information about CHAR.
1413 (describe-char (point)))
1414 (if (or (/= beg 1) (/= end (1+ total)))
1415 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1416 (if (< char 256)
1417 (single-key-description char)
1418 (buffer-substring-no-properties (point) (1+ (point))))
1419 bidi-fixer
1420 encoding-msg pos total percent beg end col hscroll)
1421 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1422 (if enable-multibyte-characters
1423 (if (< char 128)
1424 (single-key-description char)
1425 (buffer-substring-no-properties (point) (1+ (point))))
1426 (single-key-description char))
1427 bidi-fixer encoding-msg pos total percent col hscroll))))))
1429 ;; Initialize read-expression-map. It is defined at C level.
1430 (defvar read-expression-map
1431 (let ((m (make-sparse-keymap)))
1432 (define-key m "\M-\t" 'completion-at-point)
1433 ;; Might as well bind TAB to completion, since inserting a TAB char is
1434 ;; much too rarely useful.
1435 (define-key m "\t" 'completion-at-point)
1436 (set-keymap-parent m minibuffer-local-map)
1439 (defun read-minibuffer (prompt &optional initial-contents)
1440 "Return a Lisp object read using the minibuffer, unevaluated.
1441 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1442 is a string to insert in the minibuffer before reading.
1443 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1444 Such arguments are used as in `read-from-minibuffer'.)"
1445 ;; Used for interactive spec `x'.
1446 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1447 t 'minibuffer-history))
1449 (defun eval-minibuffer (prompt &optional initial-contents)
1450 "Return value of Lisp expression read using the minibuffer.
1451 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1452 is a string to insert in the minibuffer before reading.
1453 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1454 Such arguments are used as in `read-from-minibuffer'.)"
1455 ;; Used for interactive spec `X'.
1456 (eval (read--expression prompt initial-contents)))
1458 (defvar minibuffer-completing-symbol nil
1459 "Non-nil means completing a Lisp symbol in the minibuffer.")
1460 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1462 (defvar minibuffer-default nil
1463 "The current default value or list of default values in the minibuffer.
1464 The functions `read-from-minibuffer' and `completing-read' bind
1465 this variable locally.")
1467 (defcustom eval-expression-print-level 4
1468 "Value for `print-level' while printing value in `eval-expression'.
1469 A value of nil means no limit."
1470 :group 'lisp
1471 :type '(choice (const :tag "No Limit" nil) integer)
1472 :version "21.1")
1474 (defcustom eval-expression-print-length 12
1475 "Value for `print-length' while printing value in `eval-expression'.
1476 A value of nil means no limit."
1477 :group 'lisp
1478 :type '(choice (const :tag "No Limit" nil) integer)
1479 :version "21.1")
1481 (defcustom eval-expression-debug-on-error t
1482 "If non-nil set `debug-on-error' to t in `eval-expression'.
1483 If nil, don't change the value of `debug-on-error'."
1484 :group 'lisp
1485 :type 'boolean
1486 :version "21.1")
1488 (defcustom eval-expression-print-maximum-character 127
1489 "The largest integer that will be displayed as a character.
1490 This affects printing by `eval-expression' (via
1491 `eval-expression-print-format')."
1492 :group 'lisp
1493 :type 'integer
1494 :version "26.1")
1496 (defun eval-expression-print-format (value)
1497 "If VALUE in an integer, return a specially formatted string.
1498 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1499 If VALUE is not an integer, nil is returned.
1500 This function is used by commands like `eval-expression' that
1501 display the result of expression evaluation."
1502 (when (integerp value)
1503 (let ((char-string
1504 (and (characterp value)
1505 (<= value eval-expression-print-maximum-character)
1506 (char-displayable-p value)
1507 (prin1-char value))))
1508 (if char-string
1509 (format " (#o%o, #x%x, %s)" value value char-string)
1510 (format " (#o%o, #x%x)" value value)))))
1512 (defvar eval-expression-minibuffer-setup-hook nil
1513 "Hook run by `eval-expression' when entering the minibuffer.")
1515 (defun read--expression (prompt &optional initial-contents)
1516 (let ((minibuffer-completing-symbol t))
1517 (minibuffer-with-setup-hook
1518 (lambda ()
1519 ;; FIXME: call emacs-lisp-mode?
1520 (add-function :before-until (local 'eldoc-documentation-function)
1521 #'elisp-eldoc-documentation-function)
1522 (eldoc-mode 1)
1523 (add-hook 'completion-at-point-functions
1524 #'elisp-completion-at-point nil t)
1525 (run-hooks 'eval-expression-minibuffer-setup-hook))
1526 (read-from-minibuffer prompt initial-contents
1527 read-expression-map t
1528 'read-expression-history))))
1530 (defun eval-expression-get-print-arguments (prefix-argument)
1531 "Get arguments for commands that print an expression result.
1532 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1533 based on PREFIX-ARG. This function determines the interpretation
1534 of the prefix argument for `eval-expression' and
1535 `eval-last-sexp'."
1536 (let ((num (prefix-numeric-value prefix-argument)))
1537 (list (not (memq prefix-argument '(- nil)))
1538 (= num 0)
1539 (cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
1540 ((= num -1) most-positive-fixnum)
1541 (t eval-expression-print-maximum-character)))))
1543 ;; We define this, rather than making `eval' interactive,
1544 ;; for the sake of completion of names like eval-region, eval-buffer.
1545 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
1546 "Evaluate EXP and print value in the echo area.
1547 When called interactively, read an Emacs Lisp expression and
1548 evaluate it. Value is also consed on to front of the variable
1549 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1550 with a non `-' prefix argument) means insert the result into the
1551 current buffer instead of printing it in the echo area.
1553 Normally, this function truncates long output according to the
1554 value of the variables `eval-expression-print-length' and
1555 `eval-expression-print-level'. When NO-TRUNCATE is
1556 non-nil (interactively, with a prefix argument of zero), however,
1557 there is no such truncation.
1559 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1560 non-nil (interactively, unless given a positive prefix argument)
1561 it will be printed in several additional formats (octal,
1562 hexadecimal, and character). The character format is only used
1563 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1564 prefix argument is -1 or the value is below
1565 `eval-expression-print-maximum-character').
1567 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1568 minibuffer.
1570 If `eval-expression-debug-on-error' is non-nil, which is the default,
1571 this command arranges for all errors to enter the debugger."
1572 (interactive
1573 (cons (read--expression "Eval: ")
1574 (eval-expression-get-print-arguments current-prefix-arg)))
1576 (if (null eval-expression-debug-on-error)
1577 (push (eval exp lexical-binding) values)
1578 (let ((old-value (make-symbol "t")) new-value)
1579 ;; Bind debug-on-error to something unique so that we can
1580 ;; detect when evalled code changes it.
1581 (let ((debug-on-error old-value))
1582 (push (eval (macroexpand-all exp) lexical-binding) values)
1583 (setq new-value debug-on-error))
1584 ;; If evalled code has changed the value of debug-on-error,
1585 ;; propagate that change to the global binding.
1586 (unless (eq old-value new-value)
1587 (setq debug-on-error new-value))))
1589 (let ((print-length (unless no-truncate eval-expression-print-length))
1590 (print-level (unless no-truncate eval-expression-print-level))
1591 (eval-expression-print-maximum-character char-print-limit)
1592 (deactivate-mark))
1593 (let ((out (if insert-value (current-buffer) t)))
1594 (prog1
1595 (prin1 (car values) out)
1596 (let ((str (and char-print-limit
1597 (eval-expression-print-format (car values)))))
1598 (when str (princ str out)))))))
1600 (defun edit-and-eval-command (prompt command)
1601 "Prompting with PROMPT, let user edit COMMAND and eval result.
1602 COMMAND is a Lisp expression. Let user edit that expression in
1603 the minibuffer, then read and evaluate the result."
1604 (let ((command
1605 (let ((print-level nil)
1606 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1607 (unwind-protect
1608 (read-from-minibuffer prompt
1609 (prin1-to-string command)
1610 read-expression-map t
1611 'command-history)
1612 ;; If command was added to command-history as a string,
1613 ;; get rid of that. We want only evaluable expressions there.
1614 (if (stringp (car command-history))
1615 (setq command-history (cdr command-history)))))))
1617 ;; If command to be redone does not match front of history,
1618 ;; add it to the history.
1619 (or (equal command (car command-history))
1620 (setq command-history (cons command command-history)))
1621 (eval command)))
1623 (defun repeat-complex-command (arg)
1624 "Edit and re-evaluate last complex command, or ARGth from last.
1625 A complex command is one which used the minibuffer.
1626 The command is placed in the minibuffer as a Lisp form for editing.
1627 The result is executed, repeating the command as changed.
1628 If the command has been changed or is not the most recent previous
1629 command it is added to the front of the command history.
1630 You can use the minibuffer history commands \
1631 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1632 to get different commands to edit and resubmit."
1633 (interactive "p")
1634 (let ((elt (nth (1- arg) command-history))
1635 newcmd)
1636 (if elt
1637 (progn
1638 (setq newcmd
1639 (let ((print-level nil)
1640 (minibuffer-history-position arg)
1641 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1642 (unwind-protect
1643 (read-from-minibuffer
1644 "Redo: " (prin1-to-string elt) read-expression-map t
1645 (cons 'command-history arg))
1647 ;; If command was added to command-history as a
1648 ;; string, get rid of that. We want only
1649 ;; evaluable expressions there.
1650 (if (stringp (car command-history))
1651 (setq command-history (cdr command-history))))))
1653 ;; If command to be redone does not match front of history,
1654 ;; add it to the history.
1655 (or (equal newcmd (car command-history))
1656 (setq command-history (cons newcmd command-history)))
1657 (apply #'funcall-interactively
1658 (car newcmd)
1659 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1660 (if command-history
1661 (error "Argument %d is beyond length of command history" arg)
1662 (error "There are no previous complex commands to repeat")))))
1665 (defvar extended-command-history nil)
1666 (defvar execute-extended-command--last-typed nil)
1668 (defun read-extended-command ()
1669 "Read command name to invoke in `execute-extended-command'."
1670 (minibuffer-with-setup-hook
1671 (lambda ()
1672 (add-hook 'post-self-insert-hook
1673 (lambda ()
1674 (setq execute-extended-command--last-typed
1675 (minibuffer-contents)))
1676 nil 'local)
1677 (set (make-local-variable 'minibuffer-default-add-function)
1678 (lambda ()
1679 ;; Get a command name at point in the original buffer
1680 ;; to propose it after M-n.
1681 (with-current-buffer (window-buffer (minibuffer-selected-window))
1682 (and (commandp (function-called-at-point))
1683 (format "%S" (function-called-at-point)))))))
1684 ;; Read a string, completing from and restricting to the set of
1685 ;; all defined commands. Don't provide any initial input.
1686 ;; Save the command read on the extended-command history list.
1687 (completing-read
1688 (concat (cond
1689 ((eq current-prefix-arg '-) "- ")
1690 ((and (consp current-prefix-arg)
1691 (eq (car current-prefix-arg) 4)) "C-u ")
1692 ((and (consp current-prefix-arg)
1693 (integerp (car current-prefix-arg)))
1694 (format "%d " (car current-prefix-arg)))
1695 ((integerp current-prefix-arg)
1696 (format "%d " current-prefix-arg)))
1697 ;; This isn't strictly correct if `execute-extended-command'
1698 ;; is bound to anything else (e.g. [menu]).
1699 ;; It could use (key-description (this-single-command-keys)),
1700 ;; but actually a prompt other than "M-x" would be confusing,
1701 ;; because "M-x" is a well-known prompt to read a command
1702 ;; and it serves as a shorthand for "Extended command: ".
1703 "M-x ")
1704 (lambda (string pred action)
1705 (let ((pred
1706 (if (memq action '(nil t))
1707 ;; Exclude obsolete commands from completions.
1708 (lambda (sym)
1709 (and (funcall pred sym)
1710 (or (equal string (symbol-name sym))
1711 (not (get sym 'byte-obsolete-info)))))
1712 pred)))
1713 (complete-with-action action obarray string pred)))
1714 #'commandp t nil 'extended-command-history)))
1716 (defcustom suggest-key-bindings t
1717 "Non-nil means show the equivalent key-binding when M-x command has one.
1718 The value can be a length of time to show the message for.
1719 If the value is non-nil and not a number, we wait 2 seconds."
1720 :group 'keyboard
1721 :type '(choice (const :tag "off" nil)
1722 (integer :tag "time" 2)
1723 (other :tag "on")))
1725 (defcustom extended-command-suggest-shorter t
1726 "If non-nil, show a shorter M-x invocation when there is one."
1727 :group 'keyboard
1728 :type 'boolean
1729 :version "26.1")
1731 (defun execute-extended-command--shorter-1 (name length)
1732 (cond
1733 ((zerop length) (list ""))
1734 ((equal name "") nil)
1736 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1737 (execute-extended-command--shorter-1
1738 (substring name 1) (1- length)))
1739 (when (string-match "\\`\\(-\\)?[^-]*" name)
1740 (execute-extended-command--shorter-1
1741 (substring name (match-end 0)) length))))))
1743 (defun execute-extended-command--shorter (name typed)
1744 (let ((candidates '())
1745 (max (length typed))
1746 (len 1)
1747 binding)
1748 (while (and (not binding)
1749 (progn
1750 (unless candidates
1751 (setq len (1+ len))
1752 (setq candidates (execute-extended-command--shorter-1
1753 name len)))
1754 ;; Don't show the help message if the binding isn't
1755 ;; significantly shorter than the M-x command the user typed.
1756 (< len (- max 5))))
1757 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1758 (let ((candidate (pop candidates)))
1759 (when (equal name
1760 (car-safe (completion-try-completion
1761 candidate obarray 'commandp len)))
1762 (setq binding candidate))))
1763 binding))
1765 (defun execute-extended-command (prefixarg &optional command-name typed)
1766 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1767 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1768 "Read a command name, then read the arguments and call the command.
1769 To pass a prefix argument to the command you are
1770 invoking, give a prefix argument to `execute-extended-command'."
1771 (declare (interactive-only command-execute))
1772 ;; FIXME: Remember the actual text typed by the user before completion,
1773 ;; so that we don't later on suggest the same shortening.
1774 (interactive
1775 (let ((execute-extended-command--last-typed nil))
1776 (list current-prefix-arg
1777 (read-extended-command)
1778 execute-extended-command--last-typed)))
1779 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1780 (unless command-name
1781 (let ((current-prefix-arg prefixarg) ; for prompt
1782 (execute-extended-command--last-typed nil))
1783 (setq command-name (read-extended-command))
1784 (setq typed execute-extended-command--last-typed)))
1785 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1786 (binding (and suggest-key-bindings
1787 (not executing-kbd-macro)
1788 (where-is-internal function overriding-local-map t))))
1789 (unless (commandp function)
1790 (error "`%s' is not a valid command name" command-name))
1791 ;; Some features, such as novice.el, rely on this-command-keys
1792 ;; including M-x COMMAND-NAME RET.
1793 (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
1794 (setq this-command function)
1795 ;; Normally `real-this-command' should never be changed, but here we really
1796 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1797 ;; binding" for <cmd>, so the command the user really wanted to run is
1798 ;; `function' and not `execute-extended-command'. The difference is
1799 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1800 (setq real-this-command function)
1801 (let ((prefix-arg prefixarg))
1802 (command-execute function 'record))
1803 ;; If enabled, show which key runs this command.
1804 ;; But first wait, and skip the message if there is input.
1805 (let* ((waited
1806 ;; If this command displayed something in the echo area;
1807 ;; wait a few seconds, then display our suggestion message.
1808 ;; FIXME: Wait *after* running post-command-hook!
1809 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1810 ;; find a better answer anyway!
1811 (when suggest-key-bindings
1812 (sit-for (cond
1813 ((zerop (length (current-message))) 0)
1814 ((numberp suggest-key-bindings) suggest-key-bindings)
1815 (t 2))))))
1816 (when (and waited (not (consp unread-command-events)))
1817 (unless (or (not extended-command-suggest-shorter)
1818 binding executing-kbd-macro (not (symbolp function))
1819 (<= (length (symbol-name function)) 2))
1820 ;; There's no binding for CMD. Let's try and find the shortest
1821 ;; string to use in M-x.
1822 ;; FIXME: Can be slow. Cache it maybe?
1823 (while-no-input
1824 (setq binding (execute-extended-command--shorter
1825 (symbol-name function) typed))))
1826 (when binding
1827 (with-temp-message
1828 (format-message "You can run the command `%s' with %s"
1829 function
1830 (if (stringp binding)
1831 (concat "M-x " binding " RET")
1832 (key-description binding)))
1833 (sit-for (if (numberp suggest-key-bindings)
1834 suggest-key-bindings
1835 2))))))))
1837 (defun command-execute (cmd &optional record-flag keys special)
1838 ;; BEWARE: Called directly from the C code.
1839 "Execute CMD as an editor command.
1840 CMD must be a symbol that satisfies the `commandp' predicate.
1841 Optional second arg RECORD-FLAG non-nil
1842 means unconditionally put this command in the variable `command-history'.
1843 Otherwise, that is done only if an arg is read using the minibuffer.
1844 The argument KEYS specifies the value to use instead of (this-command-keys)
1845 when reading the arguments; if it is nil, (this-command-keys) is used.
1846 The argument SPECIAL, if non-nil, means that this command is executing
1847 a special event, so ignore the prefix argument and don't clear it."
1848 (setq debug-on-next-call nil)
1849 (let ((prefixarg (unless special
1850 ;; FIXME: This should probably be done around
1851 ;; pre-command-hook rather than here!
1852 (prog1 prefix-arg
1853 (setq current-prefix-arg prefix-arg)
1854 (setq prefix-arg nil)
1855 (when current-prefix-arg
1856 (prefix-command-update))))))
1857 (if (and (symbolp cmd)
1858 (get cmd 'disabled)
1859 disabled-command-function)
1860 ;; FIXME: Weird calling convention!
1861 (run-hooks 'disabled-command-function)
1862 (let ((final cmd))
1863 (while
1864 (progn
1865 (setq final (indirect-function final))
1866 (if (autoloadp final)
1867 (setq final (autoload-do-load final cmd)))))
1868 (cond
1869 ((arrayp final)
1870 ;; If requested, place the macro in the command history. For
1871 ;; other sorts of commands, call-interactively takes care of this.
1872 (when record-flag
1873 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1874 ;; Don't keep command history around forever.
1875 (when (and (numberp history-length) (> history-length 0))
1876 (let ((cell (nthcdr history-length command-history)))
1877 (if (consp cell) (setcdr cell nil)))))
1878 (execute-kbd-macro final prefixarg))
1880 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1881 (prog1 (call-interactively cmd record-flag keys)
1882 (when (and (symbolp cmd)
1883 (get cmd 'byte-obsolete-info)
1884 (not (get cmd 'command-execute-obsolete-warned)))
1885 (put cmd 'command-execute-obsolete-warned t)
1886 (message "%s" (macroexp--obsolete-warning
1887 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1889 (defvar minibuffer-history nil
1890 "Default minibuffer history list.
1891 This is used for all minibuffer input
1892 except when an alternate history list is specified.
1894 Maximum length of the history list is determined by the value
1895 of `history-length', which see.")
1896 (defvar minibuffer-history-sexp-flag nil
1897 "Control whether history list elements are expressions or strings.
1898 If the value of this variable equals current minibuffer depth,
1899 they are expressions; otherwise they are strings.
1900 \(That convention is designed to do the right thing for
1901 recursive uses of the minibuffer.)")
1902 (setq minibuffer-history-variable 'minibuffer-history)
1903 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1904 (defvar minibuffer-history-search-history nil)
1906 (defvar minibuffer-text-before-history nil
1907 "Text that was in this minibuffer before any history commands.
1908 This is nil if there have not yet been any history commands
1909 in this use of the minibuffer.")
1911 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1913 (defun minibuffer-history-initialize ()
1914 (setq minibuffer-text-before-history nil))
1916 (defun minibuffer-avoid-prompt (_new _old)
1917 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1918 (declare (obsolete cursor-intangible-mode "25.1"))
1919 (constrain-to-field nil (point-max)))
1921 (defcustom minibuffer-history-case-insensitive-variables nil
1922 "Minibuffer history variables for which matching should ignore case.
1923 If a history variable is a member of this list, then the
1924 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1925 commands ignore case when searching it, regardless of `case-fold-search'."
1926 :type '(repeat variable)
1927 :group 'minibuffer)
1929 (defun previous-matching-history-element (regexp n)
1930 "Find the previous history element that matches REGEXP.
1931 \(Previous history elements refer to earlier actions.)
1932 With prefix argument N, search for Nth previous match.
1933 If N is negative, find the next or Nth next match.
1934 Normally, history elements are matched case-insensitively if
1935 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1936 makes the search case-sensitive.
1937 See also `minibuffer-history-case-insensitive-variables'."
1938 (interactive
1939 (let* ((enable-recursive-minibuffers t)
1940 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1942 minibuffer-local-map
1944 'minibuffer-history-search-history
1945 (car minibuffer-history-search-history))))
1946 ;; Use the last regexp specified, by default, if input is empty.
1947 (list (if (string= regexp "")
1948 (if minibuffer-history-search-history
1949 (car minibuffer-history-search-history)
1950 (user-error "No previous history search regexp"))
1951 regexp)
1952 (prefix-numeric-value current-prefix-arg))))
1953 (unless (zerop n)
1954 (if (and (zerop minibuffer-history-position)
1955 (null minibuffer-text-before-history))
1956 (setq minibuffer-text-before-history
1957 (minibuffer-contents-no-properties)))
1958 (let ((history (symbol-value minibuffer-history-variable))
1959 (case-fold-search
1960 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1961 ;; On some systems, ignore case for file names.
1962 (if (memq minibuffer-history-variable
1963 minibuffer-history-case-insensitive-variables)
1965 ;; Respect the user's setting for case-fold-search:
1966 case-fold-search)
1967 nil))
1968 prevpos
1969 match-string
1970 match-offset
1971 (pos minibuffer-history-position))
1972 (while (/= n 0)
1973 (setq prevpos pos)
1974 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1975 (when (= pos prevpos)
1976 (user-error (if (= pos 1)
1977 "No later matching history item"
1978 "No earlier matching history item")))
1979 (setq match-string
1980 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1981 (let ((print-level nil))
1982 (prin1-to-string (nth (1- pos) history)))
1983 (nth (1- pos) history)))
1984 (setq match-offset
1985 (if (< n 0)
1986 (and (string-match regexp match-string)
1987 (match-end 0))
1988 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1989 (match-beginning 1))))
1990 (when match-offset
1991 (setq n (+ n (if (< n 0) 1 -1)))))
1992 (setq minibuffer-history-position pos)
1993 (goto-char (point-max))
1994 (delete-minibuffer-contents)
1995 (insert match-string)
1996 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1997 (if (memq (car (car command-history)) '(previous-matching-history-element
1998 next-matching-history-element))
1999 (setq command-history (cdr command-history))))
2001 (defun next-matching-history-element (regexp n)
2002 "Find the next history element that matches REGEXP.
2003 \(The next history element refers to a more recent action.)
2004 With prefix argument N, search for Nth next match.
2005 If N is negative, find the previous or Nth previous match.
2006 Normally, history elements are matched case-insensitively if
2007 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
2008 makes the search case-sensitive."
2009 (interactive
2010 (let* ((enable-recursive-minibuffers t)
2011 (regexp (read-from-minibuffer "Next element matching (regexp): "
2013 minibuffer-local-map
2015 'minibuffer-history-search-history
2016 (car minibuffer-history-search-history))))
2017 ;; Use the last regexp specified, by default, if input is empty.
2018 (list (if (string= regexp "")
2019 (if minibuffer-history-search-history
2020 (car minibuffer-history-search-history)
2021 (user-error "No previous history search regexp"))
2022 regexp)
2023 (prefix-numeric-value current-prefix-arg))))
2024 (previous-matching-history-element regexp (- n)))
2026 (defvar minibuffer-temporary-goal-position nil)
2028 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
2029 "Function run by `goto-history-element' before consuming default values.
2030 This is useful to dynamically add more elements to the list of default values
2031 when `goto-history-element' reaches the end of this list.
2032 Before calling this function `goto-history-element' sets the variable
2033 `minibuffer-default-add-done' to t, so it will call this function only
2034 once. In special cases, when this function needs to be called more
2035 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2036 overriding the setting of this variable to t in `goto-history-element'.")
2038 (defvar minibuffer-default-add-done nil
2039 "When nil, add more elements to the end of the list of default values.
2040 The value nil causes `goto-history-element' to add more elements to
2041 the list of defaults when it reaches the end of this list. It does
2042 this by calling a function defined by `minibuffer-default-add-function'.")
2044 (make-variable-buffer-local 'minibuffer-default-add-done)
2046 (defun minibuffer-default-add-completions ()
2047 "Return a list of all completions without the default value.
2048 This function is used to add all elements of the completion table to
2049 the end of the list of defaults just after the default value."
2050 (let ((def minibuffer-default)
2051 (all (all-completions ""
2052 minibuffer-completion-table
2053 minibuffer-completion-predicate)))
2054 (if (listp def)
2055 (append def all)
2056 (cons def (delete def all)))))
2058 (defun goto-history-element (nabs)
2059 "Puts element of the minibuffer history in the minibuffer.
2060 The argument NABS specifies the absolute history position."
2061 (interactive "p")
2062 (when (and (not minibuffer-default-add-done)
2063 (functionp minibuffer-default-add-function)
2064 (< nabs (- (if (listp minibuffer-default)
2065 (length minibuffer-default)
2066 1))))
2067 (setq minibuffer-default-add-done t
2068 minibuffer-default (funcall minibuffer-default-add-function)))
2069 (let ((minimum (if minibuffer-default
2070 (- (if (listp minibuffer-default)
2071 (length minibuffer-default)
2074 elt minibuffer-returned-to-present)
2075 (if (and (zerop minibuffer-history-position)
2076 (null minibuffer-text-before-history))
2077 (setq minibuffer-text-before-history
2078 (minibuffer-contents-no-properties)))
2079 (if (< nabs minimum)
2080 (user-error (if minibuffer-default
2081 "End of defaults; no next item"
2082 "End of history; no default available")))
2083 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2084 (length (symbol-value minibuffer-history-variable))
2086 (user-error "Beginning of history; no preceding item"))
2087 (unless (memq last-command '(next-history-element
2088 previous-history-element))
2089 (let ((prompt-end (minibuffer-prompt-end)))
2090 (set (make-local-variable 'minibuffer-temporary-goal-position)
2091 (cond ((<= (point) prompt-end) prompt-end)
2092 ((eobp) nil)
2093 (t (point))))))
2094 (goto-char (point-max))
2095 (delete-minibuffer-contents)
2096 (setq minibuffer-history-position nabs)
2097 (cond ((< nabs 0)
2098 (setq elt (if (listp minibuffer-default)
2099 (nth (1- (abs nabs)) minibuffer-default)
2100 minibuffer-default)))
2101 ((= nabs 0)
2102 (setq elt (or minibuffer-text-before-history ""))
2103 (setq minibuffer-returned-to-present t)
2104 (setq minibuffer-text-before-history nil))
2105 (t (setq elt (nth (1- minibuffer-history-position)
2106 (symbol-value minibuffer-history-variable)))))
2107 (insert
2108 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2109 (not minibuffer-returned-to-present))
2110 (let ((print-level nil))
2111 (prin1-to-string elt))
2112 elt))
2113 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2115 (defun next-history-element (n)
2116 "Puts next element of the minibuffer history in the minibuffer.
2117 With argument N, it uses the Nth following element."
2118 (interactive "p")
2119 (or (zerop n)
2120 (goto-history-element (- minibuffer-history-position n))))
2122 (defun previous-history-element (n)
2123 "Puts previous element of the minibuffer history in the minibuffer.
2124 With argument N, it uses the Nth previous element."
2125 (interactive "p")
2126 (or (zerop n)
2127 (goto-history-element (+ minibuffer-history-position n))))
2129 (defun next-line-or-history-element (&optional arg)
2130 "Move cursor vertically down ARG lines, or to the next history element.
2131 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2132 next element of the minibuffer history in the minibuffer."
2133 (interactive "^p")
2134 (or arg (setq arg 1))
2135 (let* ((old-point (point))
2136 ;; Don't add newlines if they have the mode enabled globally.
2137 (next-line-add-newlines nil)
2138 ;; Remember the original goal column of possibly multi-line input
2139 ;; excluding the length of the prompt on the first line.
2140 (prompt-end (minibuffer-prompt-end))
2141 (old-column (unless (and (eolp) (> (point) prompt-end))
2142 (if (= (line-number-at-pos) 1)
2143 (max (- (current-column) (1- prompt-end)) 0)
2144 (current-column)))))
2145 (condition-case nil
2146 (with-no-warnings
2147 (next-line arg))
2148 (end-of-buffer
2149 ;; Restore old position since `line-move-visual' moves point to
2150 ;; the end of the line when it fails to go to the next line.
2151 (goto-char old-point)
2152 (next-history-element arg)
2153 ;; Reset `temporary-goal-column' because a correct value is not
2154 ;; calculated when `next-line' above fails by bumping against
2155 ;; the bottom of the minibuffer (bug#22544).
2156 (setq temporary-goal-column 0)
2157 ;; Restore the original goal column on the last line
2158 ;; of possibly multi-line input.
2159 (goto-char (point-max))
2160 (when old-column
2161 (if (= (line-number-at-pos) 1)
2162 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2163 (move-to-column old-column)))))))
2165 (defun previous-line-or-history-element (&optional arg)
2166 "Move cursor vertically up ARG lines, or to the previous history element.
2167 When point moves over the top line of multi-line minibuffer, puts ARGth
2168 previous element of the minibuffer history in the minibuffer."
2169 (interactive "^p")
2170 (or arg (setq arg 1))
2171 (let* ((old-point (point))
2172 ;; Remember the original goal column of possibly multi-line input
2173 ;; excluding the length of the prompt on the first line.
2174 (prompt-end (minibuffer-prompt-end))
2175 (old-column (unless (and (eolp) (> (point) prompt-end))
2176 (if (= (line-number-at-pos) 1)
2177 (max (- (current-column) (1- prompt-end)) 0)
2178 (current-column)))))
2179 (condition-case nil
2180 (with-no-warnings
2181 (previous-line arg))
2182 (beginning-of-buffer
2183 ;; Restore old position since `line-move-visual' moves point to
2184 ;; the beginning of the line when it fails to go to the previous line.
2185 (goto-char old-point)
2186 (previous-history-element arg)
2187 ;; Reset `temporary-goal-column' because a correct value is not
2188 ;; calculated when `previous-line' above fails by bumping against
2189 ;; the top of the minibuffer (bug#22544).
2190 (setq temporary-goal-column 0)
2191 ;; Restore the original goal column on the first line
2192 ;; of possibly multi-line input.
2193 (goto-char (minibuffer-prompt-end))
2194 (if old-column
2195 (if (= (line-number-at-pos) 1)
2196 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2197 (move-to-column old-column))
2198 ;; Put the cursor at the end of the visual line instead of the
2199 ;; logical line, so the next `previous-line-or-history-element'
2200 ;; would move to the previous history element, not to a possible upper
2201 ;; visual line from the end of logical line in `line-move-visual' mode.
2202 (end-of-visual-line)
2203 ;; Since `end-of-visual-line' puts the cursor at the beginning
2204 ;; of the next visual line, move it one char back to the end
2205 ;; of the first visual line (bug#22544).
2206 (unless (eolp) (backward-char 1)))))))
2208 (defun next-complete-history-element (n)
2209 "Get next history element which completes the minibuffer before the point.
2210 The contents of the minibuffer after the point are deleted, and replaced
2211 by the new completion."
2212 (interactive "p")
2213 (let ((point-at-start (point)))
2214 (next-matching-history-element
2215 (concat
2216 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2218 ;; next-matching-history-element always puts us at (point-min).
2219 ;; Move to the position we were at before changing the buffer contents.
2220 ;; This is still sensible, because the text before point has not changed.
2221 (goto-char point-at-start)))
2223 (defun previous-complete-history-element (n)
2225 Get previous history element which completes the minibuffer before the point.
2226 The contents of the minibuffer after the point are deleted, and replaced
2227 by the new completion."
2228 (interactive "p")
2229 (next-complete-history-element (- n)))
2231 ;; For compatibility with the old subr of the same name.
2232 (defun minibuffer-prompt-width ()
2233 "Return the display width of the minibuffer prompt.
2234 Return 0 if current buffer is not a minibuffer."
2235 ;; Return the width of everything before the field at the end of
2236 ;; the buffer; this should be 0 for normal buffers.
2237 (1- (minibuffer-prompt-end)))
2239 ;; isearch minibuffer history
2240 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2242 (defvar minibuffer-history-isearch-message-overlay)
2243 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2245 (defun minibuffer-history-isearch-setup ()
2246 "Set up a minibuffer for using isearch to search the minibuffer history.
2247 Intended to be added to `minibuffer-setup-hook'."
2248 (set (make-local-variable 'isearch-search-fun-function)
2249 'minibuffer-history-isearch-search)
2250 (set (make-local-variable 'isearch-message-function)
2251 'minibuffer-history-isearch-message)
2252 (set (make-local-variable 'isearch-wrap-function)
2253 'minibuffer-history-isearch-wrap)
2254 (set (make-local-variable 'isearch-push-state-function)
2255 'minibuffer-history-isearch-push-state)
2256 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2258 (defun minibuffer-history-isearch-end ()
2259 "Clean up the minibuffer after terminating isearch in the minibuffer."
2260 (if minibuffer-history-isearch-message-overlay
2261 (delete-overlay minibuffer-history-isearch-message-overlay)))
2263 (defun minibuffer-history-isearch-search ()
2264 "Return the proper search function, for isearch in minibuffer history."
2265 (lambda (string bound noerror)
2266 (let ((search-fun
2267 ;; Use standard functions to search within minibuffer text
2268 (isearch-search-fun-default))
2269 found)
2270 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2271 ;; searching forward. Lazy-highlight calls this lambda with the
2272 ;; bound arg, so skip the minibuffer prompt.
2273 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2274 (goto-char (minibuffer-prompt-end)))
2276 ;; 1. First try searching in the initial minibuffer text
2277 (funcall search-fun string
2278 (if isearch-forward bound (minibuffer-prompt-end))
2279 noerror)
2280 ;; 2. If the above search fails, start putting next/prev history
2281 ;; elements in the minibuffer successively, and search the string
2282 ;; in them. Do this only when bound is nil (i.e. not while
2283 ;; lazy-highlighting search strings in the current minibuffer text).
2284 (unless bound
2285 (condition-case nil
2286 (progn
2287 (while (not found)
2288 (cond (isearch-forward
2289 (next-history-element 1)
2290 (goto-char (minibuffer-prompt-end)))
2292 (previous-history-element 1)
2293 (goto-char (point-max))))
2294 (setq isearch-barrier (point) isearch-opoint (point))
2295 ;; After putting the next/prev history element, search
2296 ;; the string in them again, until next-history-element
2297 ;; or previous-history-element raises an error at the
2298 ;; beginning/end of history.
2299 (setq found (funcall search-fun string
2300 (unless isearch-forward
2301 ;; For backward search, don't search
2302 ;; in the minibuffer prompt
2303 (minibuffer-prompt-end))
2304 noerror)))
2305 ;; Return point of the new search result
2306 (point))
2307 ;; Return nil when next(prev)-history-element fails
2308 (error nil)))))))
2310 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2311 "Display the minibuffer history search prompt.
2312 If there are no search errors, this function displays an overlay with
2313 the isearch prompt which replaces the original minibuffer prompt.
2314 Otherwise, it displays the standard isearch message returned from
2315 the function `isearch-message'."
2316 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2317 ;; Use standard function `isearch-message' when not in the minibuffer,
2318 ;; or search fails, or has an error (like incomplete regexp).
2319 ;; This function overwrites minibuffer text with isearch message,
2320 ;; so it's possible to see what is wrong in the search string.
2321 (isearch-message c-q-hack ellipsis)
2322 ;; Otherwise, put the overlay with the standard isearch prompt over
2323 ;; the initial minibuffer prompt.
2324 (if (overlayp minibuffer-history-isearch-message-overlay)
2325 (move-overlay minibuffer-history-isearch-message-overlay
2326 (point-min) (minibuffer-prompt-end))
2327 (setq minibuffer-history-isearch-message-overlay
2328 (make-overlay (point-min) (minibuffer-prompt-end)))
2329 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2330 (overlay-put minibuffer-history-isearch-message-overlay
2331 'display (isearch-message-prefix c-q-hack ellipsis))
2332 ;; And clear any previous isearch message.
2333 (message "")))
2335 (defun minibuffer-history-isearch-wrap ()
2336 "Wrap the minibuffer history search when search fails.
2337 Move point to the first history element for a forward search,
2338 or to the last history element for a backward search."
2339 ;; When `minibuffer-history-isearch-search' fails on reaching the
2340 ;; beginning/end of the history, wrap the search to the first/last
2341 ;; minibuffer history element.
2342 (if isearch-forward
2343 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2344 (goto-history-element 0))
2345 (setq isearch-success t)
2346 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2348 (defun minibuffer-history-isearch-push-state ()
2349 "Save a function restoring the state of minibuffer history search.
2350 Save `minibuffer-history-position' to the additional state parameter
2351 in the search status stack."
2352 (let ((pos minibuffer-history-position))
2353 (lambda (cmd)
2354 (minibuffer-history-isearch-pop-state cmd pos))))
2356 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2357 "Restore the minibuffer history search state.
2358 Go to the history element by the absolute history position HIST-POS."
2359 (goto-history-element hist-pos))
2362 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2363 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2365 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2366 "Table mapping redo records to the corresponding undo one.
2367 A redo record for undo-in-region maps to t.
2368 A redo record for ordinary undo maps to the following (earlier) undo.")
2370 (defvar undo-in-region nil
2371 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2373 (defvar undo-no-redo nil
2374 "If t, `undo' doesn't go through redo entries.")
2376 (defvar pending-undo-list nil
2377 "Within a run of consecutive undo commands, list remaining to be undone.
2378 If t, we undid all the way to the end of it.")
2380 (defun undo (&optional arg)
2381 "Undo some previous changes.
2382 Repeat this command to undo more changes.
2383 A numeric ARG serves as a repeat count.
2385 In Transient Mark mode when the mark is active, only undo changes within
2386 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2387 as an argument limits undo to changes within the current region."
2388 (interactive "*P")
2389 ;; Make last-command indicate for the next command that this was an undo.
2390 ;; That way, another undo will undo more.
2391 ;; If we get to the end of the undo history and get an error,
2392 ;; another undo command will find the undo history empty
2393 ;; and will get another error. To begin undoing the undos,
2394 ;; you must type some other command.
2395 (let* ((modified (buffer-modified-p))
2396 ;; For an indirect buffer, look in the base buffer for the
2397 ;; auto-save data.
2398 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2399 (recent-save (with-current-buffer base-buffer
2400 (recent-auto-save-p)))
2401 message)
2402 ;; If we get an error in undo-start,
2403 ;; the next command should not be a "consecutive undo".
2404 ;; So set `this-command' to something other than `undo'.
2405 (setq this-command 'undo-start)
2407 (unless (and (eq last-command 'undo)
2408 (or (eq pending-undo-list t)
2409 ;; If something (a timer or filter?) changed the buffer
2410 ;; since the previous command, don't continue the undo seq.
2411 (let ((list buffer-undo-list))
2412 (while (eq (car list) nil)
2413 (setq list (cdr list)))
2414 ;; If the last undo record made was made by undo
2415 ;; it shows nothing else happened in between.
2416 (gethash list undo-equiv-table))))
2417 (setq undo-in-region
2418 (or (region-active-p) (and arg (not (numberp arg)))))
2419 (if undo-in-region
2420 (undo-start (region-beginning) (region-end))
2421 (undo-start))
2422 ;; get rid of initial undo boundary
2423 (undo-more 1))
2424 ;; If we got this far, the next command should be a consecutive undo.
2425 (setq this-command 'undo)
2426 ;; Check to see whether we're hitting a redo record, and if
2427 ;; so, ask the user whether she wants to skip the redo/undo pair.
2428 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2429 (or (eq (selected-window) (minibuffer-window))
2430 (setq message (format "%s%s!"
2431 (if (or undo-no-redo (not equiv))
2432 "Undo" "Redo")
2433 (if undo-in-region " in region" ""))))
2434 (when (and (consp equiv) undo-no-redo)
2435 ;; The equiv entry might point to another redo record if we have done
2436 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2437 (while (let ((next (gethash equiv undo-equiv-table)))
2438 (if next (setq equiv next))))
2439 (setq pending-undo-list equiv)))
2440 (undo-more
2441 (if (numberp arg)
2442 (prefix-numeric-value arg)
2444 ;; Record the fact that the just-generated undo records come from an
2445 ;; undo operation--that is, they are redo records.
2446 ;; In the ordinary case (not within a region), map the redo
2447 ;; record to the following undos.
2448 ;; I don't know how to do that in the undo-in-region case.
2449 (let ((list buffer-undo-list))
2450 ;; Strip any leading undo boundaries there might be, like we do
2451 ;; above when checking.
2452 (while (eq (car list) nil)
2453 (setq list (cdr list)))
2454 (puthash list
2455 ;; Prevent identity mapping. This can happen if
2456 ;; consecutive nils are erroneously in undo list.
2457 (if (or undo-in-region (eq list pending-undo-list))
2459 pending-undo-list)
2460 undo-equiv-table))
2461 ;; Don't specify a position in the undo record for the undo command.
2462 ;; Instead, undoing this should move point to where the change is.
2463 (let ((tail buffer-undo-list)
2464 (prev nil))
2465 (while (car tail)
2466 (when (integerp (car tail))
2467 (let ((pos (car tail)))
2468 (if prev
2469 (setcdr prev (cdr tail))
2470 (setq buffer-undo-list (cdr tail)))
2471 (setq tail (cdr tail))
2472 (while (car tail)
2473 (if (eq pos (car tail))
2474 (if prev
2475 (setcdr prev (cdr tail))
2476 (setq buffer-undo-list (cdr tail)))
2477 (setq prev tail))
2478 (setq tail (cdr tail)))
2479 (setq tail nil)))
2480 (setq prev tail tail (cdr tail))))
2481 ;; Record what the current undo list says,
2482 ;; so the next command can tell if the buffer was modified in between.
2483 (and modified (not (buffer-modified-p))
2484 (with-current-buffer base-buffer
2485 (delete-auto-save-file-if-necessary recent-save)))
2486 ;; Display a message announcing success.
2487 (if message
2488 (message "%s" message))))
2490 (defun buffer-disable-undo (&optional buffer)
2491 "Make BUFFER stop keeping undo information.
2492 No argument or nil as argument means do this for the current buffer."
2493 (interactive)
2494 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2495 (setq buffer-undo-list t)))
2497 (defun undo-only (&optional arg)
2498 "Undo some previous changes.
2499 Repeat this command to undo more changes.
2500 A numeric ARG serves as a repeat count.
2501 Contrary to `undo', this will not redo a previous undo."
2502 (interactive "*p")
2503 (let ((undo-no-redo t)) (undo arg)))
2505 (defvar undo-in-progress nil
2506 "Non-nil while performing an undo.
2507 Some change-hooks test this variable to do something different.")
2509 (defun undo-more (n)
2510 "Undo back N undo-boundaries beyond what was already undone recently.
2511 Call `undo-start' to get ready to undo recent changes,
2512 then call `undo-more' one or more times to undo them."
2513 (or (listp pending-undo-list)
2514 (user-error (concat "No further undo information"
2515 (and undo-in-region " for region"))))
2516 (let ((undo-in-progress t))
2517 ;; Note: The following, while pulling elements off
2518 ;; `pending-undo-list' will call primitive change functions which
2519 ;; will push more elements onto `buffer-undo-list'.
2520 (setq pending-undo-list (primitive-undo n pending-undo-list))
2521 (if (null pending-undo-list)
2522 (setq pending-undo-list t))))
2524 (defun primitive-undo (n list)
2525 "Undo N records from the front of the list LIST.
2526 Return what remains of the list."
2528 ;; This is a good feature, but would make undo-start
2529 ;; unable to do what is expected.
2530 ;;(when (null (car (list)))
2531 ;; ;; If the head of the list is a boundary, it is the boundary
2532 ;; ;; preceding this command. Get rid of it and don't count it.
2533 ;; (setq list (cdr list))))
2535 (let ((arg n)
2536 ;; In a writable buffer, enable undoing read-only text that is
2537 ;; so because of text properties.
2538 (inhibit-read-only t)
2539 ;; Don't let `intangible' properties interfere with undo.
2540 (inhibit-point-motion-hooks t)
2541 ;; We use oldlist only to check for EQ. ++kfs
2542 (oldlist buffer-undo-list)
2543 (did-apply nil)
2544 (next nil))
2545 (while (> arg 0)
2546 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2547 ;; Handle an integer by setting point to that value.
2548 (pcase next
2549 ((pred integerp) (goto-char next))
2550 ;; Element (t . TIME) records previous modtime.
2551 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2552 ;; UNKNOWN_MODTIME_NSECS.
2553 (`(t . ,time)
2554 ;; If this records an obsolete save
2555 ;; (not matching the actual disk file)
2556 ;; then don't mark unmodified.
2557 (when (or (equal time (visited-file-modtime))
2558 (and (consp time)
2559 (equal (list (car time) (cdr time))
2560 (visited-file-modtime))))
2561 (when (fboundp 'unlock-buffer)
2562 (unlock-buffer))
2563 (set-buffer-modified-p nil)))
2564 ;; Element (nil PROP VAL BEG . END) is property change.
2565 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2566 (when (or (> (point-min) beg) (< (point-max) end))
2567 (error "Changes to be undone are outside visible portion of buffer"))
2568 (put-text-property beg end prop val))
2569 ;; Element (BEG . END) means range was inserted.
2570 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2571 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2572 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2573 (when (or (> (point-min) beg) (< (point-max) end))
2574 (error "Changes to be undone are outside visible portion of buffer"))
2575 ;; Set point first thing, so that undoing this undo
2576 ;; does not send point back to where it is now.
2577 (goto-char beg)
2578 (delete-region beg end))
2579 ;; Element (apply FUN . ARGS) means call FUN to undo.
2580 (`(apply . ,fun-args)
2581 (let ((currbuff (current-buffer)))
2582 (if (integerp (car fun-args))
2583 ;; Long format: (apply DELTA START END FUN . ARGS).
2584 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2585 (start-mark (copy-marker start nil))
2586 (end-mark (copy-marker end t)))
2587 (when (or (> (point-min) start) (< (point-max) end))
2588 (error "Changes to be undone are outside visible portion of buffer"))
2589 (apply fun args) ;; Use `save-current-buffer'?
2590 ;; Check that the function did what the entry
2591 ;; said it would do.
2592 (unless (and (= start start-mark)
2593 (= (+ delta end) end-mark))
2594 (error "Changes to be undone by function different than announced"))
2595 (set-marker start-mark nil)
2596 (set-marker end-mark nil))
2597 (apply fun-args))
2598 (unless (eq currbuff (current-buffer))
2599 (error "Undo function switched buffer"))
2600 (setq did-apply t)))
2601 ;; Element (STRING . POS) means STRING was deleted.
2602 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2603 (let ((valid-marker-adjustments nil)
2604 (apos (abs pos)))
2605 (when (or (< apos (point-min)) (> apos (point-max)))
2606 (error "Changes to be undone are outside visible portion of buffer"))
2607 ;; Check that marker adjustments which were recorded
2608 ;; with the (STRING . POS) record are still valid, ie
2609 ;; the markers haven't moved. We check their validity
2610 ;; before reinserting the string so as we don't need to
2611 ;; mind marker insertion-type.
2612 (while (and (markerp (car-safe (car list)))
2613 (integerp (cdr-safe (car list))))
2614 (let* ((marker-adj (pop list))
2615 (m (car marker-adj)))
2616 (and (eq (marker-buffer m) (current-buffer))
2617 (= apos m)
2618 (push marker-adj valid-marker-adjustments))))
2619 ;; Insert string and adjust point
2620 (if (< pos 0)
2621 (progn
2622 (goto-char (- pos))
2623 (insert string))
2624 (goto-char pos)
2625 (insert string)
2626 (goto-char pos))
2627 ;; Adjust the valid marker adjustments
2628 (dolist (adj valid-marker-adjustments)
2629 ;; Insert might have invalidated some of the markers
2630 ;; via modification hooks. Update only the currently
2631 ;; valid ones (bug#25599).
2632 (if (marker-buffer (car adj))
2633 (set-marker (car adj)
2634 (- (car adj) (cdr adj)))))))
2635 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2636 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2637 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2638 next)
2639 ;; Even though these elements are not expected in the undo
2640 ;; list, adjust them to be conservative for the 24.4
2641 ;; release. (Bug#16818)
2642 (when (marker-buffer marker)
2643 (set-marker marker
2644 (- marker offset)
2645 (marker-buffer marker))))
2646 (_ (error "Unrecognized entry in undo list %S" next))))
2647 (setq arg (1- arg)))
2648 ;; Make sure an apply entry produces at least one undo entry,
2649 ;; so the test in `undo' for continuing an undo series
2650 ;; will work right.
2651 (if (and did-apply
2652 (eq oldlist buffer-undo-list))
2653 (setq buffer-undo-list
2654 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2655 list)
2657 ;; Deep copy of a list
2658 (defun undo-copy-list (list)
2659 "Make a copy of undo list LIST."
2660 (mapcar 'undo-copy-list-1 list))
2662 (defun undo-copy-list-1 (elt)
2663 (if (consp elt)
2664 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2665 elt))
2667 (defun undo-start (&optional beg end)
2668 "Set `pending-undo-list' to the front of the undo list.
2669 The next call to `undo-more' will undo the most recently made change.
2670 If BEG and END are specified, then only undo elements
2671 that apply to text between BEG and END are used; other undo elements
2672 are ignored. If BEG and END are nil, all undo elements are used."
2673 (if (eq buffer-undo-list t)
2674 (user-error "No undo information in this buffer"))
2675 (setq pending-undo-list
2676 (if (and beg end (not (= beg end)))
2677 (undo-make-selective-list (min beg end) (max beg end))
2678 buffer-undo-list)))
2680 ;; The positions given in elements of the undo list are the positions
2681 ;; as of the time that element was recorded to undo history. In
2682 ;; general, subsequent buffer edits render those positions invalid in
2683 ;; the current buffer, unless adjusted according to the intervening
2684 ;; undo elements.
2686 ;; Undo in region is a use case that requires adjustments to undo
2687 ;; elements. It must adjust positions of elements in the region based
2688 ;; on newer elements not in the region so as they may be correctly
2689 ;; applied in the current buffer. undo-make-selective-list
2690 ;; accomplishes this with its undo-deltas list of adjustments. An
2691 ;; example undo history from oldest to newest:
2693 ;; buf pos:
2694 ;; 123456789 buffer-undo-list undo-deltas
2695 ;; --------- ---------------- -----------
2696 ;; aaa (1 . 4) (1 . -3)
2697 ;; aaba (3 . 4) N/A (in region)
2698 ;; ccaaba (1 . 3) (1 . -2)
2699 ;; ccaabaddd (7 . 10) (7 . -3)
2700 ;; ccaabdd ("ad" . 6) (6 . 2)
2701 ;; ccaabaddd (6 . 8) (6 . -2)
2702 ;; | |<-- region: "caab", from 2 to 6
2704 ;; When the user starts a run of undos in region,
2705 ;; undo-make-selective-list is called to create the full list of in
2706 ;; region elements. Each element is adjusted forward chronologically
2707 ;; through undo-deltas to determine if it is in the region.
2709 ;; In the above example, the insertion of "b" is (3 . 4) in the
2710 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2711 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2712 ;; . 6) is assessed as in the region and placed in the selective list.
2713 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2714 ;; due to the selected element. The "b" insertion is the only element
2715 ;; fully in the region, so in this example undo-make-selective-list
2716 ;; returns (nil (5 . 6)).
2718 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2719 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2720 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2721 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2722 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2724 ;; More interesting is how to adjust the "ddd" insertion due to the
2725 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2726 ;; If the reinsertion was a manual retyping of "ad", then the total
2727 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2728 ;; the reinsertion was due to undo, one might expect the first "d"
2729 ;; character would again be a part of the "ddd" text, meaning its
2730 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2732 ;; undo-make-selective-list assumes in this situation that "ad" was a
2733 ;; new edit, even if it was inserted because of an undo.
2734 ;; Consequently, if the user undos in region "8 to 10" of the
2735 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2736 ;; "ccaabad", as though the first "d" became detached from the
2737 ;; original "ddd" insertion. This quirk is a FIXME.
2739 (defun undo-make-selective-list (start end)
2740 "Return a list of undo elements for the region START to END.
2741 The elements come from `buffer-undo-list', but we keep only the
2742 elements inside this region, and discard those outside this
2743 region. The elements' positions are adjusted so as the returned
2744 list can be applied to the current buffer."
2745 (let ((ulist buffer-undo-list)
2746 ;; A list of position adjusted undo elements in the region.
2747 (selective-list (list nil))
2748 ;; A list of undo-deltas for out of region undo elements.
2749 undo-deltas
2750 undo-elt)
2751 (while ulist
2752 (when undo-no-redo
2753 (while (gethash ulist undo-equiv-table)
2754 (setq ulist (gethash ulist undo-equiv-table))))
2755 (setq undo-elt (car ulist))
2756 (cond
2757 ((null undo-elt)
2758 ;; Don't put two nils together in the list
2759 (when (car selective-list)
2760 (push nil selective-list)))
2761 ((and (consp undo-elt) (eq (car undo-elt) t))
2762 ;; This is a "was unmodified" element. Keep it
2763 ;; if we have kept everything thus far.
2764 (when (not undo-deltas)
2765 (push undo-elt selective-list)))
2766 ;; Skip over marker adjustments, instead relying
2767 ;; on finding them after (TEXT . POS) elements
2768 ((markerp (car-safe undo-elt))
2769 nil)
2771 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2772 undo-deltas)))
2773 (if (undo-elt-in-region adjusted-undo-elt start end)
2774 (progn
2775 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2776 (push adjusted-undo-elt selective-list)
2777 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2778 ;; kept. primitive-undo may discard them later.
2779 (when (and (stringp (car-safe adjusted-undo-elt))
2780 (integerp (cdr-safe adjusted-undo-elt)))
2781 (let ((list-i (cdr ulist)))
2782 (while (markerp (car-safe (car list-i)))
2783 (push (pop list-i) selective-list)))))
2784 (let ((delta (undo-delta undo-elt)))
2785 (when (/= 0 (cdr delta))
2786 (push delta undo-deltas)))))))
2787 (pop ulist))
2788 (nreverse selective-list)))
2790 (defun undo-elt-in-region (undo-elt start end)
2791 "Determine whether UNDO-ELT falls inside the region START ... END.
2792 If it crosses the edge, we return nil.
2794 Generally this function is not useful for determining
2795 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2796 because markers can be arbitrarily relocated. Instead, pass the
2797 marker adjustment's corresponding (TEXT . POS) element."
2798 (cond ((integerp undo-elt)
2799 (and (>= undo-elt start)
2800 (<= undo-elt end)))
2801 ((eq undo-elt nil)
2803 ((atom undo-elt)
2804 nil)
2805 ((stringp (car undo-elt))
2806 ;; (TEXT . POSITION)
2807 (and (>= (abs (cdr undo-elt)) start)
2808 (<= (abs (cdr undo-elt)) end)))
2809 ((and (consp undo-elt) (markerp (car undo-elt)))
2810 ;; (MARKER . ADJUSTMENT)
2811 (<= start (car undo-elt) end))
2812 ((null (car undo-elt))
2813 ;; (nil PROPERTY VALUE BEG . END)
2814 (let ((tail (nthcdr 3 undo-elt)))
2815 (and (>= (car tail) start)
2816 (<= (cdr tail) end))))
2817 ((integerp (car undo-elt))
2818 ;; (BEGIN . END)
2819 (and (>= (car undo-elt) start)
2820 (<= (cdr undo-elt) end)))))
2822 (defun undo-elt-crosses-region (undo-elt start end)
2823 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2824 This assumes we have already decided that UNDO-ELT
2825 is not *inside* the region START...END."
2826 (declare (obsolete nil "25.1"))
2827 (cond ((atom undo-elt) nil)
2828 ((null (car undo-elt))
2829 ;; (nil PROPERTY VALUE BEG . END)
2830 (let ((tail (nthcdr 3 undo-elt)))
2831 (and (< (car tail) end)
2832 (> (cdr tail) start))))
2833 ((integerp (car undo-elt))
2834 ;; (BEGIN . END)
2835 (and (< (car undo-elt) end)
2836 (> (cdr undo-elt) start)))))
2838 (defun undo-adjust-elt (elt deltas)
2839 "Return adjustment of undo element ELT by the undo DELTAS
2840 list."
2841 (pcase elt
2842 ;; POSITION
2843 ((pred integerp)
2844 (undo-adjust-pos elt deltas))
2845 ;; (BEG . END)
2846 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2847 (undo-adjust-beg-end beg end deltas))
2848 ;; (TEXT . POSITION)
2849 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2850 (cons text (* (if (< pos 0) -1 1)
2851 (undo-adjust-pos (abs pos) deltas))))
2852 ;; (nil PROPERTY VALUE BEG . END)
2853 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2854 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2855 ;; (apply DELTA START END FUN . ARGS)
2856 ;; FIXME
2857 ;; All others return same elt
2858 (_ elt)))
2860 ;; (BEG . END) can adjust to the same positions, commonly when an
2861 ;; insertion was undone and they are out of region, for example:
2863 ;; buf pos:
2864 ;; 123456789 buffer-undo-list undo-deltas
2865 ;; --------- ---------------- -----------
2866 ;; [...]
2867 ;; abbaa (2 . 4) (2 . -2)
2868 ;; aaa ("bb" . 2) (2 . 2)
2869 ;; [...]
2871 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2872 ;; undo. Further adjustments to such an element should be the same as
2873 ;; for (TEXT . POSITION) elements. The options are:
2875 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2876 ;; analogous to marker insertion-type t.
2878 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2879 ;; marker insertion-type nil.
2881 ;; There was no strong reason to prefer one or the other, except that
2882 ;; the first is more consistent with prior undo in region behavior.
2883 (defun undo-adjust-beg-end (beg end deltas)
2884 "Return cons of adjustments to BEG and END by the undo DELTAS
2885 list."
2886 (let ((adj-beg (undo-adjust-pos beg deltas)))
2887 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2888 (cons adj-beg
2889 (max adj-beg (undo-adjust-pos end deltas t)))))
2891 (defun undo-adjust-pos (pos deltas &optional use-<)
2892 "Return adjustment of POS by the undo DELTAS list, comparing
2893 with < or <= based on USE-<."
2894 (dolist (d deltas pos)
2895 (when (if use-<
2896 (< (car d) pos)
2897 (<= (car d) pos))
2898 (setq pos
2899 ;; Don't allow pos to become less than the undo-delta
2900 ;; position. This edge case is described in the overview
2901 ;; comments.
2902 (max (car d) (- pos (cdr d)))))))
2904 ;; Return the first affected buffer position and the delta for an undo element
2905 ;; delta is defined as the change in subsequent buffer positions if we *did*
2906 ;; the undo.
2907 (defun undo-delta (undo-elt)
2908 (if (consp undo-elt)
2909 (cond ((stringp (car undo-elt))
2910 ;; (TEXT . POSITION)
2911 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2912 ((integerp (car undo-elt))
2913 ;; (BEGIN . END)
2914 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2916 '(0 . 0)))
2917 '(0 . 0)))
2919 ;;; Default undo-boundary addition
2921 ;; This section adds a new undo-boundary at either after a command is
2922 ;; called or in some cases on a timer called after a change is made in
2923 ;; any buffer.
2924 (defvar-local undo-auto--last-boundary-cause nil
2925 "Describe the cause of the last undo-boundary.
2927 If `explicit', the last boundary was caused by an explicit call to
2928 `undo-boundary', that is one not called by the code in this
2929 section.
2931 If it is equal to `timer', then the last boundary was inserted
2932 by `undo-auto--boundary-timer'.
2934 If it is equal to `command', then the last boundary was inserted
2935 automatically after a command, that is by the code defined in
2936 this section.
2938 If it is equal to a list, then the last boundary was inserted by
2939 an amalgamating command. The car of the list is the number of
2940 times an amalgamating command has been called, and the cdr are the
2941 buffers that were changed during the last command.")
2943 (defvar undo-auto-current-boundary-timer nil
2944 "Current timer which will run `undo-auto--boundary-timer' or nil.
2946 If set to non-nil, this will effectively disable the timer.")
2948 (defvar undo-auto--this-command-amalgamating nil
2949 "Non-nil if `this-command' should be amalgamated.
2950 This variable is set to nil by `undo-auto--boundaries' and is set
2951 by `undo-auto-amalgamate'." )
2953 (defun undo-auto--needs-boundary-p ()
2954 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2955 (car-safe buffer-undo-list))
2957 (defun undo-auto--last-boundary-amalgamating-number ()
2958 "Return the number of amalgamating last commands or nil.
2959 Amalgamating commands are, by default, either
2960 `self-insert-command' and `delete-char', but can be any command
2961 that calls `undo-auto-amalgamate'."
2962 (car-safe undo-auto--last-boundary-cause))
2964 (defun undo-auto--ensure-boundary (cause)
2965 "Add an `undo-boundary' to the current buffer if needed.
2966 REASON describes the reason that the boundary is being added; see
2967 `undo-auto--last-boundary' for more information."
2968 (when (and
2969 (undo-auto--needs-boundary-p))
2970 (let ((last-amalgamating
2971 (undo-auto--last-boundary-amalgamating-number)))
2972 (undo-boundary)
2973 (setq undo-auto--last-boundary-cause
2974 (if (eq 'amalgamate cause)
2975 (cons
2976 (if last-amalgamating (1+ last-amalgamating) 0)
2977 undo-auto--undoably-changed-buffers)
2978 cause)))))
2980 (defun undo-auto--boundaries (cause)
2981 "Check recently changed buffers and add a boundary if necessary.
2982 REASON describes the reason that the boundary is being added; see
2983 `undo-last-boundary' for more information."
2984 ;; (Bug #23785) All commands should ensure that there is an undo
2985 ;; boundary whether they have changed the current buffer or not.
2986 (when (eq cause 'command)
2987 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2988 (dolist (b undo-auto--undoably-changed-buffers)
2989 (when (buffer-live-p b)
2990 (with-current-buffer b
2991 (undo-auto--ensure-boundary cause))))
2992 (setq undo-auto--undoably-changed-buffers nil))
2994 (defun undo-auto--boundary-timer ()
2995 "Timer which will run `undo--auto-boundary-timer'."
2996 (setq undo-auto-current-boundary-timer nil)
2997 (undo-auto--boundaries 'timer))
2999 (defun undo-auto--boundary-ensure-timer ()
3000 "Ensure that the `undo-auto-boundary-timer' is set."
3001 (unless undo-auto-current-boundary-timer
3002 (setq undo-auto-current-boundary-timer
3003 (run-at-time 10 nil #'undo-auto--boundary-timer))))
3005 (defvar undo-auto--undoably-changed-buffers nil
3006 "List of buffers that have changed recently.
3008 This list is maintained by `undo-auto--undoable-change' and
3009 `undo-auto--boundaries' and can be affected by changes to their
3010 default values.")
3012 (defun undo-auto--add-boundary ()
3013 "Add an `undo-boundary' in appropriate buffers."
3014 (undo-auto--boundaries
3015 (let ((amal undo-auto--this-command-amalgamating))
3016 (setq undo-auto--this-command-amalgamating nil)
3017 (if amal
3018 'amalgamate
3019 'command))))
3021 (defun undo-auto-amalgamate ()
3022 "Amalgamate undo if necessary.
3023 This function can be called before an amalgamating command. It
3024 removes the previous `undo-boundary' if a series of such calls
3025 have been made. By default `self-insert-command' and
3026 `delete-char' are the only amalgamating commands, although this
3027 function could be called by any command wishing to have this
3028 behavior."
3029 (let ((last-amalgamating-count
3030 (undo-auto--last-boundary-amalgamating-number)))
3031 (setq undo-auto--this-command-amalgamating t)
3032 (when
3033 last-amalgamating-count
3035 (and
3036 (< last-amalgamating-count 20)
3037 (eq this-command last-command))
3038 ;; Amalgamate all buffers that have changed.
3039 (dolist (b (cdr undo-auto--last-boundary-cause))
3040 (when (buffer-live-p b)
3041 (with-current-buffer
3043 (when
3044 ;; The head of `buffer-undo-list' is nil.
3045 ;; `car-safe' doesn't work because
3046 ;; `buffer-undo-list' need not be a list!
3047 (and (listp buffer-undo-list)
3048 (not (car buffer-undo-list)))
3049 (setq buffer-undo-list
3050 (cdr buffer-undo-list))))))
3051 (setq undo-auto--last-boundary-cause 0)))))
3053 (defun undo-auto--undoable-change ()
3054 "Called after every undoable buffer change."
3055 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
3056 (undo-auto--boundary-ensure-timer))
3057 ;; End auto-boundary section
3059 (defun undo-amalgamate-change-group (handle)
3060 "Amalgamate changes in change-group since HANDLE.
3061 Remove all undo boundaries between the state of HANDLE and now.
3062 HANDLE is as returned by `prepare-change-group'."
3063 (dolist (elt handle)
3064 (with-current-buffer (car elt)
3065 (setq elt (cdr elt))
3066 (when (consp buffer-undo-list)
3067 (let ((old-car (car-safe elt))
3068 (old-cdr (cdr-safe elt)))
3069 (unwind-protect
3070 (progn
3071 ;; Temporarily truncate the undo log at ELT.
3072 (when (consp elt)
3073 (setcar elt t) (setcdr elt nil))
3074 (when
3075 (or (null elt) ;The undo-log was empty.
3076 ;; `elt' is still in the log: normal case.
3077 (eq elt (last buffer-undo-list))
3078 ;; `elt' is not in the log any more, but that's because
3079 ;; the log is "all new", so we should remove all
3080 ;; boundaries from it.
3081 (not (eq (last buffer-undo-list) (last old-cdr))))
3082 (cl-callf (lambda (x) (delq nil x))
3083 (if (car buffer-undo-list)
3084 buffer-undo-list
3085 ;; Preserve the undo-boundaries at either ends of the
3086 ;; change-groups.
3087 (cdr buffer-undo-list)))))
3088 ;; Reset the modified cons cell ELT to its original content.
3089 (when (consp elt)
3090 (setcar elt old-car)
3091 (setcdr elt old-cdr))))))))
3094 (defcustom undo-ask-before-discard nil
3095 "If non-nil ask about discarding undo info for the current command.
3096 Normally, Emacs discards the undo info for the current command if
3097 it exceeds `undo-outer-limit'. But if you set this option
3098 non-nil, it asks in the echo area whether to discard the info.
3099 If you answer no, there is a slight risk that Emacs might crash, so
3100 only do it if you really want to undo the command.
3102 This option is mainly intended for debugging. You have to be
3103 careful if you use it for other purposes. Garbage collection is
3104 inhibited while the question is asked, meaning that Emacs might
3105 leak memory. So you should make sure that you do not wait
3106 excessively long before answering the question."
3107 :type 'boolean
3108 :group 'undo
3109 :version "22.1")
3111 (defvar undo-extra-outer-limit nil
3112 "If non-nil, an extra level of size that's ok in an undo item.
3113 We don't ask the user about truncating the undo list until the
3114 current item gets bigger than this amount.
3116 This variable only matters if `undo-ask-before-discard' is non-nil.")
3117 (make-variable-buffer-local 'undo-extra-outer-limit)
3119 ;; When the first undo batch in an undo list is longer than
3120 ;; undo-outer-limit, this function gets called to warn the user that
3121 ;; the undo info for the current command was discarded. Garbage
3122 ;; collection is inhibited around the call, so it had better not do a
3123 ;; lot of consing.
3124 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3125 (defun undo-outer-limit-truncate (size)
3126 (if undo-ask-before-discard
3127 (when (or (null undo-extra-outer-limit)
3128 (> size undo-extra-outer-limit))
3129 ;; Don't ask the question again unless it gets even bigger.
3130 ;; This applies, in particular, if the user quits from the question.
3131 ;; Such a quit quits out of GC, but something else will call GC
3132 ;; again momentarily. It will call this function again,
3133 ;; but we don't want to ask the question again.
3134 (setq undo-extra-outer-limit (+ size 50000))
3135 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3136 (yes-or-no-p (format-message
3137 "Buffer `%s' undo info is %d bytes long; discard it? "
3138 (buffer-name) size)))
3139 (progn (setq buffer-undo-list nil)
3140 (setq undo-extra-outer-limit nil)
3142 nil))
3143 (display-warning '(undo discard-info)
3144 (concat
3145 (format-message
3146 "Buffer `%s' undo info was %d bytes long.\n"
3147 (buffer-name) size)
3148 "The undo info was discarded because it exceeded \
3149 `undo-outer-limit'.
3151 This is normal if you executed a command that made a huge change
3152 to the buffer. In that case, to prevent similar problems in the
3153 future, set `undo-outer-limit' to a value that is large enough to
3154 cover the maximum size of normal changes you expect a single
3155 command to make, but not so large that it might exceed the
3156 maximum memory allotted to Emacs.
3158 If you did not execute any such command, the situation is
3159 probably due to a bug and you should report it.
3161 You can disable the popping up of this buffer by adding the entry
3162 \(undo discard-info) to the user option `warning-suppress-types',
3163 which is defined in the `warnings' library.\n")
3164 :warning)
3165 (setq buffer-undo-list nil)
3168 (defcustom password-word-equivalents
3169 '("password" "passcode" "passphrase" "pass phrase"
3170 ; These are sorted according to the GNU en_US locale.
3171 "암호" ; ko
3172 "パスワード" ; ja
3173 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3174 "ពាក្យសម្ងាត់" ; km
3175 "adgangskode" ; da
3176 "contraseña" ; es
3177 "contrasenya" ; ca
3178 "geslo" ; sl
3179 "hasło" ; pl
3180 "heslo" ; cs, sk
3181 "iphasiwedi" ; zu
3182 "jelszó" ; hu
3183 "lösenord" ; sv
3184 "lozinka" ; hr, sr
3185 "mật khẩu" ; vi
3186 "mot de passe" ; fr
3187 "parola" ; tr
3188 "pasahitza" ; eu
3189 "passord" ; nb
3190 "passwort" ; de
3191 "pasvorto" ; eo
3192 "salasana" ; fi
3193 "senha" ; pt
3194 "slaptažodis" ; lt
3195 "wachtwoord" ; nl
3196 "كلمة السر" ; ar
3197 "ססמה" ; he
3198 "лозинка" ; sr
3199 "пароль" ; kk, ru, uk
3200 "गुप्तशब्द" ; mr
3201 "शब्दकूट" ; hi
3202 "પાસવર્ડ" ; gu
3203 "సంకేతపదము" ; te
3204 "ਪਾਸਵਰਡ" ; pa
3205 "ಗುಪ್ತಪದ" ; kn
3206 "கடவுச்சொல்" ; ta
3207 "അടയാളവാക്ക്" ; ml
3208 "গুপ্তশব্দ" ; as
3209 "পাসওয়ার্ড" ; bn_IN
3210 "රහස්පදය" ; si
3211 "密码" ; zh_CN
3212 "密碼" ; zh_TW
3214 "List of words equivalent to \"password\".
3215 This is used by Shell mode and other parts of Emacs to recognize
3216 password prompts, including prompts in languages other than
3217 English. Different case choices should not be assumed to be
3218 included; callers should bind `case-fold-search' to t."
3219 :type '(repeat string)
3220 :version "24.4"
3221 :group 'processes)
3223 (defvar shell-command-history nil
3224 "History list for some commands that read shell commands.
3226 Maximum length of the history list is determined by the value
3227 of `history-length', which see.")
3229 (defvar shell-command-switch (purecopy "-c")
3230 "Switch used to have the shell execute its command line argument.")
3232 (defvar shell-command-default-error-buffer nil
3233 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3234 This buffer is used when `shell-command' or `shell-command-on-region'
3235 is run interactively. A value of nil means that output to stderr and
3236 stdout will be intermixed in the output stream.")
3238 (declare-function mailcap-file-default-commands "mailcap" (files))
3239 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3241 (defun minibuffer-default-add-shell-commands ()
3242 "Return a list of all commands associated with the current file.
3243 This function is used to add all related commands retrieved by `mailcap'
3244 to the end of the list of defaults just after the default value."
3245 (interactive)
3246 (let* ((filename (if (listp minibuffer-default)
3247 (car minibuffer-default)
3248 minibuffer-default))
3249 (commands (and filename (require 'mailcap nil t)
3250 (mailcap-file-default-commands (list filename)))))
3251 (setq commands (mapcar (lambda (command)
3252 (concat command " " filename))
3253 commands))
3254 (if (listp minibuffer-default)
3255 (append minibuffer-default commands)
3256 (cons minibuffer-default commands))))
3258 (declare-function shell-completion-vars "shell" ())
3260 (defvar minibuffer-local-shell-command-map
3261 (let ((map (make-sparse-keymap)))
3262 (set-keymap-parent map minibuffer-local-map)
3263 (define-key map "\t" 'completion-at-point)
3264 map)
3265 "Keymap used for completing shell commands in minibuffer.")
3267 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3268 "Read a shell command from the minibuffer.
3269 The arguments are the same as the ones of `read-from-minibuffer',
3270 except READ and KEYMAP are missing and HIST defaults
3271 to `shell-command-history'."
3272 (require 'shell)
3273 (minibuffer-with-setup-hook
3274 (lambda ()
3275 (shell-completion-vars)
3276 (set (make-local-variable 'minibuffer-default-add-function)
3277 'minibuffer-default-add-shell-commands))
3278 (apply 'read-from-minibuffer prompt initial-contents
3279 minibuffer-local-shell-command-map
3281 (or hist 'shell-command-history)
3282 args)))
3284 (defcustom async-shell-command-buffer 'confirm-new-buffer
3285 "What to do when the output buffer is used by another shell command.
3286 This option specifies how to resolve the conflict where a new command
3287 wants to direct its output to the buffer `*Async Shell Command*',
3288 but this buffer is already taken by another running shell command.
3290 The value `confirm-kill-process' is used to ask for confirmation before
3291 killing the already running process and running a new process
3292 in the same buffer, `confirm-new-buffer' for confirmation before running
3293 the command in a new buffer with a name other than the default buffer name,
3294 `new-buffer' for doing the same without confirmation,
3295 `confirm-rename-buffer' for confirmation before renaming the existing
3296 output buffer and running a new command in the default buffer,
3297 `rename-buffer' for doing the same without confirmation."
3298 :type '(choice (const :tag "Confirm killing of running command"
3299 confirm-kill-process)
3300 (const :tag "Confirm creation of a new buffer"
3301 confirm-new-buffer)
3302 (const :tag "Create a new buffer"
3303 new-buffer)
3304 (const :tag "Confirm renaming of existing buffer"
3305 confirm-rename-buffer)
3306 (const :tag "Rename the existing buffer"
3307 rename-buffer))
3308 :group 'shell
3309 :version "24.3")
3311 (defcustom async-shell-command-display-buffer t
3312 "Whether to display the command buffer immediately.
3313 If t, display the buffer immediately; if nil, wait until there
3314 is output."
3315 :type '(choice (const :tag "Display buffer immediately"
3317 (const :tag "Display buffer on output"
3318 nil))
3319 :group 'shell
3320 :version "26.1")
3322 (defcustom shell-command-dont-erase-buffer nil
3323 "If non-nil, output buffer is not erased between shell commands.
3324 Also, a non-nil value sets the point in the output buffer
3325 once the command completes.
3326 The value `beg-last-out' sets point at the beginning of the output,
3327 `end-last-out' sets point at the end of the buffer, `save-point'
3328 restores the buffer position before the command."
3329 :type '(choice
3330 (const :tag "Erase buffer" nil)
3331 (const :tag "Set point to beginning of last output" beg-last-out)
3332 (const :tag "Set point to end of last output" end-last-out)
3333 (const :tag "Save point" save-point))
3334 :group 'shell
3335 :version "26.1")
3337 (defvar shell-command-saved-pos nil
3338 "Record of point positions in output buffers after command completion.
3339 The value is an alist whose elements are of the form (BUFFER . POS),
3340 where BUFFER is the output buffer, and POS is the point position
3341 in BUFFER once the command finishes.
3342 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
3344 (defun shell-command--save-pos-or-erase ()
3345 "Store a buffer position or erase the buffer.
3346 See `shell-command-dont-erase-buffer'."
3347 (let ((sym shell-command-dont-erase-buffer)
3348 pos)
3349 (setq buffer-read-only nil)
3350 ;; Setting buffer-read-only to nil doesn't suffice
3351 ;; if some text has a non-nil read-only property,
3352 ;; which comint sometimes adds for prompts.
3353 (setq pos
3354 (cond ((eq sym 'save-point) (point))
3355 ((eq sym 'beg-last-out) (point-max))
3356 ((not sym)
3357 (let ((inhibit-read-only t))
3358 (erase-buffer) nil))))
3359 (when pos
3360 (goto-char (point-max))
3361 (push (cons (current-buffer) pos)
3362 shell-command-saved-pos))))
3364 (defun shell-command--set-point-after-cmd (&optional buffer)
3365 "Set point in BUFFER after command complete.
3366 BUFFER is the output buffer of the command; if nil, then defaults
3367 to the current BUFFER.
3368 Set point to the `cdr' of the element in `shell-command-saved-pos'
3369 whose `car' is BUFFER."
3370 (when shell-command-dont-erase-buffer
3371 (let* ((sym shell-command-dont-erase-buffer)
3372 (buf (or buffer (current-buffer)))
3373 (pos (alist-get buf shell-command-saved-pos)))
3374 (setq shell-command-saved-pos
3375 (assq-delete-all buf shell-command-saved-pos))
3376 (when (buffer-live-p buf)
3377 (let ((win (car (get-buffer-window-list buf)))
3378 (pmax (with-current-buffer buf (point-max))))
3379 (unless (and pos (memq sym '(save-point beg-last-out)))
3380 (setq pos pmax))
3381 ;; Set point in the window displaying buf, if any; otherwise
3382 ;; display buf temporary in selected frame and set the point.
3383 (if win
3384 (set-window-point win pos)
3385 (save-window-excursion
3386 (let ((win (display-buffer
3388 '(nil (inhibit-switch-frame . t)))))
3389 (set-window-point win pos)))))))))
3391 (defun async-shell-command (command &optional output-buffer error-buffer)
3392 "Execute string COMMAND asynchronously in background.
3394 Like `shell-command', but adds `&' at the end of COMMAND
3395 to execute it asynchronously.
3397 The output appears in the buffer `*Async Shell Command*'.
3398 That buffer is in shell mode.
3400 You can configure `async-shell-command-buffer' to specify what to do
3401 when the `*Async Shell Command*' buffer is already taken by another
3402 running shell command. To run COMMAND without displaying the output
3403 in a window you can configure `display-buffer-alist' to use the action
3404 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3406 In Elisp, you will often be better served by calling `start-process'
3407 directly, since it offers more control and does not impose the use of
3408 a shell (with its need to quote arguments)."
3409 (interactive
3410 (list
3411 (read-shell-command "Async shell command: " nil nil
3412 (let ((filename
3413 (cond
3414 (buffer-file-name)
3415 ((eq major-mode 'dired-mode)
3416 (dired-get-filename nil t)))))
3417 (and filename (file-relative-name filename))))
3418 current-prefix-arg
3419 shell-command-default-error-buffer))
3420 (unless (string-match "&[ \t]*\\'" command)
3421 (setq command (concat command " &")))
3422 (shell-command command output-buffer error-buffer))
3424 (defun shell-command (command &optional output-buffer error-buffer)
3425 "Execute string COMMAND in inferior shell; display output, if any.
3426 With prefix argument, insert the COMMAND's output at point.
3428 Interactively, prompt for COMMAND in the minibuffer.
3430 If COMMAND ends in `&', execute it asynchronously.
3431 The output appears in the buffer `*Async Shell Command*'.
3432 That buffer is in shell mode. You can also use
3433 `async-shell-command' that automatically adds `&'.
3435 Otherwise, COMMAND is executed synchronously. The output appears in
3436 the buffer `*Shell Command Output*'. If the output is short enough to
3437 display in the echo area (which is determined by the variables
3438 `resize-mini-windows' and `max-mini-window-height'), it is shown
3439 there, but it is nonetheless available in buffer `*Shell Command
3440 Output*' even though that buffer is not automatically displayed.
3442 To specify a coding system for converting non-ASCII characters
3443 in the shell command output, use \\[universal-coding-system-argument] \
3444 before this command.
3446 Noninteractive callers can specify coding systems by binding
3447 `coding-system-for-read' and `coding-system-for-write'.
3449 The optional second argument OUTPUT-BUFFER, if non-nil,
3450 says to put the output in some other buffer.
3451 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3452 and insert the output there; a non-nil value of
3453 `shell-command-dont-erase-buffer' prevents the buffer from being
3454 erased. If OUTPUT-BUFFER is not a buffer and not nil, insert the
3455 output in current buffer after point leaving mark after it. This
3456 cannot be done asynchronously.
3458 If the command terminates without error, but generates output,
3459 and you did not specify \"insert it in the current buffer\",
3460 the output can be displayed in the echo area or in its buffer.
3461 If the output is short enough to display in the echo area
3462 \(determined by the variable `max-mini-window-height' if
3463 `resize-mini-windows' is non-nil), it is shown there.
3464 Otherwise, the buffer containing the output is displayed.
3466 If there is output and an error, and you did not specify \"insert it
3467 in the current buffer\", a message about the error goes at the end
3468 of the output.
3470 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3471 or buffer name to which to direct the command's standard error output.
3472 If it is nil, error output is mingled with regular output.
3473 In an interactive call, the variable `shell-command-default-error-buffer'
3474 specifies the value of ERROR-BUFFER.
3476 In Elisp, you will often be better served by calling `call-process' or
3477 `start-process' directly, since they offer more control and do not
3478 impose the use of a shell (with its need to quote arguments)."
3480 (interactive
3481 (list
3482 (read-shell-command "Shell command: " nil nil
3483 (let ((filename
3484 (cond
3485 (buffer-file-name)
3486 ((eq major-mode 'dired-mode)
3487 (dired-get-filename nil t)))))
3488 (and filename (file-relative-name filename))))
3489 current-prefix-arg
3490 shell-command-default-error-buffer))
3491 ;; Look for a handler in case default-directory is a remote file name.
3492 (let ((handler
3493 (find-file-name-handler (directory-file-name default-directory)
3494 'shell-command)))
3495 (if handler
3496 (funcall handler 'shell-command command output-buffer error-buffer)
3497 (if (and output-buffer
3498 (not (or (bufferp output-buffer) (stringp output-buffer))))
3499 ;; Output goes in current buffer.
3500 (let ((error-file
3501 (if error-buffer
3502 (make-temp-file
3503 (expand-file-name "scor"
3504 (or small-temporary-file-directory
3505 temporary-file-directory)))
3506 nil)))
3507 (barf-if-buffer-read-only)
3508 (push-mark nil t)
3509 ;; We do not use -f for csh; we will not support broken use of
3510 ;; .cshrcs. Even the BSD csh manual says to use
3511 ;; "if ($?prompt) exit" before things which are not useful
3512 ;; non-interactively. Besides, if someone wants their other
3513 ;; aliases for shell commands then they can still have them.
3514 (call-process shell-file-name nil
3515 (if error-file
3516 (list t error-file)
3518 nil shell-command-switch command)
3519 (when (and error-file (file-exists-p error-file))
3520 (if (< 0 (nth 7 (file-attributes error-file)))
3521 (with-current-buffer (get-buffer-create error-buffer)
3522 (let ((pos-from-end (- (point-max) (point))))
3523 (or (bobp)
3524 (insert "\f\n"))
3525 ;; Do no formatting while reading error file,
3526 ;; because that can run a shell command, and we
3527 ;; don't want that to cause an infinite recursion.
3528 (format-insert-file error-file nil)
3529 ;; Put point after the inserted errors.
3530 (goto-char (- (point-max) pos-from-end)))
3531 (display-buffer (current-buffer))))
3532 (delete-file error-file))
3533 ;; This is like exchange-point-and-mark, but doesn't
3534 ;; activate the mark. It is cleaner to avoid activation,
3535 ;; even though the command loop would deactivate the mark
3536 ;; because we inserted text.
3537 (goto-char (prog1 (mark t)
3538 (set-marker (mark-marker) (point)
3539 (current-buffer)))))
3540 ;; Output goes in a separate buffer.
3541 ;; Preserve the match data in case called from a program.
3542 ;; FIXME: It'd be ridiculous for an Elisp function to call
3543 ;; shell-command and assume that it won't mess the match-data!
3544 (save-match-data
3545 (if (string-match "[ \t]*&[ \t]*\\'" command)
3546 ;; Command ending with ampersand means asynchronous.
3547 (let* ((buffer (get-buffer-create
3548 (or output-buffer "*Async Shell Command*")))
3549 (bname (buffer-name buffer))
3550 (directory default-directory)
3551 proc)
3552 ;; Remove the ampersand.
3553 (setq command (substring command 0 (match-beginning 0)))
3554 ;; Ask the user what to do with already running process.
3555 (setq proc (get-buffer-process buffer))
3556 (when proc
3557 (cond
3558 ((eq async-shell-command-buffer 'confirm-kill-process)
3559 ;; If will kill a process, query first.
3560 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3561 (kill-process proc)
3562 (error "Shell command in progress")))
3563 ((eq async-shell-command-buffer 'confirm-new-buffer)
3564 ;; If will create a new buffer, query first.
3565 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3566 (setq buffer (generate-new-buffer bname))
3567 (error "Shell command in progress")))
3568 ((eq async-shell-command-buffer 'new-buffer)
3569 ;; It will create a new buffer.
3570 (setq buffer (generate-new-buffer bname)))
3571 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3572 ;; If will rename the buffer, query first.
3573 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3574 (progn
3575 (with-current-buffer buffer
3576 (rename-uniquely))
3577 (setq buffer (get-buffer-create bname)))
3578 (error "Shell command in progress")))
3579 ((eq async-shell-command-buffer 'rename-buffer)
3580 ;; It will rename the buffer.
3581 (with-current-buffer buffer
3582 (rename-uniquely))
3583 (setq buffer (get-buffer-create bname)))))
3584 (with-current-buffer buffer
3585 (shell-command--save-pos-or-erase)
3586 (setq default-directory directory)
3587 (setq proc (start-process "Shell" buffer shell-file-name
3588 shell-command-switch command))
3589 (setq mode-line-process '(":%s"))
3590 (require 'shell) (shell-mode)
3591 (set-process-sentinel proc 'shell-command-sentinel)
3592 ;; Use the comint filter for proper handling of
3593 ;; carriage motion (see comint-inhibit-carriage-motion).
3594 (set-process-filter proc 'comint-output-filter)
3595 (if async-shell-command-display-buffer
3596 ;; Display buffer immediately.
3597 (display-buffer buffer '(nil (allow-no-window . t)))
3598 ;; Defer displaying buffer until first process output.
3599 ;; Use disposable named advice so that the buffer is
3600 ;; displayed at most once per process lifetime.
3601 (let ((nonce (make-symbol "nonce")))
3602 (add-function :before (process-filter proc)
3603 (lambda (proc _string)
3604 (let ((buf (process-buffer proc)))
3605 (when (buffer-live-p buf)
3606 (remove-function (process-filter proc)
3607 nonce)
3608 (display-buffer buf))))
3609 `((name . ,nonce)))))))
3610 ;; Otherwise, command is executed synchronously.
3611 (shell-command-on-region (point) (point) command
3612 output-buffer nil error-buffer)))))))
3614 (defun display-message-or-buffer (message &optional buffer-name action frame)
3615 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3616 MESSAGE may be either a string or a buffer.
3618 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3619 for maximum height of the echo area, as defined by `max-mini-window-height'
3620 if `resize-mini-windows' is non-nil.
3622 Returns either the string shown in the echo area, or when a pop-up
3623 buffer is used, the window used to display it.
3625 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3626 name of the buffer used to display it in the case where a pop-up buffer
3627 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3628 string and it is displayed in the echo area, it is not specified whether
3629 the contents are inserted into the buffer anyway.
3631 Optional arguments ACTION and FRAME are as for `display-buffer',
3632 and are only used if a pop-up buffer is displayed."
3633 (cond ((and (stringp message) (not (string-match "\n" message)))
3634 ;; Trivial case where we can use the echo area
3635 (message "%s" message))
3636 ((and (stringp message)
3637 (= (string-match "\n" message) (1- (length message))))
3638 ;; Trivial case where we can just remove single trailing newline
3639 (message "%s" (substring message 0 (1- (length message)))))
3641 ;; General case
3642 (with-current-buffer
3643 (if (bufferp message)
3644 message
3645 (get-buffer-create (or buffer-name "*Message*")))
3647 (unless (bufferp message)
3648 (erase-buffer)
3649 (insert message))
3651 (let ((lines
3652 (if (= (buffer-size) 0)
3654 (count-screen-lines nil nil nil (minibuffer-window)))))
3655 (cond ((= lines 0))
3656 ((and (or (<= lines 1)
3657 (<= lines
3658 (if resize-mini-windows
3659 (cond ((floatp max-mini-window-height)
3660 (* (frame-height)
3661 max-mini-window-height))
3662 ((integerp max-mini-window-height)
3663 max-mini-window-height)
3666 1)))
3667 ;; Don't use the echo area if the output buffer is
3668 ;; already displayed in the selected frame.
3669 (not (get-buffer-window (current-buffer))))
3670 ;; Echo area
3671 (goto-char (point-max))
3672 (when (bolp)
3673 (backward-char 1))
3674 (message "%s" (buffer-substring (point-min) (point))))
3676 ;; Buffer
3677 (goto-char (point-min))
3678 (display-buffer (current-buffer) action frame))))))))
3681 ;; We have a sentinel to prevent insertion of a termination message
3682 ;; in the buffer itself, and to set the point in the buffer when
3683 ;; `shell-command-dont-erase-buffer' is non-nil.
3684 (defun shell-command-sentinel (process signal)
3685 (when (memq (process-status process) '(exit signal))
3686 (shell-command--set-point-after-cmd (process-buffer process))
3687 (message "%s: %s."
3688 (car (cdr (cdr (process-command process))))
3689 (substring signal 0 -1))))
3691 (defun shell-command-on-region (start end command
3692 &optional output-buffer replace
3693 error-buffer display-error-buffer
3694 region-noncontiguous-p)
3695 "Execute string COMMAND in inferior shell with region as input.
3696 Normally display output (if any) in temp buffer `*Shell Command Output*';
3697 Prefix arg means replace the region with it. Return the exit code of
3698 COMMAND.
3700 To specify a coding system for converting non-ASCII characters
3701 in the input and output to the shell command, use \\[universal-coding-system-argument]
3702 before this command. By default, the input (from the current buffer)
3703 is encoded using coding-system specified by `process-coding-system-alist',
3704 falling back to `default-process-coding-system' if no match for COMMAND
3705 is found in `process-coding-system-alist'.
3707 Noninteractive callers can specify coding systems by binding
3708 `coding-system-for-read' and `coding-system-for-write'.
3710 If the command generates output, the output may be displayed
3711 in the echo area or in a buffer.
3712 If the output is short enough to display in the echo area
3713 \(determined by the variable `max-mini-window-height' if
3714 `resize-mini-windows' is non-nil), it is shown there.
3715 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3716 The output is available in that buffer in both cases.
3718 If there is output and an error, a message about the error
3719 appears at the end of the output.
3721 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3722 command's output. If the value is a buffer or buffer name,
3723 erase that buffer and insert the output there; a non-nil value of
3724 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3725 If the value is nil, use the buffer `*Shell Command Output*'.
3726 Any other non-nil value means to insert the output in the
3727 current buffer after START.
3729 Optional fifth arg REPLACE, if non-nil, means to insert the
3730 output in place of text from START to END, putting point and mark
3731 around it.
3733 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3734 or buffer name to which to direct the command's standard error
3735 output. If nil, error output is mingled with regular output.
3736 When called interactively, `shell-command-default-error-buffer'
3737 is used for ERROR-BUFFER.
3739 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3740 display the error buffer if there were any errors. When called
3741 interactively, this is t."
3742 (interactive (let (string)
3743 (unless (mark)
3744 (user-error "The mark is not set now, so there is no region"))
3745 ;; Do this before calling region-beginning
3746 ;; and region-end, in case subprocess output
3747 ;; relocates them while we are in the minibuffer.
3748 (setq string (read-shell-command "Shell command on region: "))
3749 ;; call-interactively recognizes region-beginning and
3750 ;; region-end specially, leaving them in the history.
3751 (list (region-beginning) (region-end)
3752 string
3753 current-prefix-arg
3754 current-prefix-arg
3755 shell-command-default-error-buffer
3757 (region-noncontiguous-p))))
3758 (let ((error-file
3759 (if error-buffer
3760 (make-temp-file
3761 (expand-file-name "scor"
3762 (or small-temporary-file-directory
3763 temporary-file-directory)))
3764 nil))
3765 exit-status)
3766 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3767 (if region-noncontiguous-p
3768 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3769 output)
3770 (with-temp-buffer
3771 (insert input)
3772 (call-process-region (point-min) (point-max)
3773 shell-file-name t t
3774 nil shell-command-switch
3775 command)
3776 (setq output (split-string (buffer-string) "\n")))
3777 (goto-char start)
3778 (funcall region-insert-function output))
3779 (if (or replace
3780 (and output-buffer
3781 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3782 ;; Replace specified region with output from command.
3783 (let ((swap (and replace (< start end))))
3784 ;; Don't muck with mark unless REPLACE says we should.
3785 (goto-char start)
3786 (and replace (push-mark (point) 'nomsg))
3787 (setq exit-status
3788 (call-shell-region start end command replace
3789 (if error-file
3790 (list t error-file)
3791 t)))
3792 ;; It is rude to delete a buffer which the command is not using.
3793 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3794 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3795 ;; (kill-buffer shell-buffer)))
3796 ;; Don't muck with mark unless REPLACE says we should.
3797 (and replace swap (exchange-point-and-mark)))
3798 ;; No prefix argument: put the output in a temp buffer,
3799 ;; replacing its entire contents.
3800 (let ((buffer (get-buffer-create
3801 (or output-buffer "*Shell Command Output*"))))
3802 (unwind-protect
3803 (if (and (eq buffer (current-buffer))
3804 (or (not shell-command-dont-erase-buffer)
3805 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3806 (not (region-active-p)))))
3807 ;; If the input is the same buffer as the output,
3808 ;; delete everything but the specified region,
3809 ;; then replace that region with the output.
3810 (progn (setq buffer-read-only nil)
3811 (delete-region (max start end) (point-max))
3812 (delete-region (point-min) (min start end))
3813 (setq exit-status
3814 (call-process-region (point-min) (point-max)
3815 shell-file-name t
3816 (if error-file
3817 (list t error-file)
3819 nil shell-command-switch
3820 command)))
3821 ;; Clear the output buffer, then run the command with
3822 ;; output there.
3823 (let ((directory default-directory))
3824 (with-current-buffer buffer
3825 (if (not output-buffer)
3826 (setq default-directory directory))
3827 (shell-command--save-pos-or-erase)))
3828 (setq exit-status
3829 (call-shell-region start end command nil
3830 (if error-file
3831 (list buffer error-file)
3832 buffer))))
3833 ;; Report the output.
3834 (with-current-buffer buffer
3835 (setq mode-line-process
3836 (cond ((null exit-status)
3837 " - Error")
3838 ((stringp exit-status)
3839 (format " - Signal [%s]" exit-status))
3840 ((not (equal 0 exit-status))
3841 (format " - Exit [%d]" exit-status)))))
3842 (if (with-current-buffer buffer (> (point-max) (point-min)))
3843 ;; There's some output, display it
3844 (progn
3845 (display-message-or-buffer buffer)
3846 (shell-command--set-point-after-cmd buffer))
3847 ;; No output; error?
3848 (let ((output
3849 (if (and error-file
3850 (< 0 (nth 7 (file-attributes error-file))))
3851 (format "some error output%s"
3852 (if shell-command-default-error-buffer
3853 (format " to the \"%s\" buffer"
3854 shell-command-default-error-buffer)
3855 ""))
3856 "no output")))
3857 (cond ((null exit-status)
3858 (message "(Shell command failed with error)"))
3859 ((equal 0 exit-status)
3860 (message "(Shell command succeeded with %s)"
3861 output))
3862 ((stringp exit-status)
3863 (message "(Shell command killed by signal %s)"
3864 exit-status))
3866 (message "(Shell command failed with code %d and %s)"
3867 exit-status output))))
3868 ;; Don't kill: there might be useful info in the undo-log.
3869 ;; (kill-buffer buffer)
3870 )))))
3872 (when (and error-file (file-exists-p error-file))
3873 (if (< 0 (nth 7 (file-attributes error-file)))
3874 (with-current-buffer (get-buffer-create error-buffer)
3875 (let ((pos-from-end (- (point-max) (point))))
3876 (or (bobp)
3877 (insert "\f\n"))
3878 ;; Do no formatting while reading error file,
3879 ;; because that can run a shell command, and we
3880 ;; don't want that to cause an infinite recursion.
3881 (format-insert-file error-file nil)
3882 ;; Put point after the inserted errors.
3883 (goto-char (- (point-max) pos-from-end)))
3884 (and display-error-buffer
3885 (display-buffer (current-buffer)))))
3886 (delete-file error-file))
3887 exit-status))
3889 (defun shell-command-to-string (command)
3890 "Execute shell command COMMAND and return its output as a string."
3891 (with-output-to-string
3892 (with-current-buffer
3893 standard-output
3894 (shell-command command t))))
3896 (defun process-file (program &optional infile buffer display &rest args)
3897 "Process files synchronously in a separate process.
3898 Similar to `call-process', but may invoke a file handler based on
3899 `default-directory'. The current working directory of the
3900 subprocess is `default-directory'.
3902 File names in INFILE and BUFFER are handled normally, but file
3903 names in ARGS should be relative to `default-directory', as they
3904 are passed to the process verbatim. (This is a difference to
3905 `call-process' which does not support file handlers for INFILE
3906 and BUFFER.)
3908 Some file handlers might not support all variants, for example
3909 they might behave as if DISPLAY was nil, regardless of the actual
3910 value passed."
3911 (let ((fh (find-file-name-handler default-directory 'process-file))
3912 lc stderr-file)
3913 (unwind-protect
3914 (if fh (apply fh 'process-file program infile buffer display args)
3915 (when infile (setq lc (file-local-copy infile)))
3916 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3917 (make-temp-file "emacs")))
3918 (prog1
3919 (apply 'call-process program
3920 (or lc infile)
3921 (if stderr-file (list (car buffer) stderr-file) buffer)
3922 display args)
3923 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3924 (when stderr-file (delete-file stderr-file))
3925 (when lc (delete-file lc)))))
3927 (defvar process-file-side-effects t
3928 "Whether a call of `process-file' changes remote files.
3930 By default, this variable is always set to t, meaning that a
3931 call of `process-file' could potentially change any file on a
3932 remote host. When set to nil, a file handler could optimize
3933 its behavior with respect to remote file attribute caching.
3935 You should only ever change this variable with a let-binding;
3936 never with `setq'.")
3938 (defun start-file-process (name buffer program &rest program-args)
3939 "Start a program in a subprocess. Return the process object for it.
3941 Similar to `start-process', but may invoke a file handler based on
3942 `default-directory'. See Info node `(elisp)Magic File Names'.
3944 This handler ought to run PROGRAM, perhaps on the local host,
3945 perhaps on a remote host that corresponds to `default-directory'.
3946 In the latter case, the local part of `default-directory' becomes
3947 the working directory of the process.
3949 PROGRAM and PROGRAM-ARGS might be file names. They are not
3950 objects of file handler invocation. File handlers might not
3951 support pty association, if PROGRAM is nil."
3952 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3953 (if fh (apply fh 'start-file-process name buffer program program-args)
3954 (apply 'start-process name buffer program program-args))))
3956 ;;;; Process menu
3958 (defvar tabulated-list-format)
3959 (defvar tabulated-list-entries)
3960 (defvar tabulated-list-sort-key)
3961 (declare-function tabulated-list-init-header "tabulated-list" ())
3962 (declare-function tabulated-list-print "tabulated-list"
3963 (&optional remember-pos update))
3965 (defvar process-menu-query-only nil)
3967 (defvar process-menu-mode-map
3968 (let ((map (make-sparse-keymap)))
3969 (define-key map [?d] 'process-menu-delete-process)
3970 map))
3972 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3973 "Major mode for listing the processes called by Emacs."
3974 (setq tabulated-list-format [("Process" 15 t)
3975 ("PID" 7 t)
3976 ("Status" 7 t)
3977 ;; 25 is the length of the long standard buffer
3978 ;; name "*Async Shell Command*<10>" (bug#30016)
3979 ("Buffer" 25 t)
3980 ("TTY" 12 t)
3981 ("Command" 0 t)])
3982 (make-local-variable 'process-menu-query-only)
3983 (setq tabulated-list-sort-key (cons "Process" nil))
3984 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t))
3986 (defun process-menu-delete-process ()
3987 "Kill process at point in a `list-processes' buffer."
3988 (interactive)
3989 (let ((pos (point)))
3990 (delete-process (tabulated-list-get-id))
3991 (revert-buffer)
3992 (goto-char (min pos (point-max)))
3993 (if (eobp)
3994 (forward-line -1)
3995 (beginning-of-line))))
3997 (defun list-processes--refresh ()
3998 "Recompute the list of processes for the Process List buffer.
3999 Also, delete any process that is exited or signaled."
4000 (setq tabulated-list-entries nil)
4001 (dolist (p (process-list))
4002 (cond ((memq (process-status p) '(exit signal closed))
4003 (delete-process p))
4004 ((or (not process-menu-query-only)
4005 (process-query-on-exit-flag p))
4006 (let* ((buf (process-buffer p))
4007 (type (process-type p))
4008 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
4009 (name (process-name p))
4010 (status (symbol-name (process-status p)))
4011 (buf-label (if (buffer-live-p buf)
4012 `(,(buffer-name buf)
4013 face link
4014 help-echo ,(format-message
4015 "Visit buffer `%s'"
4016 (buffer-name buf))
4017 follow-link t
4018 process-buffer ,buf
4019 action process-menu-visit-buffer)
4020 "--"))
4021 (tty (or (process-tty-name p) "--"))
4022 (cmd
4023 (if (memq type '(network serial))
4024 (let ((contact (process-contact p t)))
4025 (if (eq type 'network)
4026 (format "(%s %s)"
4027 (if (plist-get contact :type)
4028 "datagram"
4029 "network")
4030 (if (plist-get contact :server)
4031 (format "server on %s"
4033 (plist-get contact :host)
4034 (plist-get contact :local)))
4035 (format "connection to %s"
4036 (plist-get contact :host))))
4037 (format "(serial port %s%s)"
4038 (or (plist-get contact :port) "?")
4039 (let ((speed (plist-get contact :speed)))
4040 (if speed
4041 (format " at %s b/s" speed)
4042 "")))))
4043 (mapconcat 'identity (process-command p) " "))))
4044 (push (list p (vector name pid status buf-label tty cmd))
4045 tabulated-list-entries)))))
4046 (tabulated-list-init-header))
4048 (defun process-menu-visit-buffer (button)
4049 (display-buffer (button-get button 'process-buffer)))
4051 (defun list-processes (&optional query-only buffer)
4052 "Display a list of all processes that are Emacs sub-processes.
4053 If optional argument QUERY-ONLY is non-nil, only processes with
4054 the query-on-exit flag set are listed.
4055 Any process listed as exited or signaled is actually eliminated
4056 after the listing is made.
4057 Optional argument BUFFER specifies a buffer to use, instead of
4058 \"*Process List*\".
4059 The return value is always nil.
4061 This function lists only processes that were launched by Emacs. To
4062 see other processes running on the system, use `list-system-processes'."
4063 (interactive)
4064 (or (fboundp 'process-list)
4065 (error "Asynchronous subprocesses are not supported on this system"))
4066 (unless (bufferp buffer)
4067 (setq buffer (get-buffer-create "*Process List*")))
4068 (with-current-buffer buffer
4069 (process-menu-mode)
4070 (setq process-menu-query-only query-only)
4071 (list-processes--refresh)
4072 (tabulated-list-print))
4073 (display-buffer buffer)
4074 nil)
4076 ;;;; Prefix commands
4078 (setq prefix-command--needs-update nil)
4079 (setq prefix-command--last-echo nil)
4081 (defun internal-echo-keystrokes-prefix ()
4082 ;; BEWARE: Called directly from C code.
4083 ;; If the return value is non-nil, it means we are in the middle of
4084 ;; a command with prefix, such as a command invoked with prefix-arg.
4085 (if (not prefix-command--needs-update)
4086 prefix-command--last-echo
4087 (setq prefix-command--last-echo
4088 (let ((strs nil))
4089 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4090 (lambda (fun) (push (funcall fun) strs)))
4091 (setq strs (delq nil strs))
4092 (when strs (mapconcat #'identity strs " "))))))
4094 (defvar prefix-command-echo-keystrokes-functions nil
4095 "Abnormal hook which constructs the description of the current prefix state.
4096 Each function is called with no argument, should return a string or nil.")
4098 (defun prefix-command-update ()
4099 "Update state of prefix commands.
4100 Call it whenever you change the \"prefix command state\"."
4101 (setq prefix-command--needs-update t))
4103 (defvar prefix-command-preserve-state-hook nil
4104 "Normal hook run when a command needs to preserve the prefix.")
4106 (defun prefix-command-preserve-state ()
4107 "Pass the current prefix command state to the next command.
4108 Should be called by all prefix commands.
4109 Runs `prefix-command-preserve-state-hook'."
4110 (run-hooks 'prefix-command-preserve-state-hook)
4111 ;; If the current command is a prefix command, we don't want the next (real)
4112 ;; command to have `last-command' set to, say, `universal-argument'.
4113 (setq this-command last-command)
4114 (setq real-this-command real-last-command)
4115 (prefix-command-update))
4117 (defun reset-this-command-lengths ()
4118 (declare (obsolete prefix-command-preserve-state "25.1"))
4119 nil)
4121 ;;;;; The main prefix command.
4123 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4125 (add-hook 'prefix-command-echo-keystrokes-functions
4126 #'universal-argument--description)
4127 (defun universal-argument--description ()
4128 (when prefix-arg
4129 (concat "C-u"
4130 (pcase prefix-arg
4131 (`(-) " -")
4132 (`(,(and (pred integerp) n))
4133 (let ((str ""))
4134 (while (and (> n 4) (= (mod n 4) 0))
4135 (setq str (concat str " C-u"))
4136 (setq n (/ n 4)))
4137 (if (= n 4) str (format " %s" prefix-arg))))
4138 (_ (format " %s" prefix-arg))))))
4140 (add-hook 'prefix-command-preserve-state-hook
4141 #'universal-argument--preserve)
4142 (defun universal-argument--preserve ()
4143 (setq prefix-arg current-prefix-arg))
4145 (defvar universal-argument-map
4146 (let ((map (make-sparse-keymap))
4147 (universal-argument-minus
4148 ;; For backward compatibility, minus with no modifiers is an ordinary
4149 ;; command if digits have already been entered.
4150 `(menu-item "" negative-argument
4151 :filter ,(lambda (cmd)
4152 (if (integerp prefix-arg) nil cmd)))))
4153 (define-key map [switch-frame]
4154 (lambda (e) (interactive "e")
4155 (handle-switch-frame e) (universal-argument--mode)))
4156 (define-key map [?\C-u] 'universal-argument-more)
4157 (define-key map [?-] universal-argument-minus)
4158 (define-key map [?0] 'digit-argument)
4159 (define-key map [?1] 'digit-argument)
4160 (define-key map [?2] 'digit-argument)
4161 (define-key map [?3] 'digit-argument)
4162 (define-key map [?4] 'digit-argument)
4163 (define-key map [?5] 'digit-argument)
4164 (define-key map [?6] 'digit-argument)
4165 (define-key map [?7] 'digit-argument)
4166 (define-key map [?8] 'digit-argument)
4167 (define-key map [?9] 'digit-argument)
4168 (define-key map [kp-0] 'digit-argument)
4169 (define-key map [kp-1] 'digit-argument)
4170 (define-key map [kp-2] 'digit-argument)
4171 (define-key map [kp-3] 'digit-argument)
4172 (define-key map [kp-4] 'digit-argument)
4173 (define-key map [kp-5] 'digit-argument)
4174 (define-key map [kp-6] 'digit-argument)
4175 (define-key map [kp-7] 'digit-argument)
4176 (define-key map [kp-8] 'digit-argument)
4177 (define-key map [kp-9] 'digit-argument)
4178 (define-key map [kp-subtract] universal-argument-minus)
4179 map)
4180 "Keymap used while processing \\[universal-argument].")
4182 (defun universal-argument--mode ()
4183 (prefix-command-update)
4184 (set-transient-map universal-argument-map nil))
4186 (defun universal-argument ()
4187 "Begin a numeric argument for the following command.
4188 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4189 \\[universal-argument] following the digits or minus sign ends the argument.
4190 \\[universal-argument] without digits or minus sign provides 4 as argument.
4191 Repeating \\[universal-argument] without digits or minus sign
4192 multiplies the argument by 4 each time.
4193 For some commands, just \\[universal-argument] by itself serves as a flag
4194 which is different in effect from any particular numeric argument.
4195 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4196 (interactive)
4197 (prefix-command-preserve-state)
4198 (setq prefix-arg (list 4))
4199 (universal-argument--mode))
4201 (defun universal-argument-more (arg)
4202 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4203 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4204 (interactive "P")
4205 (prefix-command-preserve-state)
4206 (setq prefix-arg (if (consp arg)
4207 (list (* 4 (car arg)))
4208 (if (eq arg '-)
4209 (list -4)
4210 arg)))
4211 (when (consp prefix-arg) (universal-argument--mode)))
4213 (defun negative-argument (arg)
4214 "Begin a negative numeric argument for the next command.
4215 \\[universal-argument] following digits or minus sign ends the argument."
4216 (interactive "P")
4217 (prefix-command-preserve-state)
4218 (setq prefix-arg (cond ((integerp arg) (- arg))
4219 ((eq arg '-) nil)
4220 (t '-)))
4221 (universal-argument--mode))
4223 (defun digit-argument (arg)
4224 "Part of the numeric argument for the next command.
4225 \\[universal-argument] following digits or minus sign ends the argument."
4226 (interactive "P")
4227 (prefix-command-preserve-state)
4228 (let* ((char (if (integerp last-command-event)
4229 last-command-event
4230 (get last-command-event 'ascii-character)))
4231 (digit (- (logand char ?\177) ?0)))
4232 (setq prefix-arg (cond ((integerp arg)
4233 (+ (* arg 10)
4234 (if (< arg 0) (- digit) digit)))
4235 ((eq arg '-)
4236 ;; Treat -0 as just -, so that -01 will work.
4237 (if (zerop digit) '- (- digit)))
4239 digit))))
4240 (universal-argument--mode))
4243 (defvar filter-buffer-substring-functions nil
4244 "This variable is a wrapper hook around `buffer-substring--filter'.
4245 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4246 (make-obsolete-variable 'filter-buffer-substring-functions
4247 'filter-buffer-substring-function "24.4")
4249 (defvar filter-buffer-substring-function #'buffer-substring--filter
4250 "Function to perform the filtering in `filter-buffer-substring'.
4251 The function is called with the same 3 arguments (BEG END DELETE)
4252 that `filter-buffer-substring' received. It should return the
4253 buffer substring between BEG and END, after filtering. If DELETE is
4254 non-nil, it should delete the text between BEG and END from the buffer.")
4256 (defvar buffer-substring-filters nil
4257 "List of filter functions for `buffer-substring--filter'.
4258 Each function must accept a single argument, a string, and return a string.
4259 The buffer substring is passed to the first function in the list,
4260 and the return value of each function is passed to the next.
4261 As a special convention, point is set to the start of the buffer text
4262 being operated on (i.e., the first argument of `buffer-substring--filter')
4263 before these functions are called.")
4264 (make-obsolete-variable 'buffer-substring-filters
4265 'filter-buffer-substring-function "24.1")
4267 (defun filter-buffer-substring (beg end &optional delete)
4268 "Return the buffer substring between BEG and END, after filtering.
4269 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4271 This calls the function that `filter-buffer-substring-function' specifies
4272 \(passing the same three arguments that it received) to do the work,
4273 and returns whatever it does. The default function does no filtering,
4274 unless a hook has been set.
4276 Use `filter-buffer-substring' instead of `buffer-substring',
4277 `buffer-substring-no-properties', or `delete-and-extract-region' when
4278 you want to allow filtering to take place. For example, major or minor
4279 modes can use `filter-buffer-substring-function' to extract characters
4280 that are special to a buffer, and should not be copied into other buffers."
4281 (funcall filter-buffer-substring-function beg end delete))
4283 (defun buffer-substring--filter (beg end &optional delete)
4284 "Default function to use for `filter-buffer-substring-function'.
4285 Its arguments and return value are as specified for `filter-buffer-substring'.
4286 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4287 \(see `with-wrapper-hook' for details about wrapper hooks),
4288 and the abnormal hook `buffer-substring-filters'.
4289 No filtering is done unless a hook says to."
4290 (subr--with-wrapper-hook-no-warnings
4291 filter-buffer-substring-functions (beg end delete)
4292 (cond
4293 ((or delete buffer-substring-filters)
4294 (save-excursion
4295 (goto-char beg)
4296 (let ((string (if delete (delete-and-extract-region beg end)
4297 (buffer-substring beg end))))
4298 (dolist (filter buffer-substring-filters)
4299 (setq string (funcall filter string)))
4300 string)))
4302 (buffer-substring beg end)))))
4305 ;;;; Window system cut and paste hooks.
4307 (defvar interprogram-cut-function #'gui-select-text
4308 "Function to call to make a killed region available to other programs.
4309 Most window systems provide a facility for cutting and pasting
4310 text between different programs, such as the clipboard on X and
4311 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4313 This variable holds a function that Emacs calls whenever text is
4314 put in the kill ring, to make the new kill available to other
4315 programs. The function takes one argument, TEXT, which is a
4316 string containing the text which should be made available.")
4318 (defvar interprogram-paste-function #'gui-selection-value
4319 "Function to call to get text cut from other programs.
4320 Most window systems provide a facility for cutting and pasting
4321 text between different programs, such as the clipboard on X and
4322 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4324 This variable holds a function that Emacs calls to obtain text
4325 that other programs have provided for pasting. The function is
4326 called with no arguments. If no other program has provided text
4327 to paste, the function should return nil (in which case the
4328 caller, usually `current-kill', should use the top of the Emacs
4329 kill ring). If another program has provided text to paste, the
4330 function should return that text as a string (in which case the
4331 caller should put this string in the kill ring as the latest
4332 kill).
4334 The function may also return a list of strings if the window
4335 system supports multiple selections. The first string will be
4336 used as the pasted text, but the other will be placed in the kill
4337 ring for easy access via `yank-pop'.
4339 Note that the function should return a string only if a program
4340 other than Emacs has provided a string for pasting; if Emacs
4341 provided the most recent string, the function should return nil.
4342 If it is difficult to tell whether Emacs or some other program
4343 provided the current string, it is probably good enough to return
4344 nil if the string is equal (according to `string=') to the last
4345 text Emacs provided.")
4349 ;;;; The kill ring data structure.
4351 (defvar kill-ring nil
4352 "List of killed text sequences.
4353 Since the kill ring is supposed to interact nicely with cut-and-paste
4354 facilities offered by window systems, use of this variable should
4355 interact nicely with `interprogram-cut-function' and
4356 `interprogram-paste-function'. The functions `kill-new',
4357 `kill-append', and `current-kill' are supposed to implement this
4358 interaction; you may want to use them instead of manipulating the kill
4359 ring directly.")
4361 (defcustom kill-ring-max 60
4362 "Maximum length of kill ring before oldest elements are thrown away."
4363 :type 'integer
4364 :group 'killing)
4366 (defvar kill-ring-yank-pointer nil
4367 "The tail of the kill ring whose car is the last thing yanked.")
4369 (defcustom save-interprogram-paste-before-kill nil
4370 "Save clipboard strings into kill ring before replacing them.
4371 When one selects something in another program to paste it into Emacs,
4372 but kills something in Emacs before actually pasting it,
4373 this selection is gone unless this variable is non-nil,
4374 in which case the other program's selection is saved in the `kill-ring'
4375 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4376 :type 'boolean
4377 :group 'killing
4378 :version "23.2")
4380 (defcustom kill-do-not-save-duplicates nil
4381 "Do not add a new string to `kill-ring' if it duplicates the last one.
4382 The comparison is done using `equal-including-properties'."
4383 :type 'boolean
4384 :group 'killing
4385 :version "23.2")
4387 (defun kill-new (string &optional replace)
4388 "Make STRING the latest kill in the kill ring.
4389 Set `kill-ring-yank-pointer' to point to it.
4390 If `interprogram-cut-function' is non-nil, apply it to STRING.
4391 Optional second argument REPLACE non-nil means that STRING will replace
4392 the front of the kill ring, rather than being added to the list.
4394 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4395 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4396 STRING.
4398 When the yank handler has a non-nil PARAM element, the original STRING
4399 argument is not used by `insert-for-yank'. However, since Lisp code
4400 may access and use elements from the kill ring directly, the STRING
4401 argument should still be a \"useful\" string for such uses."
4402 (unless (and kill-do-not-save-duplicates
4403 ;; Due to text properties such as 'yank-handler that
4404 ;; can alter the contents to yank, comparison using
4405 ;; `equal' is unsafe.
4406 (equal-including-properties string (car kill-ring)))
4407 (if (fboundp 'menu-bar-update-yank-menu)
4408 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4409 (when save-interprogram-paste-before-kill
4410 (let ((interprogram-paste (and interprogram-paste-function
4411 (funcall interprogram-paste-function))))
4412 (when interprogram-paste
4413 (dolist (s (if (listp interprogram-paste)
4414 (nreverse interprogram-paste)
4415 (list interprogram-paste)))
4416 (unless (and kill-do-not-save-duplicates
4417 (equal-including-properties s (car kill-ring)))
4418 (push s kill-ring))))))
4419 (unless (and kill-do-not-save-duplicates
4420 (equal-including-properties string (car kill-ring)))
4421 (if (and replace kill-ring)
4422 (setcar kill-ring string)
4423 (push string kill-ring)
4424 (if (> (length kill-ring) kill-ring-max)
4425 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4426 (setq kill-ring-yank-pointer kill-ring)
4427 (if interprogram-cut-function
4428 (funcall interprogram-cut-function string)))
4430 ;; It has been argued that this should work similar to `self-insert-command'
4431 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4432 (defcustom kill-append-merge-undo nil
4433 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4434 :type 'boolean
4435 :group 'killing
4436 :version "25.1")
4438 (defun kill-append (string before-p)
4439 "Append STRING to the end of the latest kill in the kill ring.
4440 If BEFORE-P is non-nil, prepend STRING to the kill.
4441 Also removes the last undo boundary in the current buffer,
4442 depending on `kill-append-merge-undo'.
4443 If `interprogram-cut-function' is set, pass the resulting kill to it."
4444 (let* ((cur (car kill-ring)))
4445 (kill-new (if before-p (concat string cur) (concat cur string))
4446 (or (= (length cur) 0)
4447 (equal nil (get-text-property 0 'yank-handler cur))))
4448 (when (and kill-append-merge-undo (not buffer-read-only))
4449 (let ((prev buffer-undo-list)
4450 (next (cdr buffer-undo-list)))
4451 ;; find the next undo boundary
4452 (while (car next)
4453 (pop next)
4454 (pop prev))
4455 ;; remove this undo boundary
4456 (when prev
4457 (setcdr prev (cdr next)))))))
4459 (defcustom yank-pop-change-selection nil
4460 "Whether rotating the kill ring changes the window system selection.
4461 If non-nil, whenever the kill ring is rotated (usually via the
4462 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4463 to copy the new kill to the window system selection."
4464 :type 'boolean
4465 :group 'killing
4466 :version "23.1")
4468 (defun current-kill (n &optional do-not-move)
4469 "Rotate the yanking point by N places, and then return that kill.
4470 If N is zero and `interprogram-paste-function' is set to a
4471 function that returns a string or a list of strings, and if that
4472 function doesn't return nil, then that string (or list) is added
4473 to the front of the kill ring and the string (or first string in
4474 the list) is returned as the latest kill.
4476 If N is not zero, and if `yank-pop-change-selection' is
4477 non-nil, use `interprogram-cut-function' to transfer the
4478 kill at the new yank point into the window system selection.
4480 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4481 move the yanking point; just return the Nth kill forward."
4483 (let ((interprogram-paste (and (= n 0)
4484 interprogram-paste-function
4485 (funcall interprogram-paste-function))))
4486 (if interprogram-paste
4487 (progn
4488 ;; Disable the interprogram cut function when we add the new
4489 ;; text to the kill ring, so Emacs doesn't try to own the
4490 ;; selection, with identical text.
4491 (let ((interprogram-cut-function nil))
4492 (if (listp interprogram-paste)
4493 (mapc 'kill-new (nreverse interprogram-paste))
4494 (kill-new interprogram-paste)))
4495 (car kill-ring))
4496 (or kill-ring (error "Kill ring is empty"))
4497 (let ((ARGth-kill-element
4498 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4499 (length kill-ring))
4500 kill-ring)))
4501 (unless do-not-move
4502 (setq kill-ring-yank-pointer ARGth-kill-element)
4503 (when (and yank-pop-change-selection
4504 (> n 0)
4505 interprogram-cut-function)
4506 (funcall interprogram-cut-function (car ARGth-kill-element))))
4507 (car ARGth-kill-element)))))
4511 ;;;; Commands for manipulating the kill ring.
4513 (defcustom kill-read-only-ok nil
4514 "Non-nil means don't signal an error for killing read-only text."
4515 :type 'boolean
4516 :group 'killing)
4518 (defun kill-region (beg end &optional region)
4519 "Kill (\"cut\") text between point and mark.
4520 This deletes the text from the buffer and saves it in the kill ring.
4521 The command \\[yank] can retrieve it from there.
4522 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4524 If you want to append the killed region to the last killed text,
4525 use \\[append-next-kill] before \\[kill-region].
4527 Any command that calls this function is a \"kill command\".
4528 If the previous command was also a kill command,
4529 the text killed this time appends to the text killed last time
4530 to make one entry in the kill ring.
4532 The killed text is filtered by `filter-buffer-substring' before it is
4533 saved in the kill ring, so the actual saved text might be different
4534 from what was killed.
4536 If the buffer is read-only, Emacs will beep and refrain from deleting
4537 the text, but put the text in the kill ring anyway. This means that
4538 you can use the killing commands to copy text from a read-only buffer.
4540 Lisp programs should use this function for killing text.
4541 (To delete text, use `delete-region'.)
4542 Supply two arguments, character positions BEG and END indicating the
4543 stretch of text to be killed. If the optional argument REGION is
4544 non-nil, the function ignores BEG and END, and kills the current
4545 region instead."
4546 ;; Pass mark first, then point, because the order matters when
4547 ;; calling `kill-append'.
4548 (interactive (list (mark) (point) 'region))
4549 (unless (and beg end)
4550 (user-error "The mark is not set now, so there is no region"))
4551 (condition-case nil
4552 (let ((string (if region
4553 (funcall region-extract-function 'delete)
4554 (filter-buffer-substring beg end 'delete))))
4555 (when string ;STRING is nil if BEG = END
4556 ;; Add that string to the kill ring, one way or another.
4557 (if (eq last-command 'kill-region)
4558 (kill-append string (< end beg))
4559 (kill-new string)))
4560 (when (or string (eq last-command 'kill-region))
4561 (setq this-command 'kill-region))
4562 (setq deactivate-mark t)
4563 nil)
4564 ((buffer-read-only text-read-only)
4565 ;; The code above failed because the buffer, or some of the characters
4566 ;; in the region, are read-only.
4567 ;; We should beep, in case the user just isn't aware of this.
4568 ;; However, there's no harm in putting
4569 ;; the region's text in the kill ring, anyway.
4570 (copy-region-as-kill beg end region)
4571 ;; Set this-command now, so it will be set even if we get an error.
4572 (setq this-command 'kill-region)
4573 ;; This should barf, if appropriate, and give us the correct error.
4574 (if kill-read-only-ok
4575 (progn (message "Read only text copied to kill ring") nil)
4576 ;; Signal an error if the buffer is read-only.
4577 (barf-if-buffer-read-only)
4578 ;; If the buffer isn't read-only, the text is.
4579 (signal 'text-read-only (list (current-buffer)))))))
4581 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4582 ;; to get two copies of the text when the user accidentally types M-w and
4583 ;; then corrects it with the intended C-w.
4584 (defun copy-region-as-kill (beg end &optional region)
4585 "Save the region as if killed, but don't kill it.
4586 In Transient Mark mode, deactivate the mark.
4587 If `interprogram-cut-function' is non-nil, also save the text for a window
4588 system cut and paste.
4590 The copied text is filtered by `filter-buffer-substring' before it is
4591 saved in the kill ring, so the actual saved text might be different
4592 from what was in the buffer.
4594 When called from Lisp, save in the kill ring the stretch of text
4595 between BEG and END, unless the optional argument REGION is
4596 non-nil, in which case ignore BEG and END, and save the current
4597 region instead.
4599 This command's old key binding has been given to `kill-ring-save'."
4600 ;; Pass mark first, then point, because the order matters when
4601 ;; calling `kill-append'.
4602 (interactive (list (mark) (point)
4603 (prefix-numeric-value current-prefix-arg)))
4604 (let ((str (if region
4605 (funcall region-extract-function nil)
4606 (filter-buffer-substring beg end))))
4607 (if (eq last-command 'kill-region)
4608 (kill-append str (< end beg))
4609 (kill-new str)))
4610 (setq deactivate-mark t)
4611 nil)
4613 (defun kill-ring-save (beg end &optional region)
4614 "Save the region as if killed, but don't kill it.
4615 In Transient Mark mode, deactivate the mark.
4616 If `interprogram-cut-function' is non-nil, also save the text for a window
4617 system cut and paste.
4619 If you want to append the killed line to the last killed text,
4620 use \\[append-next-kill] before \\[kill-ring-save].
4622 The copied text is filtered by `filter-buffer-substring' before it is
4623 saved in the kill ring, so the actual saved text might be different
4624 from what was in the buffer.
4626 When called from Lisp, save in the kill ring the stretch of text
4627 between BEG and END, unless the optional argument REGION is
4628 non-nil, in which case ignore BEG and END, and save the current
4629 region instead.
4631 This command is similar to `copy-region-as-kill', except that it gives
4632 visual feedback indicating the extent of the region being copied."
4633 ;; Pass mark first, then point, because the order matters when
4634 ;; calling `kill-append'.
4635 (interactive (list (mark) (point)
4636 (prefix-numeric-value current-prefix-arg)))
4637 (copy-region-as-kill beg end region)
4638 ;; This use of called-interactively-p is correct because the code it
4639 ;; controls just gives the user visual feedback.
4640 (if (called-interactively-p 'interactive)
4641 (indicate-copied-region)))
4643 (defun indicate-copied-region (&optional message-len)
4644 "Indicate that the region text has been copied interactively.
4645 If the mark is visible in the selected window, blink the cursor
4646 between point and mark if there is currently no active region
4647 highlighting.
4649 If the mark lies outside the selected window, display an
4650 informative message containing a sample of the copied text. The
4651 optional argument MESSAGE-LEN, if non-nil, specifies the length
4652 of this sample text; it defaults to 40."
4653 (let ((mark (mark t))
4654 (point (point))
4655 ;; Inhibit quitting so we can make a quit here
4656 ;; look like a C-g typed as a command.
4657 (inhibit-quit t))
4658 (if (pos-visible-in-window-p mark (selected-window))
4659 ;; Swap point-and-mark quickly so as to show the region that
4660 ;; was selected. Don't do it if the region is highlighted.
4661 (unless (and (region-active-p)
4662 (face-background 'region))
4663 ;; Swap point and mark.
4664 (set-marker (mark-marker) (point) (current-buffer))
4665 (goto-char mark)
4666 (sit-for blink-matching-delay)
4667 ;; Swap back.
4668 (set-marker (mark-marker) mark (current-buffer))
4669 (goto-char point)
4670 ;; If user quit, deactivate the mark
4671 ;; as C-g would as a command.
4672 (and quit-flag (region-active-p)
4673 (deactivate-mark)))
4674 (let ((len (min (abs (- mark point))
4675 (or message-len 40))))
4676 (if (< point mark)
4677 ;; Don't say "killed"; that is misleading.
4678 (message "Saved text until \"%s\""
4679 (buffer-substring-no-properties (- mark len) mark))
4680 (message "Saved text from \"%s\""
4681 (buffer-substring-no-properties mark (+ mark len))))))))
4683 (defun append-next-kill (&optional interactive)
4684 "Cause following command, if it kills, to add to previous kill.
4685 If the next command kills forward from point, the kill is
4686 appended to the previous killed text. If the command kills
4687 backward, the kill is prepended. Kill commands that act on the
4688 region, such as `kill-region', are regarded as killing forward if
4689 point is after mark, and killing backward if point is before
4690 mark.
4692 If the next command is not a kill command, `append-next-kill' has
4693 no effect.
4695 The argument is used for internal purposes; do not supply one."
4696 (interactive "p")
4697 ;; We don't use (interactive-p), since that breaks kbd macros.
4698 (if interactive
4699 (progn
4700 (setq this-command 'kill-region)
4701 (message "If the next command is a kill, it will append"))
4702 (setq last-command 'kill-region)))
4704 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4705 "Character set that matches bidirectional formatting control characters.")
4707 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4708 "Character set that matches any character except bidirectional controls.")
4710 (defun squeeze-bidi-context-1 (from to category replacement)
4711 "A subroutine of `squeeze-bidi-context'.
4712 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4713 (let ((pt (copy-marker from))
4714 (limit (copy-marker to))
4715 (old-pt 0)
4716 lim1)
4717 (setq lim1 limit)
4718 (goto-char pt)
4719 (while (< pt limit)
4720 (if (> pt old-pt)
4721 (move-marker lim1
4722 (save-excursion
4723 ;; L and R categories include embedding and
4724 ;; override controls, but we don't want to
4725 ;; replace them, because that might change
4726 ;; the visual order. Likewise with PDF and
4727 ;; isolate controls.
4728 (+ pt (skip-chars-forward
4729 bidi-directional-non-controls-chars
4730 limit)))))
4731 ;; Replace any run of non-RTL characters by a single LRM.
4732 (if (null (re-search-forward category lim1 t))
4733 ;; No more characters of CATEGORY, we are done.
4734 (setq pt limit)
4735 (replace-match replacement nil t)
4736 (move-marker pt (point)))
4737 (setq old-pt pt)
4738 ;; Skip directional controls, if any.
4739 (move-marker
4740 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4742 (defun squeeze-bidi-context (from to)
4743 "Replace characters between FROM and TO while keeping bidi context.
4745 This function replaces the region of text with as few characters
4746 as possible, while preserving the effect that region will have on
4747 bidirectional display before and after the region."
4748 (let ((start (set-marker (make-marker)
4749 (if (> from 0) from (+ (point-max) from))))
4750 (end (set-marker (make-marker) to))
4751 ;; This is for when they copy text with read-only text
4752 ;; properties.
4753 (inhibit-read-only t))
4754 (if (null (marker-position end))
4755 (setq end (point-max-marker)))
4756 ;; Replace each run of non-RTL characters with a single LRM.
4757 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4758 ;; Replace each run of non-LTR characters with a single RLM. Note
4759 ;; that the \cR category includes both the Arabic Letter (AL) and
4760 ;; R characters; here we ignore the distinction between them,
4761 ;; because that distinction only affects Arabic Number (AN)
4762 ;; characters, which are weak and don't affect the reordering.
4763 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4765 (defun line-substring-with-bidi-context (start end &optional no-properties)
4766 "Return buffer text between START and END with its bidi context.
4768 START and END are assumed to belong to the same physical line
4769 of buffer text. This function prepends and appends to the text
4770 between START and END bidi control characters that preserve the
4771 visual order of that text when it is inserted at some other place."
4772 (if (or (< start (point-min))
4773 (> end (point-max)))
4774 (signal 'args-out-of-range (list (current-buffer) start end)))
4775 (let ((buf (current-buffer))
4776 substr para-dir from to)
4777 (save-excursion
4778 (goto-char start)
4779 (setq para-dir (current-bidi-paragraph-direction))
4780 (setq from (line-beginning-position)
4781 to (line-end-position))
4782 (goto-char from)
4783 ;; If we don't have any mixed directional characters in the
4784 ;; entire line, we can just copy the substring without adding
4785 ;; any context.
4786 (if (or (looking-at-p "\\CR*$")
4787 (looking-at-p "\\CL*$"))
4788 (setq substr (if no-properties
4789 (buffer-substring-no-properties start end)
4790 (buffer-substring start end)))
4791 (setq substr
4792 (with-temp-buffer
4793 (if no-properties
4794 (insert-buffer-substring-no-properties buf from to)
4795 (insert-buffer-substring buf from to))
4796 (squeeze-bidi-context 1 (1+ (- start from)))
4797 (squeeze-bidi-context (- end to) nil)
4798 (buffer-substring 1 (point-max)))))
4800 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4801 ;; (1) force the string to have the same base embedding
4802 ;; direction as the paragraph direction at the source, no matter
4803 ;; what is the paragraph direction at destination; and (2) avoid
4804 ;; affecting the visual order of the surrounding text at
4805 ;; destination if there are characters of different
4806 ;; directionality there.
4807 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4808 substr "\x2069"))))
4810 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4811 "Return portion of current buffer between START and END with bidi context.
4813 This function works similar to `buffer-substring', but it prepends and
4814 appends to the text bidi directional control characters necessary to
4815 preserve the visual appearance of the text if it is inserted at another
4816 place. This is useful when the buffer substring includes bidirectional
4817 text and control characters that cause non-trivial reordering on display.
4818 If copied verbatim, such text can have a very different visual appearance,
4819 and can also change the visual appearance of the surrounding text at the
4820 destination of the copy.
4822 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4823 the text properties."
4824 (let (line-end substr)
4825 (if (or (< start (point-min))
4826 (> end (point-max)))
4827 (signal 'args-out-of-range (list (current-buffer) start end)))
4828 (save-excursion
4829 (goto-char start)
4830 (setq line-end (min end (line-end-position)))
4831 (while (< start end)
4832 (setq substr
4833 (concat substr
4834 (if substr "\n" "")
4835 (line-substring-with-bidi-context start line-end
4836 no-properties)))
4837 (forward-line 1)
4838 (setq start (point))
4839 (setq line-end (min end (line-end-position))))
4840 substr)))
4842 ;; Yanking.
4844 (defcustom yank-handled-properties
4845 '((font-lock-face . yank-handle-font-lock-face-property)
4846 (category . yank-handle-category-property))
4847 "List of special text property handling conditions for yanking.
4848 Each element should have the form (PROP . FUN), where PROP is a
4849 property symbol and FUN is a function. When the `yank' command
4850 inserts text into the buffer, it scans the inserted text for
4851 stretches of text that have `eq' values of the text property
4852 PROP; for each such stretch of text, FUN is called with three
4853 arguments: the property's value in that text, and the start and
4854 end positions of the text.
4856 This is done prior to removing the properties specified by
4857 `yank-excluded-properties'."
4858 :group 'killing
4859 :type '(repeat (cons (symbol :tag "property symbol")
4860 function))
4861 :version "24.3")
4863 ;; This is actually used in subr.el but defcustom does not work there.
4864 (defcustom yank-excluded-properties
4865 '(category field follow-link fontified font-lock-face help-echo
4866 intangible invisible keymap local-map mouse-face read-only
4867 yank-handler)
4868 "Text properties to discard when yanking.
4869 The value should be a list of text properties to discard or t,
4870 which means to discard all text properties.
4872 See also `yank-handled-properties'."
4873 :type '(choice (const :tag "All" t) (repeat symbol))
4874 :group 'killing
4875 :version "24.3")
4877 (defvar yank-window-start nil)
4878 (defvar yank-undo-function nil
4879 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4880 Function is called with two parameters, START and END corresponding to
4881 the value of the mark and point; it is guaranteed that START <= END.
4882 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4884 (defun yank-pop (&optional arg)
4885 "Replace just-yanked stretch of killed text with a different stretch.
4886 This command is allowed only immediately after a `yank' or a `yank-pop'.
4887 At such a time, the region contains a stretch of reinserted
4888 previously-killed text. `yank-pop' deletes that text and inserts in its
4889 place a different stretch of killed text.
4891 With no argument, the previous kill is inserted.
4892 With argument N, insert the Nth previous kill.
4893 If N is negative, this is a more recent kill.
4895 The sequence of kills wraps around, so that after the oldest one
4896 comes the newest one.
4898 This command honors the `yank-handled-properties' and
4899 `yank-excluded-properties' variables, and the `yank-handler' text
4900 property, in the way that `yank' does."
4901 (interactive "*p")
4902 (if (not (eq last-command 'yank))
4903 (user-error "Previous command was not a yank"))
4904 (setq this-command 'yank)
4905 (unless arg (setq arg 1))
4906 (let ((inhibit-read-only t)
4907 (before (< (point) (mark t))))
4908 (if before
4909 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4910 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4911 (setq yank-undo-function nil)
4912 (set-marker (mark-marker) (point) (current-buffer))
4913 (insert-for-yank (current-kill arg))
4914 ;; Set the window start back where it was in the yank command,
4915 ;; if possible.
4916 (set-window-start (selected-window) yank-window-start t)
4917 (if before
4918 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4919 ;; It is cleaner to avoid activation, even though the command
4920 ;; loop would deactivate the mark because we inserted text.
4921 (goto-char (prog1 (mark t)
4922 (set-marker (mark-marker) (point) (current-buffer))))))
4923 nil)
4925 (defun yank (&optional arg)
4926 "Reinsert (\"paste\") the last stretch of killed text.
4927 More precisely, reinsert the most recent kill, which is the
4928 stretch of killed text most recently killed OR yanked. Put point
4929 at the end, and set mark at the beginning without activating it.
4930 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4931 With argument N, reinsert the Nth most recent kill.
4933 This command honors the `yank-handled-properties' and
4934 `yank-excluded-properties' variables, and the `yank-handler' text
4935 property, as described below.
4937 Properties listed in `yank-handled-properties' are processed,
4938 then those listed in `yank-excluded-properties' are discarded.
4940 If STRING has a non-nil `yank-handler' property anywhere, the
4941 normal insert behavior is altered, and instead, for each contiguous
4942 segment of STRING that has a given value of the `yank-handler'
4943 property, that value is used as follows:
4945 The value of a `yank-handler' property must be a list of one to four
4946 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4947 FUNCTION, if non-nil, should be a function of one argument (the
4948 object to insert); FUNCTION is called instead of `insert'.
4949 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4950 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4951 PARAM may be a list of strings to insert as a rectangle). If PARAM
4952 is nil, then the current segment of STRING is used.
4953 If NOEXCLUDE is present and non-nil, the normal removal of
4954 `yank-excluded-properties' is not performed; instead FUNCTION is
4955 responsible for the removal. This may be necessary if FUNCTION
4956 adjusts point before or after inserting the object.
4957 UNDO, if present and non-nil, should be a function to be called
4958 by `yank-pop' to undo the insertion of the current PARAM. It is
4959 given two arguments, the start and end of the region. FUNCTION
4960 may set `yank-undo-function' to override UNDO.
4962 See also the command `yank-pop' (\\[yank-pop])."
4963 (interactive "*P")
4964 (setq yank-window-start (window-start))
4965 ;; If we don't get all the way thru, make last-command indicate that
4966 ;; for the following command.
4967 (setq this-command t)
4968 (push-mark)
4969 (insert-for-yank (current-kill (cond
4970 ((listp arg) 0)
4971 ((eq arg '-) -2)
4972 (t (1- arg)))))
4973 (if (consp arg)
4974 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4975 ;; It is cleaner to avoid activation, even though the command
4976 ;; loop would deactivate the mark because we inserted text.
4977 (goto-char (prog1 (mark t)
4978 (set-marker (mark-marker) (point) (current-buffer)))))
4979 ;; If we do get all the way thru, make this-command indicate that.
4980 (if (eq this-command t)
4981 (setq this-command 'yank))
4982 nil)
4984 (defun rotate-yank-pointer (arg)
4985 "Rotate the yanking point in the kill ring.
4986 With ARG, rotate that many kills forward (or backward, if negative)."
4987 (interactive "p")
4988 (current-kill arg))
4990 ;; Some kill commands.
4992 ;; Internal subroutine of delete-char
4993 (defun kill-forward-chars (arg)
4994 (if (listp arg) (setq arg (car arg)))
4995 (if (eq arg '-) (setq arg -1))
4996 (kill-region (point) (+ (point) arg)))
4998 ;; Internal subroutine of backward-delete-char
4999 (defun kill-backward-chars (arg)
5000 (if (listp arg) (setq arg (car arg)))
5001 (if (eq arg '-) (setq arg -1))
5002 (kill-region (point) (- (point) arg)))
5004 (defcustom backward-delete-char-untabify-method 'untabify
5005 "The method for untabifying when deleting backward.
5006 Can be `untabify' -- turn a tab to many spaces, then delete one space;
5007 `hungry' -- delete all whitespace, both tabs and spaces;
5008 `all' -- delete all whitespace, including tabs, spaces and newlines;
5009 nil -- just delete one character."
5010 :type '(choice (const untabify) (const hungry) (const all) (const nil))
5011 :version "20.3"
5012 :group 'killing)
5014 (defun backward-delete-char-untabify (arg &optional killp)
5015 "Delete characters backward, changing tabs into spaces.
5016 The exact behavior depends on `backward-delete-char-untabify-method'.
5017 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
5018 Interactively, ARG is the prefix arg (default 1)
5019 and KILLP is t if a prefix arg was specified."
5020 (interactive "*p\nP")
5021 (when (eq backward-delete-char-untabify-method 'untabify)
5022 (let ((count arg))
5023 (save-excursion
5024 (while (and (> count 0) (not (bobp)))
5025 (if (= (preceding-char) ?\t)
5026 (let ((col (current-column)))
5027 (forward-char -1)
5028 (setq col (- col (current-column)))
5029 (insert-char ?\s col)
5030 (delete-char 1)))
5031 (forward-char -1)
5032 (setq count (1- count))))))
5033 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
5034 ((eq backward-delete-char-untabify-method 'all)
5035 " \t\n\r")))
5036 (n (if skip
5037 (let* ((oldpt (point))
5038 (wh (- oldpt (save-excursion
5039 (skip-chars-backward skip)
5040 (constrain-to-field nil oldpt)))))
5041 (+ arg (if (zerop wh) 0 (1- wh))))
5042 arg)))
5043 ;; Avoid warning about delete-backward-char
5044 (with-no-warnings (delete-backward-char n killp))))
5046 (defun zap-to-char (arg char)
5047 "Kill up to and including ARGth occurrence of CHAR.
5048 Case is ignored if `case-fold-search' is non-nil in the current buffer.
5049 Goes backward if ARG is negative; error if CHAR not found."
5050 (interactive (list (prefix-numeric-value current-prefix-arg)
5051 (read-char "Zap to char: " t)))
5052 ;; Avoid "obsolete" warnings for translation-table-for-input.
5053 (with-no-warnings
5054 (if (char-table-p translation-table-for-input)
5055 (setq char (or (aref translation-table-for-input char) char))))
5056 (kill-region (point) (progn
5057 (search-forward (char-to-string char) nil nil arg)
5058 (point))))
5060 ;; kill-line and its subroutines.
5062 (defcustom kill-whole-line nil
5063 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
5064 :type 'boolean
5065 :group 'killing)
5067 (defun kill-line (&optional arg)
5068 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5069 With prefix argument ARG, kill that many lines from point.
5070 Negative arguments kill lines backward.
5071 With zero argument, kills the text before point on the current line.
5073 When calling from a program, nil means \"no arg\",
5074 a number counts as a prefix arg.
5076 To kill a whole line, when point is not at the beginning, type \
5077 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5079 If `show-trailing-whitespace' is non-nil, this command will just
5080 kill the rest of the current line, even if there are no nonblanks
5081 there.
5083 If option `kill-whole-line' is non-nil, then this command kills the whole line
5084 including its terminating newline, when used at the beginning of a line
5085 with no argument. As a consequence, you can always kill a whole line
5086 by typing \\[move-beginning-of-line] \\[kill-line].
5088 If you want to append the killed line to the last killed text,
5089 use \\[append-next-kill] before \\[kill-line].
5091 If the buffer is read-only, Emacs will beep and refrain from deleting
5092 the line, but put the line in the kill ring anyway. This means that
5093 you can use this command to copy text from a read-only buffer.
5094 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5095 even beep.)"
5096 (interactive "P")
5097 (kill-region (point)
5098 ;; It is better to move point to the other end of the kill
5099 ;; before killing. That way, in a read-only buffer, point
5100 ;; moves across the text that is copied to the kill ring.
5101 ;; The choice has no effect on undo now that undo records
5102 ;; the value of point from before the command was run.
5103 (progn
5104 (if arg
5105 (forward-visible-line (prefix-numeric-value arg))
5106 (if (eobp)
5107 (signal 'end-of-buffer nil))
5108 (let ((end
5109 (save-excursion
5110 (end-of-visible-line) (point))))
5111 (if (or (save-excursion
5112 ;; If trailing whitespace is visible,
5113 ;; don't treat it as nothing.
5114 (unless show-trailing-whitespace
5115 (skip-chars-forward " \t" end))
5116 (= (point) end))
5117 (and kill-whole-line (bolp)))
5118 (forward-visible-line 1)
5119 (goto-char end))))
5120 (point))))
5122 (defun kill-whole-line (&optional arg)
5123 "Kill current line.
5124 With prefix ARG, kill that many lines starting from the current line.
5125 If ARG is negative, kill backward. Also kill the preceding newline.
5126 \(This is meant to make \\[repeat] work well with negative arguments.)
5127 If ARG is zero, kill current line but exclude the trailing newline."
5128 (interactive "p")
5129 (or arg (setq arg 1))
5130 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5131 (signal 'end-of-buffer nil))
5132 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5133 (signal 'beginning-of-buffer nil))
5134 (unless (eq last-command 'kill-region)
5135 (kill-new "")
5136 (setq last-command 'kill-region))
5137 (cond ((zerop arg)
5138 ;; We need to kill in two steps, because the previous command
5139 ;; could have been a kill command, in which case the text
5140 ;; before point needs to be prepended to the current kill
5141 ;; ring entry and the text after point appended. Also, we
5142 ;; need to use save-excursion to avoid copying the same text
5143 ;; twice to the kill ring in read-only buffers.
5144 (save-excursion
5145 (kill-region (point) (progn (forward-visible-line 0) (point))))
5146 (kill-region (point) (progn (end-of-visible-line) (point))))
5147 ((< arg 0)
5148 (save-excursion
5149 (kill-region (point) (progn (end-of-visible-line) (point))))
5150 (kill-region (point)
5151 (progn (forward-visible-line (1+ arg))
5152 (unless (bobp) (backward-char))
5153 (point))))
5155 (save-excursion
5156 (kill-region (point) (progn (forward-visible-line 0) (point))))
5157 (kill-region (point)
5158 (progn (forward-visible-line arg) (point))))))
5160 (defun forward-visible-line (arg)
5161 "Move forward by ARG lines, ignoring currently invisible newlines only.
5162 If ARG is negative, move backward -ARG lines.
5163 If ARG is zero, move to the beginning of the current line."
5164 (condition-case nil
5165 (if (> arg 0)
5166 (progn
5167 (while (> arg 0)
5168 (or (zerop (forward-line 1))
5169 (signal 'end-of-buffer nil))
5170 ;; If the newline we just skipped is invisible,
5171 ;; don't count it.
5172 (let ((prop
5173 (get-char-property (1- (point)) 'invisible)))
5174 (if (if (eq buffer-invisibility-spec t)
5175 prop
5176 (or (memq prop buffer-invisibility-spec)
5177 (assq prop buffer-invisibility-spec)))
5178 (setq arg (1+ arg))))
5179 (setq arg (1- arg)))
5180 ;; If invisible text follows, and it is a number of complete lines,
5181 ;; skip it.
5182 (let ((opoint (point)))
5183 (while (and (not (eobp))
5184 (let ((prop
5185 (get-char-property (point) 'invisible)))
5186 (if (eq buffer-invisibility-spec t)
5187 prop
5188 (or (memq prop buffer-invisibility-spec)
5189 (assq prop buffer-invisibility-spec)))))
5190 (goto-char
5191 (if (get-text-property (point) 'invisible)
5192 (or (next-single-property-change (point) 'invisible)
5193 (point-max))
5194 (next-overlay-change (point)))))
5195 (unless (bolp)
5196 (goto-char opoint))))
5197 (let ((first t))
5198 (while (or first (<= arg 0))
5199 (if first
5200 (beginning-of-line)
5201 (or (zerop (forward-line -1))
5202 (signal 'beginning-of-buffer nil)))
5203 ;; If the newline we just moved to is invisible,
5204 ;; don't count it.
5205 (unless (bobp)
5206 (let ((prop
5207 (get-char-property (1- (point)) 'invisible)))
5208 (unless (if (eq buffer-invisibility-spec t)
5209 prop
5210 (or (memq prop buffer-invisibility-spec)
5211 (assq prop buffer-invisibility-spec)))
5212 (setq arg (1+ arg)))))
5213 (setq first nil))
5214 ;; If invisible text follows, and it is a number of complete lines,
5215 ;; skip it.
5216 (let ((opoint (point)))
5217 (while (and (not (bobp))
5218 (let ((prop
5219 (get-char-property (1- (point)) 'invisible)))
5220 (if (eq buffer-invisibility-spec t)
5221 prop
5222 (or (memq prop buffer-invisibility-spec)
5223 (assq prop buffer-invisibility-spec)))))
5224 (goto-char
5225 (if (get-text-property (1- (point)) 'invisible)
5226 (or (previous-single-property-change (point) 'invisible)
5227 (point-min))
5228 (previous-overlay-change (point)))))
5229 (unless (bolp)
5230 (goto-char opoint)))))
5231 ((beginning-of-buffer end-of-buffer)
5232 nil)))
5234 (defun end-of-visible-line ()
5235 "Move to end of current visible line."
5236 (end-of-line)
5237 ;; If the following character is currently invisible,
5238 ;; skip all characters with that same `invisible' property value,
5239 ;; then find the next newline.
5240 (while (and (not (eobp))
5241 (save-excursion
5242 (skip-chars-forward "^\n")
5243 (let ((prop
5244 (get-char-property (point) 'invisible)))
5245 (if (eq buffer-invisibility-spec t)
5246 prop
5247 (or (memq prop buffer-invisibility-spec)
5248 (assq prop buffer-invisibility-spec))))))
5249 (skip-chars-forward "^\n")
5250 (if (get-text-property (point) 'invisible)
5251 (goto-char (or (next-single-property-change (point) 'invisible)
5252 (point-max)))
5253 (goto-char (next-overlay-change (point))))
5254 (end-of-line)))
5256 (defun kill-current-buffer ()
5257 "Kill the current buffer.
5258 When called in the minibuffer, get out of the minibuffer
5259 using `abort-recursive-edit'.
5261 This is like `kill-this-buffer', but it doesn't have to be invoked
5262 via the menu bar, and pays no attention to the menu-bar's frame."
5263 (interactive)
5264 (let ((frame (selected-frame)))
5265 (if (and (frame-live-p frame)
5266 (not (window-minibuffer-p (frame-selected-window frame))))
5267 (kill-buffer (current-buffer))
5268 (abort-recursive-edit))))
5271 (defun insert-buffer (buffer)
5272 "Insert after point the contents of BUFFER.
5273 Puts mark after the inserted text.
5274 BUFFER may be a buffer or a buffer name."
5275 (declare (interactive-only insert-buffer-substring))
5276 (interactive
5277 (list
5278 (progn
5279 (barf-if-buffer-read-only)
5280 (read-buffer "Insert buffer: "
5281 (if (eq (selected-window) (next-window))
5282 (other-buffer (current-buffer))
5283 (window-buffer (next-window)))
5284 t))))
5285 (push-mark
5286 (save-excursion
5287 (insert-buffer-substring (get-buffer buffer))
5288 (point)))
5289 nil)
5291 (defun append-to-buffer (buffer start end)
5292 "Append to specified buffer the text of the region.
5293 It is inserted into that buffer before its point.
5295 When calling from a program, give three arguments:
5296 BUFFER (or buffer name), START and END.
5297 START and END specify the portion of the current buffer to be copied."
5298 (interactive
5299 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5300 (region-beginning) (region-end)))
5301 (let* ((oldbuf (current-buffer))
5302 (append-to (get-buffer-create buffer))
5303 (windows (get-buffer-window-list append-to t t))
5304 point)
5305 (save-excursion
5306 (with-current-buffer append-to
5307 (setq point (point))
5308 (barf-if-buffer-read-only)
5309 (insert-buffer-substring oldbuf start end)
5310 (dolist (window windows)
5311 (when (= (window-point window) point)
5312 (set-window-point window (point))))))))
5314 (defun prepend-to-buffer (buffer start end)
5315 "Prepend to specified buffer the text of the region.
5316 It is inserted into that buffer after its point.
5318 When calling from a program, give three arguments:
5319 BUFFER (or buffer name), START and END.
5320 START and END specify the portion of the current buffer to be copied."
5321 (interactive "BPrepend to buffer: \nr")
5322 (let ((oldbuf (current-buffer)))
5323 (with-current-buffer (get-buffer-create buffer)
5324 (barf-if-buffer-read-only)
5325 (save-excursion
5326 (insert-buffer-substring oldbuf start end)))))
5328 (defun copy-to-buffer (buffer start end)
5329 "Copy to specified buffer the text of the region.
5330 It is inserted into that buffer, replacing existing text there.
5332 When calling from a program, give three arguments:
5333 BUFFER (or buffer name), START and END.
5334 START and END specify the portion of the current buffer to be copied."
5335 (interactive "BCopy to buffer: \nr")
5336 (let ((oldbuf (current-buffer)))
5337 (with-current-buffer (get-buffer-create buffer)
5338 (barf-if-buffer-read-only)
5339 (erase-buffer)
5340 (save-excursion
5341 (insert-buffer-substring oldbuf start end)))))
5343 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5345 (defvar activate-mark-hook nil
5346 "Hook run when the mark becomes active.
5347 It is also run at the end of a command, if the mark is active and
5348 it is possible that the region may have changed.")
5350 (defvar deactivate-mark-hook nil
5351 "Hook run when the mark becomes inactive.")
5353 (defun mark (&optional force)
5354 "Return this buffer's mark value as integer, or nil if never set.
5356 In Transient Mark mode, this function signals an error if
5357 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5358 or the argument FORCE is non-nil, it disregards whether the mark
5359 is active, and returns an integer or nil in the usual way.
5361 If you are using this in an editing command, you are most likely making
5362 a mistake; see the documentation of `set-mark'."
5363 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5364 (marker-position (mark-marker))
5365 (signal 'mark-inactive nil)))
5367 ;; Behind display-selections-p.
5369 (defun deactivate-mark (&optional force)
5370 "Deactivate the mark.
5371 If Transient Mark mode is disabled, this function normally does
5372 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5374 Deactivating the mark sets `mark-active' to nil, updates the
5375 primary selection according to `select-active-regions', and runs
5376 `deactivate-mark-hook'.
5378 If Transient Mark mode was temporarily enabled, reset the value
5379 of the variable `transient-mark-mode'; if this causes Transient
5380 Mark mode to be disabled, don't change `mark-active' to nil or
5381 run `deactivate-mark-hook'."
5382 (when (or (region-active-p) force)
5383 (when (and (if (eq select-active-regions 'only)
5384 (eq (car-safe transient-mark-mode) 'only)
5385 select-active-regions)
5386 (region-active-p)
5387 (display-selections-p))
5388 ;; The var `saved-region-selection', if non-nil, is the text in
5389 ;; the region prior to the last command modifying the buffer.
5390 ;; Set the selection to that, or to the current region.
5391 (cond (saved-region-selection
5392 (if (gui-backend-selection-owner-p 'PRIMARY)
5393 (gui-set-selection 'PRIMARY saved-region-selection))
5394 (setq saved-region-selection nil))
5395 ;; If another program has acquired the selection, region
5396 ;; deactivation should not clobber it (Bug#11772).
5397 ((and (/= (region-beginning) (region-end))
5398 (or (gui-backend-selection-owner-p 'PRIMARY)
5399 (null (gui-backend-selection-exists-p 'PRIMARY))))
5400 (gui-set-selection 'PRIMARY
5401 (funcall region-extract-function nil)))))
5402 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5403 (cond
5404 ((eq (car-safe transient-mark-mode) 'only)
5405 (setq transient-mark-mode (cdr transient-mark-mode))
5406 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5407 (kill-local-variable 'transient-mark-mode)))
5408 ((eq transient-mark-mode 'lambda)
5409 (kill-local-variable 'transient-mark-mode)))
5410 (setq mark-active nil)
5411 (run-hooks 'deactivate-mark-hook)
5412 (redisplay--update-region-highlight (selected-window))))
5414 (defun activate-mark (&optional no-tmm)
5415 "Activate the mark.
5416 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5417 (when (mark t)
5418 (unless (region-active-p)
5419 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5420 (setq mark-active t)
5421 (unless (or transient-mark-mode no-tmm)
5422 (setq-local transient-mark-mode 'lambda))
5423 (run-hooks 'activate-mark-hook))))
5425 (defun set-mark (pos)
5426 "Set this buffer's mark to POS. Don't use this function!
5427 That is to say, don't use this function unless you want
5428 the user to see that the mark has moved, and you want the previous
5429 mark position to be lost.
5431 Normally, when a new mark is set, the old one should go on the stack.
5432 This is why most applications should use `push-mark', not `set-mark'.
5434 Novice Emacs Lisp programmers often try to use the mark for the wrong
5435 purposes. The mark saves a location for the user's convenience.
5436 Most editing commands should not alter the mark.
5437 To remember a location for internal use in the Lisp program,
5438 store it in a Lisp variable. Example:
5440 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5441 (if pos
5442 (progn
5443 (set-marker (mark-marker) pos (current-buffer))
5444 (activate-mark 'no-tmm))
5445 ;; Normally we never clear mark-active except in Transient Mark mode.
5446 ;; But when we actually clear out the mark value too, we must
5447 ;; clear mark-active in any mode.
5448 (deactivate-mark t)
5449 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5450 ;; it should never be nil if the mark is nil.
5451 (setq mark-active nil)
5452 (set-marker (mark-marker) nil)))
5454 (defun save-mark-and-excursion--save ()
5455 (cons
5456 (let ((mark (mark-marker)))
5457 (and (marker-position mark) (copy-marker mark)))
5458 mark-active))
5460 (defun save-mark-and-excursion--restore (saved-mark-info)
5461 (let ((saved-mark (car saved-mark-info))
5462 (omark (marker-position (mark-marker)))
5463 (nmark nil)
5464 (saved-mark-active (cdr saved-mark-info)))
5465 ;; Mark marker
5466 (if (null saved-mark)
5467 (set-marker (mark-marker) nil)
5468 (setf nmark (marker-position saved-mark))
5469 (set-marker (mark-marker) nmark)
5470 (set-marker saved-mark nil))
5471 ;; Mark active
5472 (let ((cur-mark-active mark-active))
5473 (setq mark-active saved-mark-active)
5474 ;; If mark is active now, and either was not active or was at a
5475 ;; different place, run the activate hook.
5476 (if saved-mark-active
5477 (when (or (not cur-mark-active)
5478 (not (eq omark nmark)))
5479 (run-hooks 'activate-mark-hook))
5480 ;; If mark has ceased to be active, run deactivate hook.
5481 (when cur-mark-active
5482 (run-hooks 'deactivate-mark-hook))))))
5484 (defmacro save-mark-and-excursion (&rest body)
5485 "Like `save-excursion', but also save and restore the mark state.
5486 This macro does what `save-excursion' did before Emacs 25.1."
5487 (declare (indent 0) (debug t))
5488 (let ((saved-marker-sym (make-symbol "saved-marker")))
5489 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5490 (unwind-protect
5491 (save-excursion ,@body)
5492 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5494 (defcustom use-empty-active-region nil
5495 "Whether \"region-aware\" commands should act on empty regions.
5496 If nil, region-aware commands treat the empty region as inactive.
5497 If non-nil, region-aware commands treat the region as active as
5498 long as the mark is active, even if the region is empty.
5500 Region-aware commands are those that act on the region if it is
5501 active and Transient Mark mode is enabled, and on the text near
5502 point otherwise."
5503 :type 'boolean
5504 :version "23.1"
5505 :group 'editing-basics)
5507 (defun use-region-p ()
5508 "Return t if the region is active and it is appropriate to act on it.
5509 This is used by commands that act specially on the region under
5510 Transient Mark mode.
5512 The return value is t if Transient Mark mode is enabled and the
5513 mark is active; furthermore, if `use-empty-active-region' is nil,
5514 the region must not be empty. Otherwise, the return value is nil.
5516 For some commands, it may be appropriate to ignore the value of
5517 `use-empty-active-region'; in that case, use `region-active-p'."
5518 (and (region-active-p)
5519 (or use-empty-active-region (> (region-end) (region-beginning)))))
5521 (defun region-active-p ()
5522 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5524 Some commands act specially on the region when Transient Mark
5525 mode is enabled. Usually, such commands should use
5526 `use-region-p' instead of this function, because `use-region-p'
5527 also checks the value of `use-empty-active-region'."
5528 (and transient-mark-mode mark-active
5529 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5530 ;; without the mark being set (e.g. bug#17324). We really should fix
5531 ;; that problem, but in the mean time, let's make sure we don't say the
5532 ;; region is active when there's no mark.
5533 (progn (cl-assert (mark)) t)))
5535 (defun region-bounds ()
5536 "Return the boundaries of the region as a pair of positions.
5537 Value is a list of cons cells of the form (START . END)."
5538 (funcall region-extract-function 'bounds))
5540 (defun region-noncontiguous-p ()
5541 "Return non-nil if the region contains several pieces.
5542 An example is a rectangular region handled as a list of
5543 separate contiguous regions for each line."
5544 (> (length (region-bounds)) 1))
5546 (defvar redisplay-unhighlight-region-function
5547 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5549 (defvar redisplay-highlight-region-function
5550 (lambda (start end window rol)
5551 (if (not (overlayp rol))
5552 (let ((nrol (make-overlay start end)))
5553 (funcall redisplay-unhighlight-region-function rol)
5554 (overlay-put nrol 'window window)
5555 (overlay-put nrol 'face 'region)
5556 ;; Normal priority so that a large region doesn't hide all the
5557 ;; overlays within it, but high secondary priority so that if it
5558 ;; ends/starts in the middle of a small overlay, that small overlay
5559 ;; won't hide the region's boundaries.
5560 (overlay-put nrol 'priority '(nil . 100))
5561 nrol)
5562 (unless (and (eq (overlay-buffer rol) (current-buffer))
5563 (eq (overlay-start rol) start)
5564 (eq (overlay-end rol) end))
5565 (move-overlay rol start end (current-buffer)))
5566 rol)))
5568 (defun redisplay--update-region-highlight (window)
5569 (let ((rol (window-parameter window 'internal-region-overlay)))
5570 (if (not (and (region-active-p)
5571 (or highlight-nonselected-windows
5572 (eq window (selected-window))
5573 (and (window-minibuffer-p)
5574 (eq window (minibuffer-selected-window))))))
5575 (funcall redisplay-unhighlight-region-function rol)
5576 (let* ((pt (window-point window))
5577 (mark (mark))
5578 (start (min pt mark))
5579 (end (max pt mark))
5580 (new
5581 (funcall redisplay-highlight-region-function
5582 start end window rol)))
5583 (unless (equal new rol)
5584 (set-window-parameter window 'internal-region-overlay
5585 new))))))
5587 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5588 "Hook run just before redisplay.
5589 It is called in each window that is to be redisplayed. It takes one argument,
5590 which is the window that will be redisplayed. When run, the `current-buffer'
5591 is set to the buffer displayed in that window.")
5593 (defun redisplay--pre-redisplay-functions (windows)
5594 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5595 (if (null windows)
5596 (with-current-buffer (window-buffer (selected-window))
5597 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5598 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5599 (with-current-buffer (window-buffer win)
5600 (run-hook-with-args 'pre-redisplay-functions win))))))
5602 (add-function :before pre-redisplay-function
5603 #'redisplay--pre-redisplay-functions)
5606 (defvar-local mark-ring nil
5607 "The list of former marks of the current buffer, most recent first.")
5608 (put 'mark-ring 'permanent-local t)
5610 (defcustom mark-ring-max 16
5611 "Maximum size of mark ring. Start discarding off end if gets this big."
5612 :type 'integer
5613 :group 'editing-basics)
5615 (defvar global-mark-ring nil
5616 "The list of saved global marks, most recent first.")
5618 (defcustom global-mark-ring-max 16
5619 "Maximum size of global mark ring. \
5620 Start discarding off end if gets this big."
5621 :type 'integer
5622 :group 'editing-basics)
5624 (defun pop-to-mark-command ()
5625 "Jump to mark, and pop a new position for mark off the ring.
5626 \(Does not affect global mark ring)."
5627 (interactive)
5628 (if (null (mark t))
5629 (user-error "No mark set in this buffer")
5630 (if (= (point) (mark t))
5631 (message "Mark popped"))
5632 (goto-char (mark t))
5633 (pop-mark)))
5635 (defun push-mark-command (arg &optional nomsg)
5636 "Set mark at where point is.
5637 If no prefix ARG and mark is already set there, just activate it.
5638 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5639 (interactive "P")
5640 (let ((mark (mark t)))
5641 (if (or arg (null mark) (/= mark (point)))
5642 (push-mark nil nomsg t)
5643 (activate-mark 'no-tmm)
5644 (unless nomsg
5645 (message "Mark activated")))))
5647 (defcustom set-mark-command-repeat-pop nil
5648 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5649 That means that C-u \\[set-mark-command] \\[set-mark-command]
5650 will pop the mark twice, and
5651 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5652 will pop the mark three times.
5654 A value of nil means \\[set-mark-command]'s behavior does not change
5655 after C-u \\[set-mark-command]."
5656 :type 'boolean
5657 :group 'editing-basics)
5659 (defun set-mark-command (arg)
5660 "Set the mark where point is, and activate it; or jump to the mark.
5661 Setting the mark also alters the region, which is the text
5662 between point and mark; this is the closest equivalent in
5663 Emacs to what some editors call the \"selection\".
5665 With no prefix argument, set the mark at point, and push the
5666 old mark position on local mark ring. Also push the new mark on
5667 global mark ring, if the previous mark was set in another buffer.
5669 When Transient Mark Mode is off, immediately repeating this
5670 command activates `transient-mark-mode' temporarily.
5672 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5673 jump to the mark, and set the mark from
5674 position popped off the local mark ring (this does not affect the global
5675 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5676 mark ring (see `pop-global-mark').
5678 If `set-mark-command-repeat-pop' is non-nil, repeating
5679 the \\[set-mark-command] command with no prefix argument pops the next position
5680 off the local (or global) mark ring and jumps there.
5682 With \\[universal-argument] \\[universal-argument] as prefix
5683 argument, unconditionally set mark where point is, even if
5684 `set-mark-command-repeat-pop' is non-nil.
5686 Novice Emacs Lisp programmers often try to use the mark for the wrong
5687 purposes. See the documentation of `set-mark' for more information."
5688 (interactive "P")
5689 (cond ((eq transient-mark-mode 'lambda)
5690 (kill-local-variable 'transient-mark-mode))
5691 ((eq (car-safe transient-mark-mode) 'only)
5692 (deactivate-mark)))
5693 (cond
5694 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5695 (push-mark-command nil))
5696 ((not (eq this-command 'set-mark-command))
5697 (if arg
5698 (pop-to-mark-command)
5699 (push-mark-command t)))
5700 ((and set-mark-command-repeat-pop
5701 (eq last-command 'pop-global-mark)
5702 (not arg))
5703 (setq this-command 'pop-global-mark)
5704 (pop-global-mark))
5705 ((or (and set-mark-command-repeat-pop
5706 (eq last-command 'pop-to-mark-command))
5707 arg)
5708 (setq this-command 'pop-to-mark-command)
5709 (pop-to-mark-command))
5710 ((eq last-command 'set-mark-command)
5711 (if (region-active-p)
5712 (progn
5713 (deactivate-mark)
5714 (message "Mark deactivated"))
5715 (activate-mark)
5716 (message "Mark activated")))
5718 (push-mark-command nil))))
5720 (defun push-mark (&optional location nomsg activate)
5721 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5722 If the last global mark pushed was not in the current buffer,
5723 also push LOCATION on the global mark ring.
5724 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5726 Novice Emacs Lisp programmers often try to use the mark for the wrong
5727 purposes. See the documentation of `set-mark' for more information.
5729 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5730 (unless (null (mark t))
5731 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5732 (when (> (length mark-ring) mark-ring-max)
5733 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5734 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5735 (set-marker (mark-marker) (or location (point)) (current-buffer))
5736 ;; Now push the mark on the global mark ring.
5737 (if (and global-mark-ring
5738 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5739 ;; The last global mark pushed was in this same buffer.
5740 ;; Don't push another one.
5742 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5743 (when (> (length global-mark-ring) global-mark-ring-max)
5744 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5745 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5746 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5747 (message "Mark set"))
5748 (if (or activate (not transient-mark-mode))
5749 (set-mark (mark t)))
5750 nil)
5752 (defun pop-mark ()
5753 "Pop off mark ring into the buffer's actual mark.
5754 Does not set point. Does nothing if mark ring is empty."
5755 (when mark-ring
5756 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5757 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5758 (move-marker (car mark-ring) nil)
5759 (if (null (mark t)) (ding))
5760 (setq mark-ring (cdr mark-ring)))
5761 (deactivate-mark))
5763 (define-obsolete-function-alias
5764 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5765 (defun exchange-point-and-mark (&optional arg)
5766 "Put the mark where point is now, and point where the mark is now.
5767 This command works even when the mark is not active,
5768 and it reactivates the mark.
5770 If Transient Mark mode is on, a prefix ARG deactivates the mark
5771 if it is active, and otherwise avoids reactivating it. If
5772 Transient Mark mode is off, a prefix ARG enables Transient Mark
5773 mode temporarily."
5774 (interactive "P")
5775 (let ((omark (mark t))
5776 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5777 (if (null omark)
5778 (user-error "No mark set in this buffer"))
5779 (set-mark (point))
5780 (goto-char omark)
5781 (cond (temp-highlight
5782 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5783 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5784 (not (or arg (region-active-p))))
5785 (deactivate-mark))
5786 (t (activate-mark)))
5787 nil))
5789 (defcustom shift-select-mode t
5790 "When non-nil, shifted motion keys activate the mark momentarily.
5792 While the mark is activated in this way, any shift-translated point
5793 motion key extends the region, and if Transient Mark mode was off, it
5794 is temporarily turned on. Furthermore, the mark will be deactivated
5795 by any subsequent point motion key that was not shift-translated, or
5796 by any action that normally deactivates the mark in Transient Mark mode.
5798 See `this-command-keys-shift-translated' for the meaning of
5799 shift-translation."
5800 :type 'boolean
5801 :group 'editing-basics)
5803 (defun handle-shift-selection ()
5804 "Activate/deactivate mark depending on invocation thru shift translation.
5805 This function is called by `call-interactively' when a command
5806 with a `^' character in its `interactive' spec is invoked, before
5807 running the command itself.
5809 If `shift-select-mode' is enabled and the command was invoked
5810 through shift translation, set the mark and activate the region
5811 temporarily, unless it was already set in this way. See
5812 `this-command-keys-shift-translated' for the meaning of shift
5813 translation.
5815 Otherwise, if the region has been activated temporarily,
5816 deactivate it, and restore the variable `transient-mark-mode' to
5817 its earlier value."
5818 (cond ((and shift-select-mode this-command-keys-shift-translated)
5819 (unless (and mark-active
5820 (eq (car-safe transient-mark-mode) 'only))
5821 (setq-local transient-mark-mode
5822 (cons 'only
5823 (unless (eq transient-mark-mode 'lambda)
5824 transient-mark-mode)))
5825 (push-mark nil nil t)))
5826 ((eq (car-safe transient-mark-mode) 'only)
5827 (setq transient-mark-mode (cdr transient-mark-mode))
5828 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5829 (kill-local-variable 'transient-mark-mode))
5830 (deactivate-mark))))
5832 (define-minor-mode transient-mark-mode
5833 "Toggle Transient Mark mode.
5834 With a prefix argument ARG, enable Transient Mark mode if ARG is
5835 positive, and disable it otherwise. If called from Lisp, enable
5836 Transient Mark mode if ARG is omitted or nil.
5838 Transient Mark mode is a global minor mode. When enabled, the
5839 region is highlighted with the `region' face whenever the mark
5840 is active. The mark is \"deactivated\" by changing the buffer,
5841 and after certain other operations that set the mark but whose
5842 main purpose is something else--for example, incremental search,
5843 \\[beginning-of-buffer], and \\[end-of-buffer].
5845 You can also deactivate the mark by typing \\[keyboard-quit] or
5846 \\[keyboard-escape-quit].
5848 Many commands change their behavior when Transient Mark mode is
5849 in effect and the mark is active, by acting on the region instead
5850 of their usual default part of the buffer's text. Examples of
5851 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5852 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5853 To see the documentation of commands which are sensitive to the
5854 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5855 or \"mark.*active\" at the prompt."
5856 :global t
5857 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5858 :variable (default-value 'transient-mark-mode))
5860 (defvar widen-automatically t
5861 "Non-nil means it is ok for commands to call `widen' when they want to.
5862 Some commands will do this in order to go to positions outside
5863 the current accessible part of the buffer.
5865 If `widen-automatically' is nil, these commands will do something else
5866 as a fallback, and won't change the buffer bounds.")
5868 (defvar non-essential nil
5869 "Whether the currently executing code is performing an essential task.
5870 This variable should be non-nil only when running code which should not
5871 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5872 user for a password when we are simply scanning a set of files in the
5873 background or displaying possible completions before the user even asked
5874 for it.")
5876 (defun pop-global-mark ()
5877 "Pop off global mark ring and jump to the top location."
5878 (interactive)
5879 ;; Pop entries which refer to non-existent buffers.
5880 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5881 (setq global-mark-ring (cdr global-mark-ring)))
5882 (or global-mark-ring
5883 (error "No global mark set"))
5884 (let* ((marker (car global-mark-ring))
5885 (buffer (marker-buffer marker))
5886 (position (marker-position marker)))
5887 (setq global-mark-ring (nconc (cdr global-mark-ring)
5888 (list (car global-mark-ring))))
5889 (set-buffer buffer)
5890 (or (and (>= position (point-min))
5891 (<= position (point-max)))
5892 (if widen-automatically
5893 (widen)
5894 (error "Global mark position is outside accessible part of buffer")))
5895 (goto-char position)
5896 (switch-to-buffer buffer)))
5898 (defcustom next-line-add-newlines nil
5899 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5900 :type 'boolean
5901 :version "21.1"
5902 :group 'editing-basics)
5904 (defun next-line (&optional arg try-vscroll)
5905 "Move cursor vertically down ARG lines.
5906 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5907 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5908 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5909 function will not vscroll.
5911 ARG defaults to 1.
5913 If there is no character in the target line exactly under the current column,
5914 the cursor is positioned after the character in that line which spans this
5915 column, or at the end of the line if it is not long enough.
5916 If there is no line in the buffer after this one, behavior depends on the
5917 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5918 to create a line, and moves the cursor to that line. Otherwise it moves the
5919 cursor to the end of the buffer.
5921 If the variable `line-move-visual' is non-nil, this command moves
5922 by display lines. Otherwise, it moves by buffer lines, without
5923 taking variable-width characters or continued lines into account.
5924 See \\[next-logical-line] for a command that always moves by buffer lines.
5926 The command \\[set-goal-column] can be used to create
5927 a semipermanent goal column for this command.
5928 Then instead of trying to move exactly vertically (or as close as possible),
5929 this command moves to the specified goal column (or as close as possible).
5930 The goal column is stored in the variable `goal-column', which is nil
5931 when there is no goal column. Note that setting `goal-column'
5932 overrides `line-move-visual' and causes this command to move by buffer
5933 lines rather than by display lines."
5934 (declare (interactive-only forward-line))
5935 (interactive "^p\np")
5936 (or arg (setq arg 1))
5937 (if (and next-line-add-newlines (= arg 1))
5938 (if (save-excursion (end-of-line) (eobp))
5939 ;; When adding a newline, don't expand an abbrev.
5940 (let ((abbrev-mode nil))
5941 (end-of-line)
5942 (insert (if use-hard-newlines hard-newline "\n")))
5943 (line-move arg nil nil try-vscroll))
5944 (if (called-interactively-p 'interactive)
5945 (condition-case err
5946 (line-move arg nil nil try-vscroll)
5947 ((beginning-of-buffer end-of-buffer)
5948 (signal (car err) (cdr err))))
5949 (line-move arg nil nil try-vscroll)))
5950 nil)
5952 (defun previous-line (&optional arg try-vscroll)
5953 "Move cursor vertically up ARG lines.
5954 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5955 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5956 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5957 function will not vscroll.
5959 ARG defaults to 1.
5961 If there is no character in the target line exactly over the current column,
5962 the cursor is positioned after the character in that line which spans this
5963 column, or at the end of the line if it is not long enough.
5965 If the variable `line-move-visual' is non-nil, this command moves
5966 by display lines. Otherwise, it moves by buffer lines, without
5967 taking variable-width characters or continued lines into account.
5968 See \\[previous-logical-line] for a command that always moves by buffer lines.
5970 The command \\[set-goal-column] can be used to create
5971 a semipermanent goal column for this command.
5972 Then instead of trying to move exactly vertically (or as close as possible),
5973 this command moves to the specified goal column (or as close as possible).
5974 The goal column is stored in the variable `goal-column', which is nil
5975 when there is no goal column. Note that setting `goal-column'
5976 overrides `line-move-visual' and causes this command to move by buffer
5977 lines rather than by display lines."
5978 (declare (interactive-only
5979 "use `forward-line' with negative argument instead."))
5980 (interactive "^p\np")
5981 (or arg (setq arg 1))
5982 (if (called-interactively-p 'interactive)
5983 (condition-case err
5984 (line-move (- arg) nil nil try-vscroll)
5985 ((beginning-of-buffer end-of-buffer)
5986 (signal (car err) (cdr err))))
5987 (line-move (- arg) nil nil try-vscroll))
5988 nil)
5990 (defcustom track-eol nil
5991 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5992 This means moving to the end of each line moved onto.
5993 The beginning of a blank line does not count as the end of a line.
5994 This has no effect when the variable `line-move-visual' is non-nil."
5995 :type 'boolean
5996 :group 'editing-basics)
5998 (defcustom goal-column nil
5999 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
6000 A non-nil setting overrides the variable `line-move-visual', which see."
6001 :type '(choice integer
6002 (const :tag "None" nil))
6003 :group 'editing-basics)
6004 (make-variable-buffer-local 'goal-column)
6006 (defvar temporary-goal-column 0
6007 "Current goal column for vertical motion.
6008 It is the column where point was at the start of the current run
6009 of vertical motion commands.
6011 When moving by visual lines via the function `line-move-visual', it is a cons
6012 cell (COL . HSCROLL), where COL is the x-position, in pixels,
6013 divided by the default column width, and HSCROLL is the number of
6014 columns by which window is scrolled from left margin.
6016 When the `track-eol' feature is doing its job, the value is
6017 `most-positive-fixnum'.")
6019 (defvar last--line-number-width 0
6020 "Last value of width used for displaying line numbers.
6021 Used internally by `line-move-visual'.")
6023 (defcustom line-move-ignore-invisible t
6024 "Non-nil means commands that move by lines ignore invisible newlines.
6025 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
6026 as if newlines that are invisible didn't exist, and count
6027 only visible newlines. Thus, moving across 2 newlines
6028 one of which is invisible will be counted as a one-line move.
6029 Also, a non-nil value causes invisible text to be ignored when
6030 counting columns for the purposes of keeping point in the same
6031 column by \\[next-line] and \\[previous-line].
6033 Outline mode sets this."
6034 :type 'boolean
6035 :group 'editing-basics)
6037 (defcustom line-move-visual t
6038 "When non-nil, `line-move' moves point by visual lines.
6039 This movement is based on where the cursor is displayed on the
6040 screen, instead of relying on buffer contents alone. It takes
6041 into account variable-width characters and line continuation.
6042 If nil, `line-move' moves point by logical lines.
6043 A non-nil setting of `goal-column' overrides the value of this variable
6044 and forces movement by logical lines.
6045 A window that is horizontally scrolled also forces movement by logical
6046 lines."
6047 :type 'boolean
6048 :group 'editing-basics
6049 :version "23.1")
6051 ;; Only used if display-graphic-p.
6052 (declare-function font-info "font.c" (name &optional frame))
6054 (defun default-font-height ()
6055 "Return the height in pixels of the current buffer's default face font.
6057 If the default font is remapped (see `face-remapping-alist'), the
6058 function returns the height of the remapped face."
6059 (let ((default-font (face-font 'default)))
6060 (cond
6061 ((and (display-multi-font-p)
6062 ;; Avoid calling font-info if the frame's default font was
6063 ;; not changed since the frame was created. That's because
6064 ;; font-info is expensive for some fonts, see bug #14838.
6065 (not (string= (frame-parameter nil 'font) default-font)))
6066 (aref (font-info default-font) 3))
6067 (t (frame-char-height)))))
6069 (defun default-font-width ()
6070 "Return the width in pixels of the current buffer's default face font.
6072 If the default font is remapped (see `face-remapping-alist'), the
6073 function returns the width of the remapped face."
6074 (let ((default-font (face-font 'default)))
6075 (cond
6076 ((and (display-multi-font-p)
6077 ;; Avoid calling font-info if the frame's default font was
6078 ;; not changed since the frame was created. That's because
6079 ;; font-info is expensive for some fonts, see bug #14838.
6080 (not (string= (frame-parameter nil 'font) default-font)))
6081 (let* ((info (font-info (face-font 'default)))
6082 (width (aref info 11)))
6083 (if (> width 0)
6084 width
6085 (aref info 10))))
6086 (t (frame-char-width)))))
6088 (defun default-line-height ()
6089 "Return the pixel height of current buffer's default-face text line.
6091 The value includes `line-spacing', if any, defined for the buffer
6092 or the frame."
6093 (let ((dfh (default-font-height))
6094 (lsp (if (display-graphic-p)
6095 (or line-spacing
6096 (default-value 'line-spacing)
6097 (frame-parameter nil 'line-spacing)
6099 0)))
6100 (if (floatp lsp)
6101 (setq lsp (truncate (* (frame-char-height) lsp))))
6102 (+ dfh lsp)))
6104 (defun window-screen-lines ()
6105 "Return the number of screen lines in the text area of the selected window.
6107 This is different from `window-text-height' in that this function counts
6108 lines in units of the height of the font used by the default face displayed
6109 in the window, not in units of the frame's default font, and also accounts
6110 for `line-spacing', if any, defined for the window's buffer or frame.
6112 The value is a floating-point number."
6113 (let ((edges (window-inside-pixel-edges))
6114 (dlh (default-line-height)))
6115 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
6117 ;; Returns non-nil if partial move was done.
6118 (defun line-move-partial (arg noerror &optional _to-end)
6119 (if (< arg 0)
6120 ;; Move backward (up).
6121 ;; If already vscrolled, reduce vscroll
6122 (let ((vs (window-vscroll nil t))
6123 (dlh (default-line-height)))
6124 (when (> vs dlh)
6125 (set-window-vscroll nil (- vs dlh) t)))
6127 ;; Move forward (down).
6128 (let* ((lh (window-line-height -1))
6129 (rowh (car lh))
6130 (vpos (nth 1 lh))
6131 (ypos (nth 2 lh))
6132 (rbot (nth 3 lh))
6133 (this-lh (window-line-height))
6134 (this-height (car this-lh))
6135 (this-ypos (nth 2 this-lh))
6136 (dlh (default-line-height))
6137 (wslines (window-screen-lines))
6138 (edges (window-inside-pixel-edges))
6139 (winh (- (nth 3 edges) (nth 1 edges) 1))
6140 py vs last-line)
6141 (if (> (mod wslines 1.0) 0.0)
6142 (setq wslines (round (+ wslines 0.5))))
6143 (when (or (null lh)
6144 (>= rbot dlh)
6145 (<= ypos (- dlh))
6146 (null this-lh)
6147 (<= this-ypos (- dlh)))
6148 (unless lh
6149 (let ((wend (pos-visible-in-window-p t nil t)))
6150 (setq rbot (nth 3 wend)
6151 rowh (nth 4 wend)
6152 vpos (nth 5 wend))))
6153 (unless this-lh
6154 (let ((wstart (pos-visible-in-window-p nil nil t)))
6155 (setq this-ypos (nth 2 wstart)
6156 this-height (nth 4 wstart))))
6157 (setq py
6158 (or (nth 1 this-lh)
6159 (let ((ppos (posn-at-point))
6160 col-row)
6161 (setq col-row (posn-actual-col-row ppos))
6162 (if col-row
6163 (- (cdr col-row) (window-vscroll))
6164 (cdr (posn-col-row ppos))))))
6165 ;; VPOS > 0 means the last line is only partially visible.
6166 ;; But if the part that is visible is at least as tall as the
6167 ;; default font, that means the line is actually fully
6168 ;; readable, and something like line-spacing is hidden. So in
6169 ;; that case we accept the last line in the window as still
6170 ;; visible, and consider the margin as starting one line
6171 ;; later.
6172 (if (and vpos (> vpos 0))
6173 (if (and rowh
6174 (>= rowh (default-font-height))
6175 (< rowh dlh))
6176 (setq last-line (min (- wslines scroll-margin) vpos))
6177 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6178 (cond
6179 ;; If last line of window is fully visible, and vscrolling
6180 ;; more would make this line invisible, move forward.
6181 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6182 (null this-height)
6183 (<= this-height dlh))
6184 (or (null rbot) (= rbot 0)))
6185 nil)
6186 ;; If cursor is not in the bottom scroll margin, and the
6187 ;; current line is not too tall, move forward.
6188 ((and (or (null this-height) (<= this-height winh))
6189 vpos
6190 (> vpos 0)
6191 (< py last-line))
6192 nil)
6193 ;; When already vscrolled, we vscroll some more if we can,
6194 ;; or clear vscroll and move forward at end of tall image.
6195 ((> vs 0)
6196 (when (or (and rbot (> rbot 0))
6197 (and this-height (> this-height dlh)))
6198 (set-window-vscroll nil (+ vs dlh) t)))
6199 ;; If cursor just entered the bottom scroll margin, move forward,
6200 ;; but also optionally vscroll one line so redisplay won't recenter.
6201 ((and vpos
6202 (> vpos 0)
6203 (= py last-line))
6204 ;; Don't vscroll if the partially-visible line at window
6205 ;; bottom is not too tall (a.k.a. "just one more text
6206 ;; line"): in that case, we do want redisplay to behave
6207 ;; normally, i.e. recenter or whatever.
6209 ;; Note: ROWH + RBOT from the value returned by
6210 ;; pos-visible-in-window-p give the total height of the
6211 ;; partially-visible glyph row at the end of the window. As
6212 ;; we are dealing with floats, we disregard sub-pixel
6213 ;; discrepancies between that and DLH.
6214 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6215 (set-window-vscroll nil dlh t))
6216 (line-move-1 arg noerror)
6218 ;; If there are lines above the last line, scroll-up one line.
6219 ((and vpos (> vpos 0))
6220 (scroll-up 1)
6222 ;; Finally, start vscroll.
6224 (set-window-vscroll nil dlh t)))))))
6227 ;; This is like line-move-1 except that it also performs
6228 ;; vertical scrolling of tall images if appropriate.
6229 ;; That is not really a clean thing to do, since it mixes
6230 ;; scrolling with cursor motion. But so far we don't have
6231 ;; a cleaner solution to the problem of making C-n do something
6232 ;; useful given a tall image.
6233 (defun line-move (arg &optional noerror _to-end try-vscroll)
6234 "Move forward ARG lines.
6235 If NOERROR, don't signal an error if we can't move ARG lines.
6236 TO-END is unused.
6237 TRY-VSCROLL controls whether to vscroll tall lines: if either
6238 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6239 not vscroll."
6240 (if noninteractive
6241 (line-move-1 arg noerror)
6242 (unless (and auto-window-vscroll try-vscroll
6243 ;; Only vscroll for single line moves
6244 (= (abs arg) 1)
6245 ;; Under scroll-conservatively, the display engine
6246 ;; does this better.
6247 (zerop scroll-conservatively)
6248 ;; But don't vscroll in a keyboard macro.
6249 (not defining-kbd-macro)
6250 (not executing-kbd-macro)
6251 (line-move-partial arg noerror))
6252 (set-window-vscroll nil 0 t)
6253 (if (and line-move-visual
6254 ;; Display-based column are incompatible with goal-column.
6255 (not goal-column)
6256 ;; When the text in the window is scrolled to the left,
6257 ;; display-based motion doesn't make sense (because each
6258 ;; logical line occupies exactly one screen line).
6259 (not (> (window-hscroll) 0))
6260 ;; Likewise when the text _was_ scrolled to the left
6261 ;; when the current run of vertical motion commands
6262 ;; started.
6263 (not (and (memq last-command
6264 `(next-line previous-line ,this-command))
6265 auto-hscroll-mode
6266 (numberp temporary-goal-column)
6267 (>= temporary-goal-column
6268 (- (window-width) hscroll-margin)))))
6269 (prog1 (line-move-visual arg noerror)
6270 ;; If we moved into a tall line, set vscroll to make
6271 ;; scrolling through tall images more smooth.
6272 (let ((lh (line-pixel-height))
6273 (edges (window-inside-pixel-edges))
6274 (dlh (default-line-height))
6275 winh)
6276 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6277 (if (and (< arg 0)
6278 (< (point) (window-start))
6279 (> lh winh))
6280 (set-window-vscroll
6282 (- lh dlh) t))))
6283 (line-move-1 arg noerror)))))
6285 ;; Display-based alternative to line-move-1.
6286 ;; Arg says how many lines to move. The value is t if we can move the
6287 ;; specified number of lines.
6288 (defun line-move-visual (arg &optional noerror)
6289 "Move ARG lines forward.
6290 If NOERROR, don't signal an error if we can't move that many lines."
6291 (let ((opoint (point))
6292 (hscroll (window-hscroll))
6293 (lnum-width (line-number-display-width t))
6294 target-hscroll)
6295 ;; Check if the previous command was a line-motion command, or if
6296 ;; we were called from some other command.
6297 (if (and (consp temporary-goal-column)
6298 (memq last-command `(next-line previous-line ,this-command)))
6299 ;; If so, there's no need to reset `temporary-goal-column',
6300 ;; but we may need to hscroll.
6301 (progn
6302 (if (or (/= (cdr temporary-goal-column) hscroll)
6303 (> (cdr temporary-goal-column) 0))
6304 (setq target-hscroll (cdr temporary-goal-column)))
6305 ;; Update the COLUMN part of temporary-goal-column if the
6306 ;; line-number display changed its width since the last
6307 ;; time.
6308 (setq temporary-goal-column
6309 (cons (+ (car temporary-goal-column)
6310 (/ (float (- lnum-width last--line-number-width))
6311 (frame-char-width)))
6312 (cdr temporary-goal-column)))
6313 (setq last--line-number-width lnum-width))
6314 ;; Otherwise, we should reset `temporary-goal-column'.
6315 (let ((posn (posn-at-point))
6316 x-pos)
6317 (cond
6318 ;; Handle the `overflow-newline-into-fringe' case
6319 ;; (left-fringe is for the R2L case):
6320 ((memq (nth 1 posn) '(right-fringe left-fringe))
6321 (setq temporary-goal-column (cons (window-width) hscroll)))
6322 ((car (posn-x-y posn))
6323 (setq x-pos (car (posn-x-y posn)))
6324 ;; In R2L lines, the X pixel coordinate is measured from the
6325 ;; left edge of the window, but columns are still counted
6326 ;; from the logical-order beginning of the line, i.e. from
6327 ;; the right edge in this case. We need to adjust for that.
6328 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6329 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6330 (setq temporary-goal-column
6331 (cons (/ (float x-pos)
6332 (frame-char-width))
6333 hscroll)))
6334 (executing-kbd-macro
6335 ;; When we move beyond the first/last character visible in
6336 ;; the window, posn-at-point will return nil, so we need to
6337 ;; approximate the goal column as below.
6338 (setq temporary-goal-column
6339 (mod (current-column) (window-text-width)))))))
6340 (if target-hscroll
6341 (set-window-hscroll (selected-window) target-hscroll))
6342 ;; vertical-motion can move more than it was asked to if it moves
6343 ;; across display strings with newlines. We don't want to ring
6344 ;; the bell and announce beginning/end of buffer in that case.
6345 (or (and (or (and (>= arg 0)
6346 (>= (vertical-motion
6347 (cons (or goal-column
6348 (if (consp temporary-goal-column)
6349 (car temporary-goal-column)
6350 temporary-goal-column))
6351 arg))
6352 arg))
6353 (and (< arg 0)
6354 (<= (vertical-motion
6355 (cons (or goal-column
6356 (if (consp temporary-goal-column)
6357 (car temporary-goal-column)
6358 temporary-goal-column))
6359 arg))
6360 arg)))
6361 (or (>= arg 0)
6362 (/= (point) opoint)
6363 ;; If the goal column lies on a display string,
6364 ;; `vertical-motion' advances the cursor to the end
6365 ;; of the string. For arg < 0, this can cause the
6366 ;; cursor to get stuck. (Bug#3020).
6367 (= (vertical-motion arg) arg)))
6368 (unless noerror
6369 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6370 nil)))))
6372 ;; This is the guts of next-line and previous-line.
6373 ;; Arg says how many lines to move.
6374 ;; The value is t if we can move the specified number of lines.
6375 (defun line-move-1 (arg &optional noerror _to-end)
6376 ;; Don't run any point-motion hooks, and disregard intangibility,
6377 ;; for intermediate positions.
6378 (let ((inhibit-point-motion-hooks t)
6379 (opoint (point))
6380 (orig-arg arg))
6381 (if (consp temporary-goal-column)
6382 (setq temporary-goal-column (+ (car temporary-goal-column)
6383 (cdr temporary-goal-column))))
6384 (unwind-protect
6385 (progn
6386 (if (not (memq last-command '(next-line previous-line)))
6387 (setq temporary-goal-column
6388 (if (and track-eol (eolp)
6389 ;; Don't count beg of empty line as end of line
6390 ;; unless we just did explicit end-of-line.
6391 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6392 most-positive-fixnum
6393 (current-column))))
6395 (if (not (or (integerp selective-display)
6396 line-move-ignore-invisible))
6397 ;; Use just newline characters.
6398 ;; Set ARG to 0 if we move as many lines as requested.
6399 (or (if (> arg 0)
6400 (progn (if (> arg 1) (forward-line (1- arg)))
6401 ;; This way of moving forward ARG lines
6402 ;; verifies that we have a newline after the last one.
6403 ;; It doesn't get confused by intangible text.
6404 (end-of-line)
6405 (if (zerop (forward-line 1))
6406 (setq arg 0)))
6407 (and (zerop (forward-line arg))
6408 (bolp)
6409 (setq arg 0)))
6410 (unless noerror
6411 (signal (if (< arg 0)
6412 'beginning-of-buffer
6413 'end-of-buffer)
6414 nil)))
6415 ;; Move by arg lines, but ignore invisible ones.
6416 (let (done)
6417 (while (and (> arg 0) (not done))
6418 ;; If the following character is currently invisible,
6419 ;; skip all characters with that same `invisible' property value.
6420 (while (and (not (eobp)) (invisible-p (point)))
6421 (goto-char (next-char-property-change (point))))
6422 ;; Move a line.
6423 ;; We don't use `end-of-line', since we want to escape
6424 ;; from field boundaries occurring exactly at point.
6425 (goto-char (constrain-to-field
6426 (let ((inhibit-field-text-motion t))
6427 (line-end-position))
6428 (point) t t
6429 'inhibit-line-move-field-capture))
6430 ;; If there's no invisibility here, move over the newline.
6431 (cond
6432 ((eobp)
6433 (if (not noerror)
6434 (signal 'end-of-buffer nil)
6435 (setq done t)))
6436 ((and (> arg 1) ;; Use vertical-motion for last move
6437 (not (integerp selective-display))
6438 (not (invisible-p (point))))
6439 ;; We avoid vertical-motion when possible
6440 ;; because that has to fontify.
6441 (forward-line 1))
6442 ;; Otherwise move a more sophisticated way.
6443 ((zerop (vertical-motion 1))
6444 (if (not noerror)
6445 (signal 'end-of-buffer nil)
6446 (setq done t))))
6447 (unless done
6448 (setq arg (1- arg))))
6449 ;; The logic of this is the same as the loop above,
6450 ;; it just goes in the other direction.
6451 (while (and (< arg 0) (not done))
6452 ;; For completely consistency with the forward-motion
6453 ;; case, we should call beginning-of-line here.
6454 ;; However, if point is inside a field and on a
6455 ;; continued line, the call to (vertical-motion -1)
6456 ;; below won't move us back far enough; then we return
6457 ;; to the same column in line-move-finish, and point
6458 ;; gets stuck -- cyd
6459 (forward-line 0)
6460 (cond
6461 ((bobp)
6462 (if (not noerror)
6463 (signal 'beginning-of-buffer nil)
6464 (setq done t)))
6465 ((and (< arg -1) ;; Use vertical-motion for last move
6466 (not (integerp selective-display))
6467 (not (invisible-p (1- (point)))))
6468 (forward-line -1))
6469 ((zerop (vertical-motion -1))
6470 (if (not noerror)
6471 (signal 'beginning-of-buffer nil)
6472 (setq done t))))
6473 (unless done
6474 (setq arg (1+ arg))
6475 (while (and ;; Don't move over previous invis lines
6476 ;; if our target is the middle of this line.
6477 (or (zerop (or goal-column temporary-goal-column))
6478 (< arg 0))
6479 (not (bobp)) (invisible-p (1- (point))))
6480 (goto-char (previous-char-property-change (point))))))))
6481 ;; This is the value the function returns.
6482 (= arg 0))
6484 (cond ((> arg 0)
6485 ;; If we did not move down as far as desired, at least go
6486 ;; to end of line. Be sure to call point-entered and
6487 ;; point-left-hooks.
6488 (let* ((npoint (prog1 (line-end-position)
6489 (goto-char opoint)))
6490 (inhibit-point-motion-hooks nil))
6491 (goto-char npoint)))
6492 ((< arg 0)
6493 ;; If we did not move up as far as desired,
6494 ;; at least go to beginning of line.
6495 (let* ((npoint (prog1 (line-beginning-position)
6496 (goto-char opoint)))
6497 (inhibit-point-motion-hooks nil))
6498 (goto-char npoint)))
6500 (line-move-finish (or goal-column temporary-goal-column)
6501 opoint (> orig-arg 0)))))))
6503 (defun line-move-finish (column opoint forward)
6504 (let ((repeat t))
6505 (while repeat
6506 ;; Set REPEAT to t to repeat the whole thing.
6507 (setq repeat nil)
6509 (let (new
6510 (old (point))
6511 (line-beg (line-beginning-position))
6512 (line-end
6513 ;; Compute the end of the line
6514 ;; ignoring effectively invisible newlines.
6515 (save-excursion
6516 ;; Like end-of-line but ignores fields.
6517 (skip-chars-forward "^\n")
6518 (while (and (not (eobp)) (invisible-p (point)))
6519 (goto-char (next-char-property-change (point)))
6520 (skip-chars-forward "^\n"))
6521 (point))))
6523 ;; Move to the desired column.
6524 (if (and line-move-visual
6525 (not (or truncate-lines truncate-partial-width-windows)))
6526 ;; Under line-move-visual, goal-column should be
6527 ;; interpreted in units of the frame's canonical character
6528 ;; width, which is exactly what vertical-motion does.
6529 (vertical-motion (cons column 0))
6530 (line-move-to-column (truncate column)))
6532 ;; Corner case: suppose we start out in a field boundary in
6533 ;; the middle of a continued line. When we get to
6534 ;; line-move-finish, point is at the start of a new *screen*
6535 ;; line but the same text line; then line-move-to-column would
6536 ;; move us backwards. Test using C-n with point on the "x" in
6537 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6538 (and forward
6539 (< (point) old)
6540 (goto-char old))
6542 (setq new (point))
6544 ;; Process intangibility within a line.
6545 ;; With inhibit-point-motion-hooks bound to nil, a call to
6546 ;; goto-char moves point past intangible text.
6548 ;; However, inhibit-point-motion-hooks controls both the
6549 ;; intangibility and the point-entered/point-left hooks. The
6550 ;; following hack avoids calling the point-* hooks
6551 ;; unnecessarily. Note that we move *forward* past intangible
6552 ;; text when the initial and final points are the same.
6553 (goto-char new)
6554 (let ((inhibit-point-motion-hooks nil))
6555 (goto-char new)
6557 ;; If intangibility moves us to a different (later) place
6558 ;; in the same line, use that as the destination.
6559 (if (<= (point) line-end)
6560 (setq new (point))
6561 ;; If that position is "too late",
6562 ;; try the previous allowable position.
6563 ;; See if it is ok.
6564 (backward-char)
6565 (if (if forward
6566 ;; If going forward, don't accept the previous
6567 ;; allowable position if it is before the target line.
6568 (< line-beg (point))
6569 ;; If going backward, don't accept the previous
6570 ;; allowable position if it is still after the target line.
6571 (<= (point) line-end))
6572 (setq new (point))
6573 ;; As a last resort, use the end of the line.
6574 (setq new line-end))))
6576 ;; Now move to the updated destination, processing fields
6577 ;; as well as intangibility.
6578 (goto-char opoint)
6579 (let ((inhibit-point-motion-hooks nil))
6580 (goto-char
6581 ;; Ignore field boundaries if the initial and final
6582 ;; positions have the same `field' property, even if the
6583 ;; fields are non-contiguous. This seems to be "nicer"
6584 ;; behavior in many situations.
6585 (if (eq (get-char-property new 'field)
6586 (get-char-property opoint 'field))
6588 (constrain-to-field new opoint t t
6589 'inhibit-line-move-field-capture))))
6591 ;; If all this moved us to a different line,
6592 ;; retry everything within that new line.
6593 (when (or (< (point) line-beg) (> (point) line-end))
6594 ;; Repeat the intangibility and field processing.
6595 (setq repeat t))))))
6597 (defun line-move-to-column (col)
6598 "Try to find column COL, considering invisibility.
6599 This function works only in certain cases,
6600 because what we really need is for `move-to-column'
6601 and `current-column' to be able to ignore invisible text."
6602 (if (zerop col)
6603 (beginning-of-line)
6604 (move-to-column col))
6606 (when (and line-move-ignore-invisible
6607 (not (bolp)) (invisible-p (1- (point))))
6608 (let ((normal-location (point))
6609 (normal-column (current-column)))
6610 ;; If the following character is currently invisible,
6611 ;; skip all characters with that same `invisible' property value.
6612 (while (and (not (eobp))
6613 (invisible-p (point)))
6614 (goto-char (next-char-property-change (point))))
6615 ;; Have we advanced to a larger column position?
6616 (if (> (current-column) normal-column)
6617 ;; We have made some progress towards the desired column.
6618 ;; See if we can make any further progress.
6619 (line-move-to-column (+ (current-column) (- col normal-column)))
6620 ;; Otherwise, go to the place we originally found
6621 ;; and move back over invisible text.
6622 ;; that will get us to the same place on the screen
6623 ;; but with a more reasonable buffer position.
6624 (goto-char normal-location)
6625 (let ((line-beg
6626 ;; We want the real line beginning, so it's consistent
6627 ;; with bolp below, otherwise we might infloop.
6628 (let ((inhibit-field-text-motion t))
6629 (line-beginning-position))))
6630 (while (and (not (bolp)) (invisible-p (1- (point))))
6631 (goto-char (previous-char-property-change (point) line-beg))))))))
6633 (defun move-end-of-line (arg)
6634 "Move point to end of current line as displayed.
6635 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6636 If point reaches the beginning or end of buffer, it stops there.
6638 To ignore the effects of the `intangible' text or overlay
6639 property, bind `inhibit-point-motion-hooks' to t.
6640 If there is an image in the current line, this function
6641 disregards newlines that are part of the text on which the image
6642 rests."
6643 (interactive "^p")
6644 (or arg (setq arg 1))
6645 (let (done)
6646 (while (not done)
6647 (let ((newpos
6648 (save-excursion
6649 (let ((goal-column 0)
6650 (line-move-visual nil))
6651 (and (line-move arg t)
6652 ;; With bidi reordering, we may not be at bol,
6653 ;; so make sure we are.
6654 (skip-chars-backward "^\n")
6655 (not (bobp))
6656 (progn
6657 (while (and (not (bobp)) (invisible-p (1- (point))))
6658 (goto-char (previous-single-char-property-change
6659 (point) 'invisible)))
6660 (backward-char 1)))
6661 (point)))))
6662 (goto-char newpos)
6663 (if (and (> (point) newpos)
6664 (eq (preceding-char) ?\n))
6665 (backward-char 1)
6666 (if (and (> (point) newpos) (not (eobp))
6667 (not (eq (following-char) ?\n)))
6668 ;; If we skipped something intangible and now we're not
6669 ;; really at eol, keep going.
6670 (setq arg 1)
6671 (setq done t)))))))
6673 (defun move-beginning-of-line (arg)
6674 "Move point to beginning of current line as displayed.
6675 \(If there's an image in the line, this disregards newlines
6676 which are part of the text that the image rests on.)
6678 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6679 If point reaches the beginning or end of buffer, it stops there.
6680 \(But if the buffer doesn't end in a newline, it stops at the
6681 beginning of the last line.)
6682 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6683 (interactive "^p")
6684 (or arg (setq arg 1))
6686 (let ((orig (point))
6687 first-vis first-vis-field-value)
6689 ;; Move by lines, if ARG is not 1 (the default).
6690 (if (/= arg 1)
6691 (let ((line-move-visual nil))
6692 (line-move (1- arg) t)))
6694 ;; Move to beginning-of-line, ignoring fields and invisible text.
6695 (skip-chars-backward "^\n")
6696 (while (and (not (bobp)) (invisible-p (1- (point))))
6697 (goto-char (previous-char-property-change (point)))
6698 (skip-chars-backward "^\n"))
6700 ;; Now find first visible char in the line.
6701 (while (and (< (point) orig) (invisible-p (point)))
6702 (goto-char (next-char-property-change (point) orig)))
6703 (setq first-vis (point))
6705 ;; See if fields would stop us from reaching FIRST-VIS.
6706 (setq first-vis-field-value
6707 (constrain-to-field first-vis orig (/= arg 1) t nil))
6709 (goto-char (if (/= first-vis-field-value first-vis)
6710 ;; If yes, obey them.
6711 first-vis-field-value
6712 ;; Otherwise, move to START with attention to fields.
6713 ;; (It is possible that fields never matter in this case.)
6714 (constrain-to-field (point) orig
6715 (/= arg 1) t nil)))))
6718 ;; Many people have said they rarely use this feature, and often type
6719 ;; it by accident. Maybe it shouldn't even be on a key.
6720 (put 'set-goal-column 'disabled t)
6722 (defun set-goal-column (arg)
6723 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6724 Those commands will move to this position in the line moved to
6725 rather than trying to keep the same horizontal position.
6726 With a non-nil argument ARG, clears out the goal column
6727 so that \\[next-line] and \\[previous-line] resume vertical motion.
6728 The goal column is stored in the variable `goal-column'.
6729 This is a buffer-local setting."
6730 (interactive "P")
6731 (if arg
6732 (progn
6733 (setq goal-column nil)
6734 (message "No goal column"))
6735 (setq goal-column (current-column))
6736 ;; The older method below can be erroneous if `set-goal-column' is bound
6737 ;; to a sequence containing %
6738 ;;(message (substitute-command-keys
6739 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6740 ;;goal-column)
6741 (message "%s"
6742 (concat
6743 (format "Goal column %d " goal-column)
6744 (substitute-command-keys
6745 "(use \\[set-goal-column] with an arg to unset it)")))
6748 nil)
6750 ;;; Editing based on visual lines, as opposed to logical lines.
6752 (defun end-of-visual-line (&optional n)
6753 "Move point to end of current visual line.
6754 With argument N not nil or 1, move forward N - 1 visual lines first.
6755 If point reaches the beginning or end of buffer, it stops there.
6756 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6757 (interactive "^p")
6758 (or n (setq n 1))
6759 (if (/= n 1)
6760 (let ((line-move-visual t))
6761 (line-move (1- n) t)))
6762 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6763 ;; constrain to field boundaries, so we don't either.
6764 (vertical-motion (cons (window-width) 0)))
6766 (defun beginning-of-visual-line (&optional n)
6767 "Move point to beginning of current visual line.
6768 With argument N not nil or 1, move forward N - 1 visual lines first.
6769 If point reaches the beginning or end of buffer, it stops there.
6770 \(But if the buffer doesn't end in a newline, it stops at the
6771 beginning of the last visual line.)
6772 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6773 (interactive "^p")
6774 (or n (setq n 1))
6775 (let ((opoint (point)))
6776 (if (/= n 1)
6777 (let ((line-move-visual t))
6778 (line-move (1- n) t)))
6779 (vertical-motion 0)
6780 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6781 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6783 (defun kill-visual-line (&optional arg)
6784 "Kill the rest of the visual line.
6785 With prefix argument ARG, kill that many visual lines from point.
6786 If ARG is negative, kill visual lines backward.
6787 If ARG is zero, kill the text before point on the current visual
6788 line.
6790 If you want to append the killed line to the last killed text,
6791 use \\[append-next-kill] before \\[kill-line].
6793 If the buffer is read-only, Emacs will beep and refrain from deleting
6794 the line, but put the line in the kill ring anyway. This means that
6795 you can use this command to copy text from a read-only buffer.
6796 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6797 even beep.)"
6798 (interactive "P")
6799 ;; Like in `kill-line', it's better to move point to the other end
6800 ;; of the kill before killing.
6801 (let ((opoint (point))
6802 (kill-whole-line (and kill-whole-line (bolp))))
6803 (if arg
6804 (vertical-motion (prefix-numeric-value arg))
6805 (end-of-visual-line 1)
6806 (if (= (point) opoint)
6807 (vertical-motion 1)
6808 ;; Skip any trailing whitespace at the end of the visual line.
6809 ;; We used to do this only if `show-trailing-whitespace' is
6810 ;; nil, but that's wrong; the correct thing would be to check
6811 ;; whether the trailing whitespace is highlighted. But, it's
6812 ;; OK to just do this unconditionally.
6813 (skip-chars-forward " \t")))
6814 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6815 (1+ (point))
6816 (point)))))
6818 (defun next-logical-line (&optional arg try-vscroll)
6819 "Move cursor vertically down ARG lines.
6820 This is identical to `next-line', except that it always moves
6821 by logical lines instead of visual lines, ignoring the value of
6822 the variable `line-move-visual'."
6823 (interactive "^p\np")
6824 (let ((line-move-visual nil))
6825 (with-no-warnings
6826 (next-line arg try-vscroll))))
6828 (defun previous-logical-line (&optional arg try-vscroll)
6829 "Move cursor vertically up ARG lines.
6830 This is identical to `previous-line', except that it always moves
6831 by logical lines instead of visual lines, ignoring the value of
6832 the variable `line-move-visual'."
6833 (interactive "^p\np")
6834 (let ((line-move-visual nil))
6835 (with-no-warnings
6836 (previous-line arg try-vscroll))))
6838 (defgroup visual-line nil
6839 "Editing based on visual lines."
6840 :group 'convenience
6841 :version "23.1")
6843 (defvar visual-line-mode-map
6844 (let ((map (make-sparse-keymap)))
6845 (define-key map [remap kill-line] 'kill-visual-line)
6846 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6847 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6848 ;; These keybindings interfere with xterm function keys. Are
6849 ;; there any other suitable bindings?
6850 ;; (define-key map "\M-[" 'previous-logical-line)
6851 ;; (define-key map "\M-]" 'next-logical-line)
6852 map))
6854 (defcustom visual-line-fringe-indicators '(nil nil)
6855 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6856 The value should be a list of the form (LEFT RIGHT), where LEFT
6857 and RIGHT are symbols representing the bitmaps to display, to
6858 indicate wrapped lines, in the left and right fringes respectively.
6859 See also `fringe-indicator-alist'.
6860 The default is not to display fringe indicators for wrapped lines.
6861 This variable does not affect fringe indicators displayed for
6862 other purposes."
6863 :type '(list (choice (const :tag "Hide left indicator" nil)
6864 (const :tag "Left curly arrow" left-curly-arrow)
6865 (symbol :tag "Other bitmap"))
6866 (choice (const :tag "Hide right indicator" nil)
6867 (const :tag "Right curly arrow" right-curly-arrow)
6868 (symbol :tag "Other bitmap")))
6869 :set (lambda (symbol value)
6870 (dolist (buf (buffer-list))
6871 (with-current-buffer buf
6872 (when (and (boundp 'visual-line-mode)
6873 (symbol-value 'visual-line-mode))
6874 (setq fringe-indicator-alist
6875 (cons (cons 'continuation value)
6876 (assq-delete-all
6877 'continuation
6878 (copy-tree fringe-indicator-alist)))))))
6879 (set-default symbol value)))
6881 (defvar visual-line--saved-state nil)
6883 (define-minor-mode visual-line-mode
6884 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6885 Interactively, with a prefix argument, enable
6886 Visual Line mode if the prefix argument is positive,
6887 and disable it otherwise. If called from Lisp, toggle
6888 the mode if ARG is `toggle', disable the mode if ARG is
6889 a non-positive integer, and enable the mode otherwise
6890 \(including if ARG is omitted or nil or a positive integer).
6892 When Visual Line mode is enabled, `word-wrap' is turned on in
6893 this buffer, and simple editing commands are redefined to act on
6894 visual lines, not logical lines. See Info node `Visual Line
6895 Mode' for details."
6896 :keymap visual-line-mode-map
6897 :group 'visual-line
6898 :lighter " Wrap"
6899 (if visual-line-mode
6900 (progn
6901 (set (make-local-variable 'visual-line--saved-state) nil)
6902 ;; Save the local values of some variables, to be restored if
6903 ;; visual-line-mode is turned off.
6904 (dolist (var '(line-move-visual truncate-lines
6905 truncate-partial-width-windows
6906 word-wrap fringe-indicator-alist))
6907 (if (local-variable-p var)
6908 (push (cons var (symbol-value var))
6909 visual-line--saved-state)))
6910 (set (make-local-variable 'line-move-visual) t)
6911 (set (make-local-variable 'truncate-partial-width-windows) nil)
6912 (setq truncate-lines nil
6913 word-wrap t
6914 fringe-indicator-alist
6915 (cons (cons 'continuation visual-line-fringe-indicators)
6916 fringe-indicator-alist)))
6917 (kill-local-variable 'line-move-visual)
6918 (kill-local-variable 'word-wrap)
6919 (kill-local-variable 'truncate-lines)
6920 (kill-local-variable 'truncate-partial-width-windows)
6921 (kill-local-variable 'fringe-indicator-alist)
6922 (dolist (saved visual-line--saved-state)
6923 (set (make-local-variable (car saved)) (cdr saved)))
6924 (kill-local-variable 'visual-line--saved-state)))
6926 (defun turn-on-visual-line-mode ()
6927 (visual-line-mode 1))
6929 (define-globalized-minor-mode global-visual-line-mode
6930 visual-line-mode turn-on-visual-line-mode)
6933 (defun transpose-chars (arg)
6934 "Interchange characters around point, moving forward one character.
6935 With prefix arg ARG, effect is to take character before point
6936 and drag it forward past ARG other characters (backward if ARG negative).
6937 If no argument and at end of line, the previous two chars are exchanged."
6938 (interactive "*P")
6939 (when (and (null arg) (eolp) (not (bobp))
6940 (not (get-text-property (1- (point)) 'read-only)))
6941 (forward-char -1))
6942 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6944 (defun transpose-words (arg)
6945 "Interchange words around point, leaving point at end of them.
6946 With prefix arg ARG, effect is to take word before or around point
6947 and drag it forward past ARG other words (backward if ARG negative).
6948 If ARG is zero, the words around or after point and around or after mark
6949 are interchanged."
6950 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6951 (interactive "*p")
6952 (transpose-subr 'forward-word arg))
6954 (defun transpose-sexps (arg)
6955 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6956 Unlike `transpose-words', point must be between the two sexps and not
6957 in the middle of a sexp to be transposed.
6958 With non-zero prefix arg ARG, effect is to take the sexp before point
6959 and drag it forward past ARG other sexps (backward if ARG is negative).
6960 If ARG is zero, the sexps ending at or after point and at or after mark
6961 are interchanged."
6962 (interactive "*p")
6963 (transpose-subr
6964 (lambda (arg)
6965 ;; Here we should try to simulate the behavior of
6966 ;; (cons (progn (forward-sexp x) (point))
6967 ;; (progn (forward-sexp (- x)) (point)))
6968 ;; Except that we don't want to rely on the second forward-sexp
6969 ;; putting us back to where we want to be, since forward-sexp-function
6970 ;; might do funny things like infix-precedence.
6971 (if (if (> arg 0)
6972 (looking-at "\\sw\\|\\s_")
6973 (and (not (bobp))
6974 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6975 ;; Jumping over a symbol. We might be inside it, mind you.
6976 (progn (funcall (if (> arg 0)
6977 'skip-syntax-backward 'skip-syntax-forward)
6978 "w_")
6979 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6980 ;; Otherwise, we're between sexps. Take a step back before jumping
6981 ;; to make sure we'll obey the same precedence no matter which direction
6982 ;; we're going.
6983 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6984 (cons (save-excursion (forward-sexp arg) (point))
6985 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6986 (not (zerop (funcall (if (> arg 0)
6987 'skip-syntax-forward
6988 'skip-syntax-backward)
6989 ".")))))
6990 (point)))))
6991 arg 'special))
6993 (defun transpose-lines (arg)
6994 "Exchange current line and previous line, leaving point after both.
6995 With argument ARG, takes previous line and moves it past ARG lines.
6996 With argument 0, interchanges line point is in with line mark is in."
6997 (interactive "*p")
6998 (transpose-subr (function
6999 (lambda (arg)
7000 (if (> arg 0)
7001 (progn
7002 ;; Move forward over ARG lines,
7003 ;; but create newlines if necessary.
7004 (setq arg (forward-line arg))
7005 (if (/= (preceding-char) ?\n)
7006 (setq arg (1+ arg)))
7007 (if (> arg 0)
7008 (newline arg)))
7009 (forward-line arg))))
7010 arg))
7012 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
7013 ;; which seems inconsistent with the ARG /= 0 case.
7014 ;; FIXME document SPECIAL.
7015 (defun transpose-subr (mover arg &optional special)
7016 "Subroutine to do the work of transposing objects.
7017 Works for lines, sentences, paragraphs, etc. MOVER is a function that
7018 moves forward by units of the given object (e.g. forward-sentence,
7019 forward-paragraph). If ARG is zero, exchanges the current object
7020 with the one containing mark. If ARG is an integer, moves the
7021 current object past ARG following (if ARG is positive) or
7022 preceding (if ARG is negative) objects, leaving point after the
7023 current object."
7024 (let ((aux (if special mover
7025 (lambda (x)
7026 (cons (progn (funcall mover x) (point))
7027 (progn (funcall mover (- x)) (point))))))
7028 pos1 pos2)
7029 (cond
7030 ((= arg 0)
7031 (save-excursion
7032 (setq pos1 (funcall aux 1))
7033 (goto-char (or (mark) (error "No mark set in this buffer")))
7034 (setq pos2 (funcall aux 1))
7035 (transpose-subr-1 pos1 pos2))
7036 (exchange-point-and-mark))
7037 ((> arg 0)
7038 (setq pos1 (funcall aux -1))
7039 (setq pos2 (funcall aux arg))
7040 (transpose-subr-1 pos1 pos2)
7041 (goto-char (car pos2)))
7043 (setq pos1 (funcall aux -1))
7044 (goto-char (car pos1))
7045 (setq pos2 (funcall aux arg))
7046 (transpose-subr-1 pos1 pos2)
7047 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
7049 (defun transpose-subr-1 (pos1 pos2)
7050 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
7051 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
7052 (when (> (car pos1) (car pos2))
7053 (let ((swap pos1))
7054 (setq pos1 pos2 pos2 swap)))
7055 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
7056 (atomic-change-group
7057 ;; This sequence of insertions attempts to preserve marker
7058 ;; positions at the start and end of the transposed objects.
7059 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
7060 (len1 (- (cdr pos1) (car pos1)))
7061 (len2 (length word))
7062 (boundary (make-marker)))
7063 (set-marker boundary (car pos2))
7064 (goto-char (cdr pos1))
7065 (insert-before-markers word)
7066 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
7067 (goto-char boundary)
7068 (insert word)
7069 (goto-char (+ boundary len1))
7070 (delete-region (point) (+ (point) len2))
7071 (set-marker boundary nil))))
7073 (defun backward-word (&optional arg)
7074 "Move backward until encountering the beginning of a word.
7075 With argument ARG, do this that many times.
7076 If ARG is omitted or nil, move point backward one word.
7078 The word boundaries are normally determined by the buffer's syntax
7079 table, but `find-word-boundary-function-table', such as set up
7080 by `subword-mode', can change that. If a Lisp program needs to
7081 move by words determined strictly by the syntax table, it should
7082 use `backward-word-strictly' instead."
7083 (interactive "^p")
7084 (forward-word (- (or arg 1))))
7086 (defun mark-word (&optional arg allow-extend)
7087 "Set mark ARG words away from point.
7088 The place mark goes is the same place \\[forward-word] would
7089 move to with the same argument.
7090 Interactively, if this command is repeated
7091 or (in Transient Mark mode) if the mark is active,
7092 it marks the next ARG words after the ones already marked."
7093 (interactive "P\np")
7094 (cond ((and allow-extend
7095 (or (and (eq last-command this-command) (mark t))
7096 (region-active-p)))
7097 (setq arg (if arg (prefix-numeric-value arg)
7098 (if (< (mark) (point)) -1 1)))
7099 (set-mark
7100 (save-excursion
7101 (goto-char (mark))
7102 (forward-word arg)
7103 (point))))
7105 (push-mark
7106 (save-excursion
7107 (forward-word (prefix-numeric-value arg))
7108 (point))
7109 nil t))))
7111 (defun kill-word (arg)
7112 "Kill characters forward until encountering the end of a word.
7113 With argument ARG, do this that many times."
7114 (interactive "p")
7115 (kill-region (point) (progn (forward-word arg) (point))))
7117 (defun backward-kill-word (arg)
7118 "Kill characters backward until encountering the beginning of a word.
7119 With argument ARG, do this that many times."
7120 (interactive "p")
7121 (kill-word (- arg)))
7123 (defun current-word (&optional strict really-word)
7124 "Return the word at or near point, as a string.
7125 The return value includes no text properties.
7127 If optional arg STRICT is non-nil, return nil unless point is
7128 within or adjacent to a word, otherwise look for a word within
7129 point's line. If there is no word anywhere on point's line, the
7130 value is nil regardless of STRICT.
7132 By default, this function treats as a single word any sequence of
7133 characters that have either word or symbol syntax. If optional
7134 arg REALLY-WORD is non-nil, only characters of word syntax can
7135 constitute a word."
7136 (save-excursion
7137 (let* ((oldpoint (point)) (start (point)) (end (point))
7138 (syntaxes (if really-word "w" "w_"))
7139 (not-syntaxes (concat "^" syntaxes)))
7140 (skip-syntax-backward syntaxes) (setq start (point))
7141 (goto-char oldpoint)
7142 (skip-syntax-forward syntaxes) (setq end (point))
7143 (when (and (eq start oldpoint) (eq end oldpoint)
7144 ;; Point is neither within nor adjacent to a word.
7145 (not strict))
7146 ;; Look for preceding word in same line.
7147 (skip-syntax-backward not-syntaxes (line-beginning-position))
7148 (if (bolp)
7149 ;; No preceding word in same line.
7150 ;; Look for following word in same line.
7151 (progn
7152 (skip-syntax-forward not-syntaxes (line-end-position))
7153 (setq start (point))
7154 (skip-syntax-forward syntaxes)
7155 (setq end (point)))
7156 (setq end (point))
7157 (skip-syntax-backward syntaxes)
7158 (setq start (point))))
7159 ;; If we found something nonempty, return it as a string.
7160 (unless (= start end)
7161 (buffer-substring-no-properties start end)))))
7163 (defcustom fill-prefix nil
7164 "String for filling to insert at front of new line, or nil for none."
7165 :type '(choice (const :tag "None" nil)
7166 string)
7167 :group 'fill)
7168 (make-variable-buffer-local 'fill-prefix)
7169 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7171 (defcustom auto-fill-inhibit-regexp nil
7172 "Regexp to match lines which should not be auto-filled."
7173 :type '(choice (const :tag "None" nil)
7174 regexp)
7175 :group 'fill)
7177 (defun do-auto-fill ()
7178 "The default value for `normal-auto-fill-function'.
7179 This is the default auto-fill function, some major modes use a different one.
7180 Returns t if it really did any work."
7181 (let (fc justify give-up
7182 (fill-prefix fill-prefix))
7183 (if (or (not (setq justify (current-justification)))
7184 (null (setq fc (current-fill-column)))
7185 (and (eq justify 'left)
7186 (<= (current-column) fc))
7187 (and auto-fill-inhibit-regexp
7188 (save-excursion (beginning-of-line)
7189 (looking-at auto-fill-inhibit-regexp))))
7190 nil ;; Auto-filling not required
7191 (if (memq justify '(full center right))
7192 (save-excursion (unjustify-current-line)))
7194 ;; Choose a fill-prefix automatically.
7195 (when (and adaptive-fill-mode
7196 (or (null fill-prefix) (string= fill-prefix "")))
7197 (let ((prefix
7198 (fill-context-prefix
7199 (save-excursion (fill-forward-paragraph -1) (point))
7200 (save-excursion (fill-forward-paragraph 1) (point)))))
7201 (and prefix (not (equal prefix ""))
7202 ;; Use auto-indentation rather than a guessed empty prefix.
7203 (not (and fill-indent-according-to-mode
7204 (string-match "\\`[ \t]*\\'" prefix)))
7205 (setq fill-prefix prefix))))
7207 (while (and (not give-up) (> (current-column) fc))
7208 ;; Determine where to split the line.
7209 (let ((fill-point
7210 (save-excursion
7211 (beginning-of-line)
7212 ;; Don't split earlier in the line than the length of the
7213 ;; fill prefix, since the resulting line would be longer.
7214 (when fill-prefix
7215 (move-to-column (string-width fill-prefix)))
7216 (let ((after-prefix (point)))
7217 (move-to-column (1+ fc))
7218 (fill-move-to-break-point after-prefix)
7219 (point)))))
7221 ;; See whether the place we found is any good.
7222 (if (save-excursion
7223 (goto-char fill-point)
7224 (or (bolp)
7225 ;; There is no use breaking at end of line.
7226 (save-excursion (skip-chars-forward " ") (eolp))
7227 ;; Don't split right after a comment starter
7228 ;; since we would just make another comment starter.
7229 (and comment-start-skip
7230 (let ((limit (point)))
7231 (beginning-of-line)
7232 (and (re-search-forward comment-start-skip
7233 limit t)
7234 (eq (point) limit))))))
7235 ;; No good place to break => stop trying.
7236 (setq give-up t)
7237 ;; Ok, we have a useful place to break the line. Do it.
7238 (let ((prev-column (current-column)))
7239 ;; If point is at the fill-point, do not `save-excursion'.
7240 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7241 ;; point will end up before it rather than after it.
7242 (if (save-excursion
7243 (skip-chars-backward " \t")
7244 (= (point) fill-point))
7245 (default-indent-new-line t)
7246 (save-excursion
7247 (goto-char fill-point)
7248 (default-indent-new-line t)))
7249 ;; Now do justification, if required
7250 (if (not (eq justify 'left))
7251 (save-excursion
7252 (end-of-line 0)
7253 (justify-current-line justify nil t)))
7254 ;; If making the new line didn't reduce the hpos of
7255 ;; the end of the line, then give up now;
7256 ;; trying again will not help.
7257 (if (>= (current-column) prev-column)
7258 (setq give-up t))))))
7259 ;; Justify last line.
7260 (justify-current-line justify t t)
7261 t)))
7263 (defvar comment-line-break-function 'comment-indent-new-line
7264 "Mode-specific function which line breaks and continues a comment.
7265 This function is called during auto-filling when a comment syntax
7266 is defined.
7267 The function should take a single optional argument, which is a flag
7268 indicating whether it should use soft newlines.")
7270 (defun default-indent-new-line (&optional soft)
7271 "Break line at point and indent.
7272 If a comment syntax is defined, call `comment-indent-new-line'.
7274 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7275 unless optional argument SOFT is non-nil."
7276 (interactive)
7277 (if comment-start
7278 (funcall comment-line-break-function soft)
7279 ;; Insert the newline before removing empty space so that markers
7280 ;; get preserved better.
7281 (if soft (insert-and-inherit ?\n) (newline 1))
7282 (save-excursion (forward-char -1) (delete-horizontal-space))
7283 (delete-horizontal-space)
7285 (if (and fill-prefix (not adaptive-fill-mode))
7286 ;; Blindly trust a non-adaptive fill-prefix.
7287 (progn
7288 (indent-to-left-margin)
7289 (insert-before-markers-and-inherit fill-prefix))
7291 (cond
7292 ;; If there's an adaptive prefix, use it unless we're inside
7293 ;; a comment and the prefix is not a comment starter.
7294 (fill-prefix
7295 (indent-to-left-margin)
7296 (insert-and-inherit fill-prefix))
7297 ;; If we're not inside a comment, just try to indent.
7298 (t (indent-according-to-mode))))))
7300 (defun internal-auto-fill ()
7301 "The function called by `self-insert-command' to perform auto-filling."
7302 (when (or (not comment-start)
7303 (not comment-auto-fill-only-comments)
7304 (nth 4 (syntax-ppss)))
7305 (funcall auto-fill-function)))
7307 (defvar normal-auto-fill-function 'do-auto-fill
7308 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7309 Some major modes set this.")
7311 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7312 ;; `functions' and `hooks' are usually unsafe to set, but setting
7313 ;; auto-fill-function to nil in a file-local setting is safe and
7314 ;; can be useful to prevent auto-filling.
7315 (put 'auto-fill-function 'safe-local-variable 'null)
7317 (define-minor-mode auto-fill-mode
7318 "Toggle automatic line breaking (Auto Fill mode).
7319 Interactively, with a prefix argument, enable
7320 Auto Fill mode if the prefix argument is positive,
7321 and disable it otherwise. If called from Lisp, toggle
7322 the mode if ARG is `toggle', disable the mode if ARG is
7323 a non-positive integer, and enable the mode otherwise
7324 \(including if ARG is omitted or nil or a positive integer).
7326 When Auto Fill mode is enabled, inserting a space at a column
7327 beyond `current-fill-column' automatically breaks the line at a
7328 previous space.
7330 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7331 non-nil.
7333 The value of `normal-auto-fill-function' specifies the function to use
7334 for `auto-fill-function' when turning Auto Fill mode on."
7335 :variable (auto-fill-function
7336 . (lambda (v) (setq auto-fill-function
7337 (if v normal-auto-fill-function)))))
7339 ;; This holds a document string used to document auto-fill-mode.
7340 (defun auto-fill-function ()
7341 "Automatically break line at a previous space, in insertion of text."
7342 nil)
7344 (defun turn-on-auto-fill ()
7345 "Unconditionally turn on Auto Fill mode."
7346 (auto-fill-mode 1))
7348 (defun turn-off-auto-fill ()
7349 "Unconditionally turn off Auto Fill mode."
7350 (auto-fill-mode -1))
7352 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7354 (defun set-fill-column (arg)
7355 "Set `fill-column' to specified argument.
7356 Use \\[universal-argument] followed by a number to specify a column.
7357 Just \\[universal-argument] as argument means to use the current column."
7358 (interactive
7359 (list (or current-prefix-arg
7360 ;; We used to use current-column silently, but C-x f is too easily
7361 ;; typed as a typo for C-x C-f, so we turned it into an error and
7362 ;; now an interactive prompt.
7363 (read-number "Set fill-column to: " (current-column)))))
7364 (if (consp arg)
7365 (setq arg (current-column)))
7366 (if (not (integerp arg))
7367 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7368 (error "set-fill-column requires an explicit argument")
7369 (message "Fill column set to %d (was %d)" arg fill-column)
7370 (setq fill-column arg)))
7372 (defun set-selective-display (arg)
7373 "Set `selective-display' to ARG; clear it if no arg.
7374 When the value of `selective-display' is a number > 0,
7375 lines whose indentation is >= that value are not displayed.
7376 The variable `selective-display' has a separate value for each buffer."
7377 (interactive "P")
7378 (if (eq selective-display t)
7379 (error "selective-display already in use for marked lines"))
7380 (let ((current-vpos
7381 (save-restriction
7382 (narrow-to-region (point-min) (point))
7383 (goto-char (window-start))
7384 (vertical-motion (window-height)))))
7385 (setq selective-display
7386 (and arg (prefix-numeric-value arg)))
7387 (recenter current-vpos))
7388 (set-window-start (selected-window) (window-start))
7389 (princ "selective-display set to " t)
7390 (prin1 selective-display t)
7391 (princ "." t))
7393 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7395 (defun toggle-truncate-lines (&optional arg)
7396 "Toggle truncating of long lines for the current buffer.
7397 When truncating is off, long lines are folded.
7398 With prefix argument ARG, truncate long lines if ARG is positive,
7399 otherwise fold them. Note that in side-by-side windows, this
7400 command has no effect if `truncate-partial-width-windows' is
7401 non-nil."
7402 (interactive "P")
7403 (setq truncate-lines
7404 (if (null arg)
7405 (not truncate-lines)
7406 (> (prefix-numeric-value arg) 0)))
7407 (force-mode-line-update)
7408 (unless truncate-lines
7409 (let ((buffer (current-buffer)))
7410 (walk-windows (lambda (window)
7411 (if (eq buffer (window-buffer window))
7412 (set-window-hscroll window 0)))
7413 nil t)))
7414 (message "Truncate long lines %s"
7415 (if truncate-lines "enabled" "disabled")))
7417 (defun toggle-word-wrap (&optional arg)
7418 "Toggle whether to use word-wrapping for continuation lines.
7419 With prefix argument ARG, wrap continuation lines at word boundaries
7420 if ARG is positive, otherwise wrap them at the right screen edge.
7421 This command toggles the value of `word-wrap'. It has no effect
7422 if long lines are truncated."
7423 (interactive "P")
7424 (setq word-wrap
7425 (if (null arg)
7426 (not word-wrap)
7427 (> (prefix-numeric-value arg) 0)))
7428 (force-mode-line-update)
7429 (message "Word wrapping %s"
7430 (if word-wrap "enabled" "disabled")))
7432 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7433 "The string displayed in the mode line when in overwrite mode.")
7434 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7435 "The string displayed in the mode line when in binary overwrite mode.")
7437 (define-minor-mode overwrite-mode
7438 "Toggle Overwrite mode.
7439 With a prefix argument ARG, enable Overwrite mode if ARG is
7440 positive, and disable it otherwise. If called from Lisp, enable
7441 the mode if ARG is omitted or nil.
7443 When Overwrite mode is enabled, printing characters typed in
7444 replace existing text on a one-for-one basis, rather than pushing
7445 it to the right. At the end of a line, such characters extend
7446 the line. Before a tab, such characters insert until the tab is
7447 filled in. \\[quoted-insert] still inserts characters in
7448 overwrite mode; this is supposed to make it easier to insert
7449 characters when necessary."
7450 :variable (overwrite-mode
7451 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7453 (define-minor-mode binary-overwrite-mode
7454 "Toggle Binary Overwrite mode.
7455 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7456 is positive, and disable it otherwise. If called from Lisp,
7457 enable the mode if ARG is omitted or nil.
7459 When Binary Overwrite mode is enabled, printing characters typed
7460 in replace existing text. Newlines are not treated specially, so
7461 typing at the end of a line joins the line to the next, with the
7462 typed character between them. Typing before a tab character
7463 simply replaces the tab with the character typed.
7464 \\[quoted-insert] replaces the text at the cursor, just as
7465 ordinary typing characters do.
7467 Note that Binary Overwrite mode is not its own minor mode; it is
7468 a specialization of overwrite mode, entered by setting the
7469 `overwrite-mode' variable to `overwrite-mode-binary'."
7470 :variable (overwrite-mode
7471 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7473 (define-minor-mode line-number-mode
7474 "Toggle line number display in the mode line (Line Number mode).
7475 With a prefix argument ARG, enable Line Number mode if ARG is
7476 positive, and disable it otherwise. If called from Lisp, enable
7477 the mode if ARG is omitted or nil.
7479 Line numbers do not appear for very large buffers and buffers
7480 with very long lines; see variables `line-number-display-limit'
7481 and `line-number-display-limit-width'."
7482 :init-value t :global t :group 'mode-line)
7484 (define-minor-mode column-number-mode
7485 "Toggle column number display in the mode line (Column Number mode).
7486 With a prefix argument ARG, enable Column Number mode if ARG is
7487 positive, and disable it otherwise.
7489 If called from Lisp, enable the mode if ARG is omitted or nil."
7490 :global t :group 'mode-line)
7492 (define-minor-mode size-indication-mode
7493 "Toggle buffer size display in the mode line (Size Indication mode).
7494 With a prefix argument ARG, enable Size Indication mode if ARG is
7495 positive, and disable it otherwise.
7497 If called from Lisp, enable the mode if ARG is omitted or nil."
7498 :global t :group 'mode-line)
7500 (define-minor-mode auto-save-mode
7501 "Toggle auto-saving in the current buffer (Auto Save mode).
7502 With a prefix argument ARG, enable Auto Save mode if ARG is
7503 positive, and disable it otherwise.
7505 If called from Lisp, enable the mode if ARG is omitted or nil."
7506 :variable ((and buffer-auto-save-file-name
7507 ;; If auto-save is off because buffer has shrunk,
7508 ;; then toggling should turn it on.
7509 (>= buffer-saved-size 0))
7510 . (lambda (val)
7511 (setq buffer-auto-save-file-name
7512 (cond
7513 ((null val) nil)
7514 ((and buffer-file-name auto-save-visited-file-name
7515 (not buffer-read-only))
7516 buffer-file-name)
7517 (t (make-auto-save-file-name))))))
7518 ;; If -1 was stored here, to temporarily turn off saving,
7519 ;; turn it back on.
7520 (and (< buffer-saved-size 0)
7521 (setq buffer-saved-size 0)))
7523 (defgroup paren-blinking nil
7524 "Blinking matching of parens and expressions."
7525 :prefix "blink-matching-"
7526 :group 'paren-matching)
7528 (defcustom blink-matching-paren t
7529 "Non-nil means show matching open-paren when close-paren is inserted.
7530 If t, highlight the paren. If `jump', briefly move cursor to its
7531 position. If `jump-offscreen', move cursor there even if the
7532 position is off screen. With any other non-nil value, the
7533 off-screen position of the opening paren will be shown in the
7534 echo area."
7535 :type '(choice
7536 (const :tag "Disable" nil)
7537 (const :tag "Highlight" t)
7538 (const :tag "Move cursor" jump)
7539 (const :tag "Move cursor, even if off screen" jump-offscreen))
7540 :group 'paren-blinking)
7542 (defcustom blink-matching-paren-on-screen t
7543 "Non-nil means show matching open-paren when it is on screen.
7544 If nil, don't show it (but the open-paren can still be shown
7545 in the echo area when it is off screen).
7547 This variable has no effect if `blink-matching-paren' is nil.
7548 \(In that case, the open-paren is never shown.)
7549 It is also ignored if `show-paren-mode' is enabled."
7550 :type 'boolean
7551 :group 'paren-blinking)
7553 (defcustom blink-matching-paren-distance (* 100 1024)
7554 "If non-nil, maximum distance to search backwards for matching open-paren.
7555 If nil, search stops at the beginning of the accessible portion of the buffer."
7556 :version "23.2" ; 25->100k
7557 :type '(choice (const nil) integer)
7558 :group 'paren-blinking)
7560 (defcustom blink-matching-delay 1
7561 "Time in seconds to delay after showing a matching paren."
7562 :type 'number
7563 :group 'paren-blinking)
7565 (defcustom blink-matching-paren-dont-ignore-comments nil
7566 "If nil, `blink-matching-paren' ignores comments.
7567 More precisely, when looking for the matching parenthesis,
7568 it skips the contents of comments that end before point."
7569 :type 'boolean
7570 :group 'paren-blinking)
7572 (defun blink-matching-check-mismatch (start end)
7573 "Return whether or not START...END are matching parens.
7574 END is the current point and START is the blink position.
7575 START might be nil if no matching starter was found.
7576 Returns non-nil if we find there is a mismatch."
7577 (let* ((end-syntax (syntax-after (1- end)))
7578 (matching-paren (and (consp end-syntax)
7579 (eq (syntax-class end-syntax) 5)
7580 (cdr end-syntax))))
7581 ;; For self-matched chars like " and $, we can't know when they're
7582 ;; mismatched or unmatched, so we can only do it for parens.
7583 (when matching-paren
7584 (not (and start
7586 (eq (char-after start) matching-paren)
7587 ;; The cdr might hold a new paren-class info rather than
7588 ;; a matching-char info, in which case the two CDRs
7589 ;; should match.
7590 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7592 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7593 "Function to check parentheses mismatches.
7594 The function takes two arguments (START and END) where START is the
7595 position just before the opening token and END is the position right after.
7596 START can be nil, if it was not found.
7597 The function should return non-nil if the two tokens do not match.")
7599 (defvar blink-matching--overlay
7600 (let ((ol (make-overlay (point) (point) nil t)))
7601 (overlay-put ol 'face 'show-paren-match)
7602 (delete-overlay ol)
7604 "Overlay used to highlight the matching paren.")
7606 (defun blink-matching-open ()
7607 "Momentarily highlight the beginning of the sexp before point."
7608 (interactive)
7609 (when (and (not (bobp))
7610 blink-matching-paren)
7611 (let* ((oldpos (point))
7612 (message-log-max nil) ; Don't log messages about paren matching.
7613 (blinkpos
7614 (save-excursion
7615 (save-restriction
7616 (if blink-matching-paren-distance
7617 (narrow-to-region
7618 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7619 (- (point) blink-matching-paren-distance))
7620 oldpos))
7621 (let ((parse-sexp-ignore-comments
7622 (and parse-sexp-ignore-comments
7623 (not blink-matching-paren-dont-ignore-comments))))
7624 (condition-case ()
7625 (progn
7626 (syntax-propertize (point))
7627 (forward-sexp -1)
7628 ;; backward-sexp skips backward over prefix chars,
7629 ;; so move back to the matching paren.
7630 (while (and (< (point) (1- oldpos))
7631 (let ((code (syntax-after (point))))
7632 (or (eq (syntax-class code) 6)
7633 (eq (logand 1048576 (car code))
7634 1048576))))
7635 (forward-char 1))
7636 (point))
7637 (error nil))))))
7638 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7639 (cond
7640 (mismatch
7641 (if blinkpos
7642 (if (minibufferp)
7643 (minibuffer-message "Mismatched parentheses")
7644 (message "Mismatched parentheses"))
7645 (if (minibufferp)
7646 (minibuffer-message "No matching parenthesis found")
7647 (message "No matching parenthesis found"))))
7648 ((not blinkpos) nil)
7649 ((or
7650 (eq blink-matching-paren 'jump-offscreen)
7651 (pos-visible-in-window-p blinkpos))
7652 ;; Matching open within window, temporarily move to or highlight
7653 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7654 ;; is non-nil.
7655 (and blink-matching-paren-on-screen
7656 (not show-paren-mode)
7657 (if (memq blink-matching-paren '(jump jump-offscreen))
7658 (save-excursion
7659 (goto-char blinkpos)
7660 (sit-for blink-matching-delay))
7661 (unwind-protect
7662 (progn
7663 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7664 (current-buffer))
7665 (sit-for blink-matching-delay))
7666 (delete-overlay blink-matching--overlay)))))
7668 (let ((open-paren-line-string
7669 (save-excursion
7670 (goto-char blinkpos)
7671 ;; Show what precedes the open in its line, if anything.
7672 (cond
7673 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7674 (buffer-substring (line-beginning-position)
7675 (1+ blinkpos)))
7676 ;; Show what follows the open in its line, if anything.
7677 ((save-excursion
7678 (forward-char 1)
7679 (skip-chars-forward " \t")
7680 (not (eolp)))
7681 (buffer-substring blinkpos
7682 (line-end-position)))
7683 ;; Otherwise show the previous nonblank line,
7684 ;; if there is one.
7685 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7686 (concat
7687 (buffer-substring (progn
7688 (skip-chars-backward "\n \t")
7689 (line-beginning-position))
7690 (progn (end-of-line)
7691 (skip-chars-backward " \t")
7692 (point)))
7693 ;; Replace the newline and other whitespace with `...'.
7694 "..."
7695 (buffer-substring blinkpos (1+ blinkpos))))
7696 ;; There is nothing to show except the char itself.
7697 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7698 (minibuffer-message
7699 "Matches %s"
7700 (substring-no-properties open-paren-line-string))))))))
7702 (defvar blink-paren-function 'blink-matching-open
7703 "Function called, if non-nil, whenever a close parenthesis is inserted.
7704 More precisely, a char with closeparen syntax is self-inserted.")
7706 (defun blink-paren-post-self-insert-function ()
7707 (when (and (eq (char-before) last-command-event) ; Sanity check.
7708 (memq (char-syntax last-command-event) '(?\) ?\$))
7709 blink-paren-function
7710 (not executing-kbd-macro)
7711 (not noninteractive)
7712 ;; Verify an even number of quoting characters precede the close.
7713 ;; FIXME: Also check if this parenthesis closes a comment as
7714 ;; can happen in Pascal and SML.
7715 (= 1 (logand 1 (- (point)
7716 (save-excursion
7717 (forward-char -1)
7718 (skip-syntax-backward "/\\")
7719 (point))))))
7720 (funcall blink-paren-function)))
7722 (put 'blink-paren-post-self-insert-function 'priority 100)
7724 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7725 ;; Most likely, this hook is nil, so this arg doesn't matter,
7726 ;; but I use it as a reminder that this function usually
7727 ;; likes to be run after others since it does
7728 ;; `sit-for'. That's also the reason it get a `priority' prop
7729 ;; of 100.
7730 'append)
7732 ;; This executes C-g typed while Emacs is waiting for a command.
7733 ;; Quitting out of a program does not go through here;
7734 ;; that happens in the maybe_quit function at the C code level.
7735 (defun keyboard-quit ()
7736 "Signal a `quit' condition.
7737 During execution of Lisp code, this character causes a quit directly.
7738 At top-level, as an editor command, this simply beeps."
7739 (interactive)
7740 ;; Avoid adding the region to the window selection.
7741 (setq saved-region-selection nil)
7742 (let (select-active-regions)
7743 (deactivate-mark))
7744 (if (fboundp 'kmacro-keyboard-quit)
7745 (kmacro-keyboard-quit))
7746 (when completion-in-region-mode
7747 (completion-in-region-mode -1))
7748 ;; Force the next redisplay cycle to remove the "Def" indicator from
7749 ;; all the mode lines.
7750 (if defining-kbd-macro
7751 (force-mode-line-update t))
7752 (setq defining-kbd-macro nil)
7753 (let ((debug-on-quit nil))
7754 (signal 'quit nil)))
7756 (defvar buffer-quit-function nil
7757 "Function to call to \"quit\" the current buffer, or nil if none.
7758 \\[keyboard-escape-quit] calls this function when its more local actions
7759 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7761 (defun keyboard-escape-quit ()
7762 "Exit the current \"mode\" (in a generalized sense of the word).
7763 This command can exit an interactive command such as `query-replace',
7764 can clear out a prefix argument or a region,
7765 can get out of the minibuffer or other recursive edit,
7766 cancel the use of the current buffer (for special-purpose buffers),
7767 or go back to just one window (by deleting all but the selected window)."
7768 (interactive)
7769 (cond ((eq last-command 'mode-exited) nil)
7770 ((region-active-p)
7771 (deactivate-mark))
7772 ((> (minibuffer-depth) 0)
7773 (abort-recursive-edit))
7774 (current-prefix-arg
7775 nil)
7776 ((> (recursion-depth) 0)
7777 (exit-recursive-edit))
7778 (buffer-quit-function
7779 (funcall buffer-quit-function))
7780 ((not (one-window-p t))
7781 (delete-other-windows))
7782 ((string-match "^ \\*" (buffer-name (current-buffer)))
7783 (bury-buffer))))
7785 (defun play-sound-file (file &optional volume device)
7786 "Play sound stored in FILE.
7787 VOLUME and DEVICE correspond to the keywords of the sound
7788 specification for `play-sound'."
7789 (interactive "fPlay sound file: ")
7790 (let ((sound (list :file file)))
7791 (if volume
7792 (plist-put sound :volume volume))
7793 (if device
7794 (plist-put sound :device device))
7795 (push 'sound sound)
7796 (play-sound sound)))
7799 (defcustom read-mail-command 'rmail
7800 "Your preference for a mail reading package.
7801 This is used by some keybindings which support reading mail.
7802 See also `mail-user-agent' concerning sending mail."
7803 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7804 (function-item :tag "Gnus" :format "%t\n" gnus)
7805 (function-item :tag "Emacs interface to MH"
7806 :format "%t\n" mh-rmail)
7807 (function :tag "Other"))
7808 :version "21.1"
7809 :group 'mail)
7811 (defcustom mail-user-agent 'message-user-agent
7812 "Your preference for a mail composition package.
7813 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7814 outgoing email message. This variable lets you specify which
7815 mail-sending package you prefer.
7817 Valid values include:
7819 `message-user-agent' -- use the Message package.
7820 See Info node `(message)'.
7821 `sendmail-user-agent' -- use the Mail package.
7822 See Info node `(emacs)Sending Mail'.
7823 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7824 See Info node `(mh-e)'.
7825 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7826 paraphernalia if Gnus is running, particularly
7827 the Gcc: header for archiving.
7829 Additional valid symbols may be available; check with the author of
7830 your package for details. The function should return non-nil if it
7831 succeeds.
7833 See also `read-mail-command' concerning reading mail."
7834 :type '(radio (function-item :tag "Message package"
7835 :format "%t\n"
7836 message-user-agent)
7837 (function-item :tag "Mail package"
7838 :format "%t\n"
7839 sendmail-user-agent)
7840 (function-item :tag "Emacs interface to MH"
7841 :format "%t\n"
7842 mh-e-user-agent)
7843 (function-item :tag "Message with full Gnus features"
7844 :format "%t\n"
7845 gnus-user-agent)
7846 (function :tag "Other"))
7847 :version "23.2" ; sendmail->message
7848 :group 'mail)
7850 (defcustom compose-mail-user-agent-warnings t
7851 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7852 If the value of `mail-user-agent' is the default, and the user
7853 appears to have customizations applying to the old default,
7854 `compose-mail' issues a warning."
7855 :type 'boolean
7856 :version "23.2"
7857 :group 'mail)
7859 (defun rfc822-goto-eoh ()
7860 "If the buffer starts with a mail header, move point to the header's end.
7861 Otherwise, moves to `point-min'.
7862 The end of the header is the start of the next line, if there is one,
7863 else the end of the last line. This function obeys RFC822."
7864 (goto-char (point-min))
7865 (when (re-search-forward
7866 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7867 (goto-char (match-beginning 0))))
7869 ;; Used by Rmail (e.g., rmail-forward).
7870 (defvar mail-encode-mml nil
7871 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7872 the outgoing message before sending it.")
7874 (defun compose-mail (&optional to subject other-headers continue
7875 switch-function yank-action send-actions
7876 return-action)
7877 "Start composing a mail message to send.
7878 This uses the user's chosen mail composition package
7879 as selected with the variable `mail-user-agent'.
7880 The optional arguments TO and SUBJECT specify recipients
7881 and the initial Subject field, respectively.
7883 OTHER-HEADERS is an alist specifying additional
7884 header fields. Elements look like (HEADER . VALUE) where both
7885 HEADER and VALUE are strings.
7887 CONTINUE, if non-nil, says to continue editing a message already
7888 being composed. Interactively, CONTINUE is the prefix argument.
7890 SWITCH-FUNCTION, if non-nil, is a function to use to
7891 switch to and display the buffer used for mail composition.
7893 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7894 to insert the raw text of the message being replied to.
7895 It has the form (FUNCTION . ARGS). The user agent will apply
7896 FUNCTION to ARGS, to insert the raw text of the original message.
7897 \(The user agent will also run `mail-citation-hook', *after* the
7898 original text has been inserted in this way.)
7900 SEND-ACTIONS is a list of actions to call when the message is sent.
7901 Each action has the form (FUNCTION . ARGS).
7903 RETURN-ACTION, if non-nil, is an action for returning to the
7904 caller. It has the form (FUNCTION . ARGS). The function is
7905 called after the mail has been sent or put aside, and the mail
7906 buffer buried."
7907 (interactive
7908 (list nil nil nil current-prefix-arg))
7910 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7911 ;; from sendmail-user-agent to message-user-agent. Some users may
7912 ;; encounter incompatibilities. This hack tries to detect problems
7913 ;; and warn about them.
7914 (and compose-mail-user-agent-warnings
7915 (eq mail-user-agent 'message-user-agent)
7916 (let (warn-vars)
7917 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7918 mail-citation-hook mail-archive-file-name
7919 mail-default-reply-to mail-mailing-lists
7920 mail-self-blind))
7921 (and (boundp var)
7922 (symbol-value var)
7923 (push var warn-vars)))
7924 (when warn-vars
7925 (display-warning 'mail
7926 (format-message "\
7927 The default mail mode is now Message mode.
7928 You have the following Mail mode variable%s customized:
7929 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7930 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7931 (if (> (length warn-vars) 1) "s" "")
7932 (mapconcat 'symbol-name
7933 warn-vars " "))))))
7935 (let ((function (get mail-user-agent 'composefunc)))
7936 (funcall function to subject other-headers continue switch-function
7937 yank-action send-actions return-action)))
7939 (defun compose-mail-other-window (&optional to subject other-headers continue
7940 yank-action send-actions
7941 return-action)
7942 "Like \\[compose-mail], but edit the outgoing message in another window."
7943 (interactive (list nil nil nil current-prefix-arg))
7944 (compose-mail to subject other-headers continue
7945 'switch-to-buffer-other-window yank-action send-actions
7946 return-action))
7948 (defun compose-mail-other-frame (&optional to subject other-headers continue
7949 yank-action send-actions
7950 return-action)
7951 "Like \\[compose-mail], but edit the outgoing message in another frame."
7952 (interactive (list nil nil nil current-prefix-arg))
7953 (compose-mail to subject other-headers continue
7954 'switch-to-buffer-other-frame yank-action send-actions
7955 return-action))
7958 (defvar set-variable-value-history nil
7959 "History of values entered with `set-variable'.
7961 Maximum length of the history list is determined by the value
7962 of `history-length', which see.")
7964 (defun set-variable (variable value &optional make-local)
7965 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7966 VARIABLE should be a user option variable name, a Lisp variable
7967 meant to be customized by users. You should enter VALUE in Lisp syntax,
7968 so if you want VALUE to be a string, you must surround it with doublequotes.
7969 VALUE is used literally, not evaluated.
7971 If VARIABLE has a `variable-interactive' property, that is used as if
7972 it were the arg to `interactive' (which see) to interactively read VALUE.
7974 If VARIABLE has been defined with `defcustom', then the type information
7975 in the definition is used to check that VALUE is valid.
7977 Note that this function is at heart equivalent to the basic `set' function.
7978 For a variable defined with `defcustom', it does not pay attention to
7979 any :set property that the variable might have (if you want that, use
7980 \\[customize-set-variable] instead).
7982 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7983 (interactive
7984 (let* ((default-var (variable-at-point))
7985 (var (if (custom-variable-p default-var)
7986 (read-variable (format "Set variable (default %s): " default-var)
7987 default-var)
7988 (read-variable "Set variable: ")))
7989 (minibuffer-help-form '(describe-variable var))
7990 (prop (get var 'variable-interactive))
7991 (obsolete (car (get var 'byte-obsolete-variable)))
7992 (prompt (format "Set %s %s to value: " var
7993 (cond ((local-variable-p var)
7994 "(buffer-local)")
7995 ((or current-prefix-arg
7996 (local-variable-if-set-p var))
7997 "buffer-locally")
7998 (t "globally"))))
7999 (val (progn
8000 (when obsolete
8001 (message (concat "`%S' is obsolete; "
8002 (if (symbolp obsolete) "use `%S' instead" "%s"))
8003 var obsolete)
8004 (sit-for 3))
8005 (if prop
8006 ;; Use VAR's `variable-interactive' property
8007 ;; as an interactive spec for prompting.
8008 (call-interactively `(lambda (arg)
8009 (interactive ,prop)
8010 arg))
8011 (read-from-minibuffer prompt nil
8012 read-expression-map t
8013 'set-variable-value-history
8014 (format "%S" (symbol-value var)))))))
8015 (list var val current-prefix-arg)))
8017 (and (custom-variable-p variable)
8018 (not (get variable 'custom-type))
8019 (custom-load-symbol variable))
8020 (let ((type (get variable 'custom-type)))
8021 (when type
8022 ;; Match with custom type.
8023 (require 'cus-edit)
8024 (setq type (widget-convert type))
8025 (unless (widget-apply type :match value)
8026 (user-error "Value `%S' does not match type %S of %S"
8027 value (car type) variable))))
8029 (if make-local
8030 (make-local-variable variable))
8032 (set variable value)
8034 ;; Force a thorough redisplay for the case that the variable
8035 ;; has an effect on the display, like `tab-width' has.
8036 (force-mode-line-update))
8038 ;; Define the major mode for lists of completions.
8040 (defvar completion-list-mode-map
8041 (let ((map (make-sparse-keymap)))
8042 (define-key map [mouse-2] 'choose-completion)
8043 (define-key map [follow-link] 'mouse-face)
8044 (define-key map [down-mouse-2] nil)
8045 (define-key map "\C-m" 'choose-completion)
8046 (define-key map "\e\e\e" 'delete-completion-window)
8047 (define-key map [left] 'previous-completion)
8048 (define-key map [right] 'next-completion)
8049 (define-key map [?\t] 'next-completion)
8050 (define-key map [backtab] 'previous-completion)
8051 (define-key map "q" 'quit-window)
8052 (define-key map "z" 'kill-current-buffer)
8053 map)
8054 "Local map for completion list buffers.")
8056 ;; Completion mode is suitable only for specially formatted data.
8057 (put 'completion-list-mode 'mode-class 'special)
8059 (defvar completion-reference-buffer nil
8060 "Record the buffer that was current when the completion list was requested.
8061 This is a local variable in the completion list buffer.
8062 Initial value is nil to avoid some compiler warnings.")
8064 (defvar completion-no-auto-exit nil
8065 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8066 This also applies to other functions such as `choose-completion'.")
8068 (defvar completion-base-position nil
8069 "Position of the base of the text corresponding to the shown completions.
8070 This variable is used in the *Completions* buffers.
8071 Its value is a list of the form (START END) where START is the place
8072 where the completion should be inserted and END (if non-nil) is the end
8073 of the text to replace. If END is nil, point is used instead.")
8075 (defvar completion-list-insert-choice-function #'completion--replace
8076 "Function to use to insert the text chosen in *Completions*.
8077 Called with three arguments (BEG END TEXT), it should replace the text
8078 between BEG and END with TEXT. Expected to be set buffer-locally
8079 in the *Completions* buffer.")
8081 (defvar completion-base-size nil
8082 "Number of chars before point not involved in completion.
8083 This is a local variable in the completion list buffer.
8084 It refers to the chars in the minibuffer if completing in the
8085 minibuffer, or in `completion-reference-buffer' otherwise.
8086 Only characters in the field at point are included.
8088 If nil, Emacs determines which part of the tail end of the
8089 buffer's text is involved in completion by comparing the text
8090 directly.")
8091 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8093 (defun delete-completion-window ()
8094 "Delete the completion list window.
8095 Go to the window from which completion was requested."
8096 (interactive)
8097 (let ((buf completion-reference-buffer))
8098 (if (one-window-p t)
8099 (if (window-dedicated-p) (delete-frame))
8100 (delete-window (selected-window))
8101 (if (get-buffer-window buf)
8102 (select-window (get-buffer-window buf))))))
8104 (defun previous-completion (n)
8105 "Move to the previous item in the completion list."
8106 (interactive "p")
8107 (next-completion (- n)))
8109 (defun next-completion (n)
8110 "Move to the next item in the completion list.
8111 With prefix argument N, move N items (negative N means move backward)."
8112 (interactive "p")
8113 (let ((beg (point-min)) (end (point-max)))
8114 (while (and (> n 0) (not (eobp)))
8115 ;; If in a completion, move to the end of it.
8116 (when (get-text-property (point) 'mouse-face)
8117 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8118 ;; Move to start of next one.
8119 (unless (get-text-property (point) 'mouse-face)
8120 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8121 (setq n (1- n)))
8122 (while (and (< n 0) (not (bobp)))
8123 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8124 ;; If in a completion, move to the start of it.
8125 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8126 (goto-char (previous-single-property-change
8127 (point) 'mouse-face nil beg)))
8128 ;; Move to end of the previous completion.
8129 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8130 (goto-char (previous-single-property-change
8131 (point) 'mouse-face nil beg)))
8132 ;; Move to the start of that one.
8133 (goto-char (previous-single-property-change
8134 (point) 'mouse-face nil beg))
8135 (setq n (1+ n))))))
8137 (defun choose-completion (&optional event)
8138 "Choose the completion at point.
8139 If EVENT, use EVENT's position to determine the starting position."
8140 (interactive (list last-nonmenu-event))
8141 ;; In case this is run via the mouse, give temporary modes such as
8142 ;; isearch a chance to turn off.
8143 (run-hooks 'mouse-leave-buffer-hook)
8144 (with-current-buffer (window-buffer (posn-window (event-start event)))
8145 (let ((buffer completion-reference-buffer)
8146 (base-size completion-base-size)
8147 (base-position completion-base-position)
8148 (insert-function completion-list-insert-choice-function)
8149 (choice
8150 (save-excursion
8151 (goto-char (posn-point (event-start event)))
8152 (let (beg end)
8153 (cond
8154 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8155 (setq end (point) beg (1+ (point))))
8156 ((and (not (bobp))
8157 (get-text-property (1- (point)) 'mouse-face))
8158 (setq end (1- (point)) beg (point)))
8159 (t (error "No completion here")))
8160 (setq beg (previous-single-property-change beg 'mouse-face))
8161 (setq end (or (next-single-property-change end 'mouse-face)
8162 (point-max)))
8163 (buffer-substring-no-properties beg end)))))
8165 (unless (buffer-live-p buffer)
8166 (error "Destination buffer is dead"))
8167 (quit-window nil (posn-window (event-start event)))
8169 (with-current-buffer buffer
8170 (choose-completion-string
8171 choice buffer
8172 (or base-position
8173 (when base-size
8174 ;; Someone's using old completion code that doesn't know
8175 ;; about base-position yet.
8176 (list (+ base-size (field-beginning))))
8177 ;; If all else fails, just guess.
8178 (list (choose-completion-guess-base-position choice)))
8179 insert-function)))))
8181 ;; Delete the longest partial match for STRING
8182 ;; that can be found before POINT.
8183 (defun choose-completion-guess-base-position (string)
8184 (save-excursion
8185 (let ((opoint (point))
8186 len)
8187 ;; Try moving back by the length of the string.
8188 (goto-char (max (- (point) (length string))
8189 (minibuffer-prompt-end)))
8190 ;; See how far back we were actually able to move. That is the
8191 ;; upper bound on how much we can match and delete.
8192 (setq len (- opoint (point)))
8193 (if completion-ignore-case
8194 (setq string (downcase string)))
8195 (while (and (> len 0)
8196 (let ((tail (buffer-substring (point) opoint)))
8197 (if completion-ignore-case
8198 (setq tail (downcase tail)))
8199 (not (string= tail (substring string 0 len)))))
8200 (setq len (1- len))
8201 (forward-char 1))
8202 (point))))
8204 (defun choose-completion-delete-max-match (string)
8205 (declare (obsolete choose-completion-guess-base-position "23.2"))
8206 (delete-region (choose-completion-guess-base-position string) (point)))
8208 (defvar choose-completion-string-functions nil
8209 "Functions that may override the normal insertion of a completion choice.
8210 These functions are called in order with three arguments:
8211 CHOICE - the string to insert in the buffer,
8212 BUFFER - the buffer in which the choice should be inserted,
8213 BASE-POSITION - where to insert the completion.
8215 If a function in the list returns non-nil, that function is supposed
8216 to have inserted the CHOICE in the BUFFER, and possibly exited
8217 the minibuffer; no further functions will be called.
8219 If all functions in the list return nil, that means to use
8220 the default method of inserting the completion in BUFFER.")
8222 (defun choose-completion-string (choice &optional
8223 buffer base-position insert-function)
8224 "Switch to BUFFER and insert the completion choice CHOICE.
8225 BASE-POSITION says where to insert the completion.
8226 INSERT-FUNCTION says how to insert the completion and falls
8227 back on `completion-list-insert-choice-function' when nil."
8229 ;; If BUFFER is the minibuffer, exit the minibuffer
8230 ;; unless it is reading a file name and CHOICE is a directory,
8231 ;; or completion-no-auto-exit is non-nil.
8233 ;; Some older code may call us passing `base-size' instead of
8234 ;; `base-position'. It's difficult to make any use of `base-size',
8235 ;; so we just ignore it.
8236 (unless (consp base-position)
8237 (message "Obsolete `base-size' passed to choose-completion-string")
8238 (setq base-position nil))
8240 (let* ((buffer (or buffer completion-reference-buffer))
8241 (mini-p (minibufferp buffer)))
8242 ;; If BUFFER is a minibuffer, barf unless it's the currently
8243 ;; active minibuffer.
8244 (if (and mini-p
8245 (not (and (active-minibuffer-window)
8246 (equal buffer
8247 (window-buffer (active-minibuffer-window))))))
8248 (error "Minibuffer is not active for completion")
8249 ;; Set buffer so buffer-local choose-completion-string-functions works.
8250 (set-buffer buffer)
8251 (unless (run-hook-with-args-until-success
8252 'choose-completion-string-functions
8253 ;; The fourth arg used to be `mini-p' but was useless
8254 ;; (since minibufferp can be used on the `buffer' arg)
8255 ;; and indeed unused. The last used to be `base-size', so we
8256 ;; keep it to try and avoid breaking old code.
8257 choice buffer base-position nil)
8258 ;; This remove-text-properties should be unnecessary since `choice'
8259 ;; comes from buffer-substring-no-properties.
8260 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8261 ;; Insert the completion into the buffer where it was requested.
8262 (funcall (or insert-function completion-list-insert-choice-function)
8263 (or (car base-position) (point))
8264 (or (cadr base-position) (point))
8265 choice)
8266 ;; Update point in the window that BUFFER is showing in.
8267 (let ((window (get-buffer-window buffer t)))
8268 (set-window-point window (point)))
8269 ;; If completing for the minibuffer, exit it with this choice.
8270 (and (not completion-no-auto-exit)
8271 (minibufferp buffer)
8272 minibuffer-completion-table
8273 ;; If this is reading a file name, and the file name chosen
8274 ;; is a directory, don't exit the minibuffer.
8275 (let* ((result (buffer-substring (field-beginning) (point)))
8276 (bounds
8277 (completion-boundaries result minibuffer-completion-table
8278 minibuffer-completion-predicate
8279 "")))
8280 (if (eq (car bounds) (length result))
8281 ;; The completion chosen leads to a new set of completions
8282 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8283 (let ((mini (active-minibuffer-window)))
8284 (select-window mini)
8285 (when minibuffer-auto-raise
8286 (raise-frame (window-frame mini))))
8287 (exit-minibuffer))))))))
8289 (define-derived-mode completion-list-mode nil "Completion List"
8290 "Major mode for buffers showing lists of possible completions.
8291 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8292 to select the completion near point.
8293 Or click to select one with the mouse.
8295 \\{completion-list-mode-map}"
8296 (set (make-local-variable 'completion-base-size) nil))
8298 (defun completion-list-mode-finish ()
8299 "Finish setup of the completions buffer.
8300 Called from `temp-buffer-show-hook'."
8301 (when (eq major-mode 'completion-list-mode)
8302 (setq buffer-read-only t)))
8304 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8307 ;; Variables and faces used in `completion-setup-function'.
8309 (defcustom completion-show-help t
8310 "Non-nil means show help message in *Completions* buffer."
8311 :type 'boolean
8312 :version "22.1"
8313 :group 'completion)
8315 ;; This function goes in completion-setup-hook, so that it is called
8316 ;; after the text of the completion list buffer is written.
8317 (defun completion-setup-function ()
8318 (let* ((mainbuf (current-buffer))
8319 (base-dir
8320 ;; FIXME: This is a bad hack. We try to set the default-directory
8321 ;; in the *Completions* buffer so that the relative file names
8322 ;; displayed there can be treated as valid file names, independently
8323 ;; from the completion context. But this suffers from many problems:
8324 ;; - It's not clear when the completions are file names. With some
8325 ;; completion tables (e.g. bzr revision specs), the listed
8326 ;; completions can mix file names and other things.
8327 ;; - It doesn't pay attention to possible quoting.
8328 ;; - With fancy completion styles, the code below will not always
8329 ;; find the right base directory.
8330 (if minibuffer-completing-file-name
8331 (file-name-as-directory
8332 (expand-file-name
8333 (buffer-substring (minibuffer-prompt-end)
8334 (- (point) (or completion-base-size 0))))))))
8335 (with-current-buffer standard-output
8336 (let ((base-size completion-base-size) ;Read before killing localvars.
8337 (base-position completion-base-position)
8338 (insert-fun completion-list-insert-choice-function))
8339 (completion-list-mode)
8340 (set (make-local-variable 'completion-base-size) base-size)
8341 (set (make-local-variable 'completion-base-position) base-position)
8342 (set (make-local-variable 'completion-list-insert-choice-function)
8343 insert-fun))
8344 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8345 (if base-dir (setq default-directory base-dir))
8346 ;; Maybe insert help string.
8347 (when completion-show-help
8348 (goto-char (point-min))
8349 (if (display-mouse-p)
8350 (insert "Click on a completion to select it.\n"))
8351 (insert (substitute-command-keys
8352 "In this buffer, type \\[choose-completion] to \
8353 select the completion near point.\n\n"))))))
8355 (add-hook 'completion-setup-hook 'completion-setup-function)
8357 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8358 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8360 (defun switch-to-completions ()
8361 "Select the completion list window."
8362 (interactive)
8363 (let ((window (or (get-buffer-window "*Completions*" 0)
8364 ;; Make sure we have a completions window.
8365 (progn (minibuffer-completion-help)
8366 (get-buffer-window "*Completions*" 0)))))
8367 (when window
8368 (select-window window)
8369 ;; In the new buffer, go to the first completion.
8370 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8371 (when (bobp)
8372 (next-completion 1)))))
8374 ;;; Support keyboard commands to turn on various modifiers.
8376 ;; These functions -- which are not commands -- each add one modifier
8377 ;; to the following event.
8379 (defun event-apply-alt-modifier (_ignore-prompt)
8380 "\\<function-key-map>Add the Alt modifier to the following event.
8381 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8382 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8383 (defun event-apply-super-modifier (_ignore-prompt)
8384 "\\<function-key-map>Add the Super modifier to the following event.
8385 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8386 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8387 (defun event-apply-hyper-modifier (_ignore-prompt)
8388 "\\<function-key-map>Add the Hyper modifier to the following event.
8389 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8390 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8391 (defun event-apply-shift-modifier (_ignore-prompt)
8392 "\\<function-key-map>Add the Shift modifier to the following event.
8393 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8394 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8395 (defun event-apply-control-modifier (_ignore-prompt)
8396 "\\<function-key-map>Add the Ctrl modifier to the following event.
8397 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8398 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8399 (defun event-apply-meta-modifier (_ignore-prompt)
8400 "\\<function-key-map>Add the Meta modifier to the following event.
8401 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8402 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8404 (defun event-apply-modifier (event symbol lshiftby prefix)
8405 "Apply a modifier flag to event EVENT.
8406 SYMBOL is the name of this modifier, as a symbol.
8407 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8408 PREFIX is the string that represents this modifier in an event type symbol."
8409 (if (numberp event)
8410 (cond ((eq symbol 'control)
8411 (if (and (<= (downcase event) ?z)
8412 (>= (downcase event) ?a))
8413 (- (downcase event) ?a -1)
8414 (if (and (<= (downcase event) ?Z)
8415 (>= (downcase event) ?A))
8416 (- (downcase event) ?A -1)
8417 (logior (lsh 1 lshiftby) event))))
8418 ((eq symbol 'shift)
8419 (if (and (<= (downcase event) ?z)
8420 (>= (downcase event) ?a))
8421 (upcase event)
8422 (logior (lsh 1 lshiftby) event)))
8424 (logior (lsh 1 lshiftby) event)))
8425 (if (memq symbol (event-modifiers event))
8426 event
8427 (let ((event-type (if (symbolp event) event (car event))))
8428 (setq event-type (intern (concat prefix (symbol-name event-type))))
8429 (if (symbolp event)
8430 event-type
8431 (cons event-type (cdr event)))))))
8433 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8434 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8435 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8436 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8437 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8438 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8440 ;;;; Keypad support.
8442 ;; Make the keypad keys act like ordinary typing keys. If people add
8443 ;; bindings for the function key symbols, then those bindings will
8444 ;; override these, so this shouldn't interfere with any existing
8445 ;; bindings.
8447 ;; Also tell read-char how to handle these keys.
8448 (mapc
8449 (lambda (keypad-normal)
8450 (let ((keypad (nth 0 keypad-normal))
8451 (normal (nth 1 keypad-normal)))
8452 (put keypad 'ascii-character normal)
8453 (define-key function-key-map (vector keypad) (vector normal))))
8454 ;; See also kp-keys bound in bindings.el.
8455 '((kp-space ?\s)
8456 (kp-tab ?\t)
8457 (kp-enter ?\r)
8458 (kp-separator ?,)
8459 (kp-equal ?=)
8460 ;; Do the same for various keys that are represented as symbols under
8461 ;; GUIs but naturally correspond to characters.
8462 (backspace 127)
8463 (delete 127)
8464 (tab ?\t)
8465 (linefeed ?\n)
8466 (clear ?\C-l)
8467 (return ?\C-m)
8468 (escape ?\e)
8471 ;;;;
8472 ;;;; forking a twin copy of a buffer.
8473 ;;;;
8475 (defvar clone-buffer-hook nil
8476 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8478 (defvar clone-indirect-buffer-hook nil
8479 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8481 (defun clone-process (process &optional newname)
8482 "Create a twin copy of PROCESS.
8483 If NEWNAME is nil, it defaults to PROCESS' name;
8484 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8485 If PROCESS is associated with a buffer, the new process will be associated
8486 with the current buffer instead.
8487 Returns nil if PROCESS has already terminated."
8488 (setq newname (or newname (process-name process)))
8489 (if (string-match "<[0-9]+>\\'" newname)
8490 (setq newname (substring newname 0 (match-beginning 0))))
8491 (when (memq (process-status process) '(run stop open))
8492 (let* ((process-connection-type (process-tty-name process))
8493 (new-process
8494 (if (memq (process-status process) '(open))
8495 (let ((args (process-contact process t)))
8496 (setq args (plist-put args :name newname))
8497 (setq args (plist-put args :buffer
8498 (if (process-buffer process)
8499 (current-buffer))))
8500 (apply 'make-network-process args))
8501 (apply 'start-process newname
8502 (if (process-buffer process) (current-buffer))
8503 (process-command process)))))
8504 (set-process-query-on-exit-flag
8505 new-process (process-query-on-exit-flag process))
8506 (set-process-inherit-coding-system-flag
8507 new-process (process-inherit-coding-system-flag process))
8508 (set-process-filter new-process (process-filter process))
8509 (set-process-sentinel new-process (process-sentinel process))
8510 (set-process-plist new-process (copy-sequence (process-plist process)))
8511 new-process)))
8513 ;; things to maybe add (currently partly covered by `funcall mode'):
8514 ;; - syntax-table
8515 ;; - overlays
8516 (defun clone-buffer (&optional newname display-flag)
8517 "Create and return a twin copy of the current buffer.
8518 Unlike an indirect buffer, the new buffer can be edited
8519 independently of the old one (if it is not read-only).
8520 NEWNAME is the name of the new buffer. It may be modified by
8521 adding or incrementing <N> at the end as necessary to create a
8522 unique buffer name. If nil, it defaults to the name of the
8523 current buffer, with the proper suffix. If DISPLAY-FLAG is
8524 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8525 clone a file-visiting buffer, or a buffer whose major mode symbol
8526 has a non-nil `no-clone' property, results in an error.
8528 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8529 current buffer with appropriate suffix. However, if a prefix
8530 argument is given, then the command prompts for NEWNAME in the
8531 minibuffer.
8533 This runs the normal hook `clone-buffer-hook' in the new buffer
8534 after it has been set up properly in other respects."
8535 (interactive
8536 (progn
8537 (if buffer-file-name
8538 (error "Cannot clone a file-visiting buffer"))
8539 (if (get major-mode 'no-clone)
8540 (error "Cannot clone a buffer in %s mode" mode-name))
8541 (list (if current-prefix-arg
8542 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8543 t)))
8544 (if buffer-file-name
8545 (error "Cannot clone a file-visiting buffer"))
8546 (if (get major-mode 'no-clone)
8547 (error "Cannot clone a buffer in %s mode" mode-name))
8548 (setq newname (or newname (buffer-name)))
8549 (if (string-match "<[0-9]+>\\'" newname)
8550 (setq newname (substring newname 0 (match-beginning 0))))
8551 (let ((buf (current-buffer))
8552 (ptmin (point-min))
8553 (ptmax (point-max))
8554 (pt (point))
8555 (mk (if mark-active (mark t)))
8556 (modified (buffer-modified-p))
8557 (mode major-mode)
8558 (lvars (buffer-local-variables))
8559 (process (get-buffer-process (current-buffer)))
8560 (new (generate-new-buffer (or newname (buffer-name)))))
8561 (save-restriction
8562 (widen)
8563 (with-current-buffer new
8564 (insert-buffer-substring buf)))
8565 (with-current-buffer new
8566 (narrow-to-region ptmin ptmax)
8567 (goto-char pt)
8568 (if mk (set-mark mk))
8569 (set-buffer-modified-p modified)
8571 ;; Clone the old buffer's process, if any.
8572 (when process (clone-process process))
8574 ;; Now set up the major mode.
8575 (funcall mode)
8577 ;; Set up other local variables.
8578 (mapc (lambda (v)
8579 (condition-case ()
8580 (if (symbolp v)
8581 (makunbound v)
8582 (set (make-local-variable (car v)) (cdr v)))
8583 (setting-constant nil))) ;E.g. for enable-multibyte-characters.
8584 lvars)
8586 (setq mark-ring (mapcar (lambda (mk) (copy-marker (marker-position mk)))
8587 mark-ring))
8589 ;; Run any hooks (typically set up by the major mode
8590 ;; for cloning to work properly).
8591 (run-hooks 'clone-buffer-hook))
8592 (if display-flag
8593 ;; Presumably the current buffer is shown in the selected frame, so
8594 ;; we want to display the clone elsewhere.
8595 (let ((same-window-regexps nil)
8596 (same-window-buffer-names))
8597 (pop-to-buffer new)))
8598 new))
8601 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8602 "Create an indirect buffer that is a twin copy of the current buffer.
8604 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8605 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8606 or if not called with a prefix arg, NEWNAME defaults to the current
8607 buffer's name. The name is modified by adding a `<N>' suffix to it
8608 or by incrementing the N in an existing suffix. Trying to clone a
8609 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8610 property results in an error.
8612 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8613 This is always done when called interactively.
8615 Optional third arg NORECORD non-nil means do not put this buffer at the
8616 front of the list of recently selected ones.
8618 Returns the newly created indirect buffer."
8619 (interactive
8620 (progn
8621 (if (get major-mode 'no-clone-indirect)
8622 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8623 (list (if current-prefix-arg
8624 (read-buffer "Name of indirect buffer: " (current-buffer)))
8625 t)))
8626 (if (get major-mode 'no-clone-indirect)
8627 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8628 (setq newname (or newname (buffer-name)))
8629 (if (string-match "<[0-9]+>\\'" newname)
8630 (setq newname (substring newname 0 (match-beginning 0))))
8631 (let* ((name (generate-new-buffer-name newname))
8632 (buffer (make-indirect-buffer (current-buffer) name t)))
8633 (with-current-buffer buffer
8634 (run-hooks 'clone-indirect-buffer-hook))
8635 (when display-flag
8636 (pop-to-buffer buffer nil norecord))
8637 buffer))
8640 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8641 "Like `clone-indirect-buffer' but display in another window."
8642 (interactive
8643 (progn
8644 (if (get major-mode 'no-clone-indirect)
8645 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8646 (list (if current-prefix-arg
8647 (read-buffer "Name of indirect buffer: " (current-buffer)))
8648 t)))
8649 (let ((pop-up-windows t))
8650 (clone-indirect-buffer newname display-flag norecord)))
8653 ;;; Handling of Backspace and Delete keys.
8655 (defcustom normal-erase-is-backspace 'maybe
8656 "Set the default behavior of the Delete and Backspace keys.
8658 If set to t, Delete key deletes forward and Backspace key deletes
8659 backward.
8661 If set to nil, both Delete and Backspace keys delete backward.
8663 If set to `maybe' (which is the default), Emacs automatically
8664 selects a behavior. On window systems, the behavior depends on
8665 the keyboard used. If the keyboard has both a Backspace key and
8666 a Delete key, and both are mapped to their usual meanings, the
8667 option's default value is set to t, so that Backspace can be used
8668 to delete backward, and Delete can be used to delete forward.
8670 If not running under a window system, customizing this option
8671 accomplishes a similar effect by mapping C-h, which is usually
8672 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8673 via `keyboard-translate'. The former functionality of C-h is
8674 available on the F1 key. You should probably not use this
8675 setting if you don't have both Backspace, Delete and F1 keys.
8677 Setting this variable with setq doesn't take effect. Programmatically,
8678 call `normal-erase-is-backspace-mode' (which see) instead."
8679 :type '(choice (const :tag "Off" nil)
8680 (const :tag "Maybe" maybe)
8681 (other :tag "On" t))
8682 :group 'editing-basics
8683 :version "21.1"
8684 :set (lambda (symbol value)
8685 ;; The fboundp is because of a problem with :set when
8686 ;; dumping Emacs. It doesn't really matter.
8687 (if (fboundp 'normal-erase-is-backspace-mode)
8688 (normal-erase-is-backspace-mode (or value 0))
8689 (set-default symbol value))))
8691 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8692 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8693 (unless frame (setq frame (selected-frame)))
8694 (with-selected-frame frame
8695 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8696 (normal-erase-is-backspace-mode
8697 (if (if (eq normal-erase-is-backspace 'maybe)
8698 (and (not noninteractive)
8699 (or (memq system-type '(ms-dos windows-nt))
8700 (memq window-system '(w32 ns))
8701 (and (memq window-system '(x))
8702 (fboundp 'x-backspace-delete-keys-p)
8703 (x-backspace-delete-keys-p))
8704 ;; If the terminal Emacs is running on has erase char
8705 ;; set to ^H, use the Backspace key for deleting
8706 ;; backward, and the Delete key for deleting forward.
8707 (and (null window-system)
8708 (eq tty-erase-char ?\^H))))
8709 normal-erase-is-backspace)
8710 1 0)))))
8712 (define-minor-mode normal-erase-is-backspace-mode
8713 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8714 With a prefix argument ARG, enable this feature if ARG is
8715 positive, and disable it otherwise. If called from Lisp, enable
8716 the mode if ARG is omitted or nil.
8718 On window systems, when this mode is on, Delete is mapped to C-d
8719 and Backspace is mapped to DEL; when this mode is off, both
8720 Delete and Backspace are mapped to DEL. (The remapping goes via
8721 `local-function-key-map', so binding Delete or Backspace in the
8722 global or local keymap will override that.)
8724 In addition, on window systems, the bindings of C-Delete, M-Delete,
8725 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8726 the global keymap in accordance with the functionality of Delete and
8727 Backspace. For example, if Delete is remapped to C-d, which deletes
8728 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8729 to DEL, which deletes backward, C-Delete is bound to
8730 `backward-kill-word'.
8732 If not running on a window system, a similar effect is accomplished by
8733 remapping C-h (normally produced by the Backspace key) and DEL via
8734 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8735 to C-d; if it's off, the keys are not remapped.
8737 When not running on a window system, and this mode is turned on, the
8738 former functionality of C-h is available on the F1 key. You should
8739 probably not turn on this mode on a text-only terminal if you don't
8740 have both Backspace, Delete and F1 keys.
8742 See also `normal-erase-is-backspace'."
8743 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8744 . (lambda (v)
8745 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8746 (if v 1 0))))
8747 (let ((enabled (eq 1 (terminal-parameter
8748 nil 'normal-erase-is-backspace))))
8750 (cond ((or (memq window-system '(x w32 ns pc))
8751 (memq system-type '(ms-dos windows-nt)))
8752 (let ((bindings
8753 `(([M-delete] [M-backspace])
8754 ([C-M-delete] [C-M-backspace])
8755 ([?\e C-delete] [?\e C-backspace]))))
8757 (if enabled
8758 (progn
8759 (define-key local-function-key-map [delete] [deletechar])
8760 (define-key local-function-key-map [kp-delete] [deletechar])
8761 (define-key local-function-key-map [backspace] [?\C-?])
8762 (dolist (b bindings)
8763 ;; Not sure if input-decode-map is really right, but
8764 ;; keyboard-translate-table (used below) only works
8765 ;; for integer events, and key-translation-table is
8766 ;; global (like the global-map, used earlier).
8767 (define-key input-decode-map (car b) nil)
8768 (define-key input-decode-map (cadr b) nil)))
8769 (define-key local-function-key-map [delete] [?\C-?])
8770 (define-key local-function-key-map [kp-delete] [?\C-?])
8771 (define-key local-function-key-map [backspace] [?\C-?])
8772 (dolist (b bindings)
8773 (define-key input-decode-map (car b) (cadr b))
8774 (define-key input-decode-map (cadr b) (car b))))))
8776 (if enabled
8777 (progn
8778 (keyboard-translate ?\C-h ?\C-?)
8779 (keyboard-translate ?\C-? ?\C-d))
8780 (keyboard-translate ?\C-h ?\C-h)
8781 (keyboard-translate ?\C-? ?\C-?))))
8783 (if (called-interactively-p 'interactive)
8784 (message "Delete key deletes %s"
8785 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8786 "forward" "backward")))))
8788 (defvar vis-mode-saved-buffer-invisibility-spec nil
8789 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8791 (define-minor-mode read-only-mode
8792 "Change whether the current buffer is read-only.
8793 With prefix argument ARG, make the buffer read-only if ARG is
8794 positive, otherwise make it writable. If buffer is read-only
8795 and `view-read-only' is non-nil, enter view mode.
8797 Do not call this from a Lisp program unless you really intend to
8798 do the same thing as the \\[read-only-mode] command, including
8799 possibly enabling or disabling View mode. Also, note that this
8800 command works by setting the variable `buffer-read-only', which
8801 does not affect read-only regions caused by text properties. To
8802 ignore read-only status in a Lisp program (whether due to text
8803 properties or buffer state), bind `inhibit-read-only' temporarily
8804 to a non-nil value."
8805 :variable buffer-read-only
8806 (cond
8807 ((and (not buffer-read-only) view-mode)
8808 (View-exit-and-edit)
8809 (make-local-variable 'view-read-only)
8810 (setq view-read-only t)) ; Must leave view mode.
8811 ((and buffer-read-only view-read-only
8812 ;; If view-mode is already active, `view-mode-enter' is a nop.
8813 (not view-mode)
8814 (not (eq (get major-mode 'mode-class) 'special)))
8815 (view-mode-enter))))
8817 (define-minor-mode visible-mode
8818 "Toggle making all invisible text temporarily visible (Visible mode).
8819 With a prefix argument ARG, enable Visible mode if ARG is
8820 positive, and disable it otherwise. If called from Lisp, enable
8821 the mode if ARG is omitted or nil.
8823 This mode works by saving the value of `buffer-invisibility-spec'
8824 and setting it to nil."
8825 :lighter " Vis"
8826 :group 'editing-basics
8827 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8828 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8829 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8830 (when visible-mode
8831 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8832 buffer-invisibility-spec)
8833 (setq buffer-invisibility-spec nil)))
8835 (defvar messages-buffer-mode-map
8836 (let ((map (make-sparse-keymap)))
8837 (set-keymap-parent map special-mode-map)
8838 (define-key map "g" nil) ; nothing to revert
8839 map))
8841 (define-derived-mode messages-buffer-mode special-mode "Messages"
8842 "Major mode used in the \"*Messages*\" buffer.")
8844 (defun messages-buffer ()
8845 "Return the \"*Messages*\" buffer.
8846 If it does not exist, create and it switch it to `messages-buffer-mode'."
8847 (or (get-buffer "*Messages*")
8848 (with-current-buffer (get-buffer-create "*Messages*")
8849 (messages-buffer-mode)
8850 (current-buffer))))
8853 ;; Minibuffer prompt stuff.
8855 ;;(defun minibuffer-prompt-modification (start end)
8856 ;; (error "You cannot modify the prompt"))
8859 ;;(defun minibuffer-prompt-insertion (start end)
8860 ;; (let ((inhibit-modification-hooks t))
8861 ;; (delete-region start end)
8862 ;; ;; Discard undo information for the text insertion itself
8863 ;; ;; and for the text deletion.above.
8864 ;; (when (consp buffer-undo-list)
8865 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8866 ;; (message "You cannot modify the prompt")))
8869 ;;(setq minibuffer-prompt-properties
8870 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8871 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8874 ;;;; Problematic external packages.
8876 ;; rms says this should be done by specifying symbols that define
8877 ;; versions together with bad values. This is therefore not as
8878 ;; flexible as it could be. See the thread:
8879 ;; https://lists.gnu.org/r/emacs-devel/2007-08/msg00300.html
8880 (defconst bad-packages-alist
8881 ;; Not sure exactly which semantic versions have problems.
8882 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8883 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8884 "The version of `semantic' loaded does not work in Emacs 22.
8885 It can cause constant high CPU load.
8886 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8887 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8888 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8889 ;; provided the `CUA-mode' feature. Since this is no longer true,
8890 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8891 (CUA-mode t nil
8892 "CUA-mode is now part of the standard GNU Emacs distribution,
8893 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8895 You have loaded an older version of CUA-mode which does not work
8896 correctly with this version of Emacs. You should remove the old
8897 version and use the one distributed with Emacs."))
8898 "Alist of packages known to cause problems in this version of Emacs.
8899 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8900 PACKAGE is either a regular expression to match file names, or a
8901 symbol (a feature name), like for `with-eval-after-load'.
8902 SYMBOL is either the name of a string variable, or t. Upon
8903 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8904 warning using STRING as the message.")
8906 (defun bad-package-check (package)
8907 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8908 (condition-case nil
8909 (let* ((list (assoc package bad-packages-alist))
8910 (symbol (nth 1 list)))
8911 (and list
8912 (boundp symbol)
8913 (or (eq symbol t)
8914 (and (stringp (setq symbol (eval symbol)))
8915 (string-match-p (nth 2 list) symbol)))
8916 (display-warning package (nth 3 list) :warning)))
8917 (error nil)))
8919 (dolist (elem bad-packages-alist)
8920 (let ((pkg (car elem)))
8921 (with-eval-after-load pkg
8922 (bad-package-check pkg))))
8925 ;;; Generic dispatcher commands
8927 ;; Macro `define-alternatives' is used to create generic commands.
8928 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8929 ;; that can have different alternative implementations where choosing
8930 ;; among them is exclusively a matter of user preference.
8932 ;; (define-alternatives COMMAND) creates a new interactive command
8933 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8934 ;; Typically, the user will not need to customize this variable; packages
8935 ;; wanting to add alternative implementations should use
8937 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8939 (defmacro define-alternatives (command &rest customizations)
8940 "Define the new command `COMMAND'.
8942 The argument `COMMAND' should be a symbol.
8944 Running `M-x COMMAND RET' for the first time prompts for which
8945 alternative to use and records the selected command as a custom
8946 variable.
8948 Running `C-u M-x COMMAND RET' prompts again for an alternative
8949 and overwrites the previous choice.
8951 The variable `COMMAND-alternatives' contains an alist with
8952 alternative implementations of COMMAND. `define-alternatives'
8953 does not have any effect until this variable is set.
8955 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8956 `defcustom' keywords and values to add to the declaration of
8957 `COMMAND-alternatives' (typically :group and :version)."
8958 (let* ((command-name (symbol-name command))
8959 (varalt-name (concat command-name "-alternatives"))
8960 (varalt-sym (intern varalt-name))
8961 (varimp-sym (intern (concat command-name "--implementation"))))
8962 `(progn
8964 (defcustom ,varalt-sym nil
8965 ,(format "Alist of alternative implementations for the `%s' command.
8967 Each entry must be a pair (ALTNAME . ALTFUN), where:
8968 ALTNAME - The name shown at user to describe the alternative implementation.
8969 ALTFUN - The function called to implement this alternative."
8970 command-name)
8971 :type '(alist :key-type string :value-type function)
8972 ,@customizations)
8974 (put ',varalt-sym 'definition-name ',command)
8975 (defvar ,varimp-sym nil "Internal use only.")
8977 (defun ,command (&optional arg)
8978 ,(format "Run generic command `%s'.
8979 If used for the first time, or with interactive ARG, ask the user which
8980 implementation to use for `%s'. The variable `%s'
8981 contains the list of implementations currently supported for this command."
8982 command-name command-name varalt-name)
8983 (interactive "P")
8984 (when (or arg (null ,varimp-sym))
8985 (let ((val (completing-read
8986 ,(format-message
8987 "Select implementation for command `%s': "
8988 command-name)
8989 ,varalt-sym nil t)))
8990 (unless (string-equal val "")
8991 (when (null ,varimp-sym)
8992 (message
8993 "Use C-u M-x %s RET`to select another implementation"
8994 ,command-name)
8995 (sit-for 3))
8996 (customize-save-variable ',varimp-sym
8997 (cdr (assoc-string val ,varalt-sym))))))
8998 (if ,varimp-sym
8999 (call-interactively ,varimp-sym)
9000 (message "%s" ,(format-message
9001 "No implementation selected for command `%s'"
9002 command-name)))))))
9005 ;;; Functions for changing capitalization that Do What I Mean
9006 (defun upcase-dwim (arg)
9007 "Upcase words in the region, if active; if not, upcase word at point.
9008 If the region is active, this function calls `upcase-region'.
9009 Otherwise, it calls `upcase-word', with prefix argument passed to it
9010 to upcase ARG words."
9011 (interactive "*p")
9012 (if (use-region-p)
9013 (upcase-region (region-beginning) (region-end) (region-noncontiguous-p))
9014 (upcase-word arg)))
9016 (defun downcase-dwim (arg)
9017 "Downcase words in the region, if active; if not, downcase word at point.
9018 If the region is active, this function calls `downcase-region'.
9019 Otherwise, it calls `downcase-word', with prefix argument passed to it
9020 to downcase ARG words."
9021 (interactive "*p")
9022 (if (use-region-p)
9023 (downcase-region (region-beginning) (region-end) (region-noncontiguous-p))
9024 (downcase-word arg)))
9026 (defun capitalize-dwim (arg)
9027 "Capitalize words in the region, if active; if not, capitalize word at point.
9028 If the region is active, this function calls `capitalize-region'.
9029 Otherwise, it calls `capitalize-word', with prefix argument passed to it
9030 to capitalize ARG words."
9031 (interactive "*p")
9032 (if (use-region-p)
9033 (capitalize-region (region-beginning) (region-end))
9034 (capitalize-word arg)))
9038 (provide 'simple)
9040 ;;; simple.el ends here