Don't require isearch-update before isearch-done
[emacs.git] / lisp / simple.el
blob04a525c439243761060da230baca930c97d66ce1
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2016 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
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 <http://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 shell-command-dont-erase-buffer nil
41 "If non-nil, output buffer is not erased between shell commands.
42 Also, a non-nil value set the point in the output buffer
43 once the command complete.
44 The value `beg-last-out' set point at the beginning of the output,
45 `end-last-out' set point at the end of the buffer, `save-point'
46 restore the buffer position before the command."
47 :type '(choice
48 (const :tag "Erase buffer" nil)
49 (const :tag "Set point to beginning of last output" beg-last-out)
50 (const :tag "Set point to end of last output" end-last-out)
51 (const :tag "Save point" save-point))
52 :group 'shell
53 :version "25.2")
55 (defvar shell-command-saved-pos nil
56 "Point position in the output buffer after command complete.
57 It is an alist (BUFFER . POS), where BUFFER is the output
58 buffer, and POS is the point position in BUFFER once the command finish.
59 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
61 (defcustom idle-update-delay 0.5
62 "Idle time delay before updating various things on the screen.
63 Various Emacs features that update auxiliary information when point moves
64 wait this many seconds after Emacs becomes idle before doing an update."
65 :type 'number
66 :group 'display
67 :version "22.1")
69 (defgroup killing nil
70 "Killing and yanking commands."
71 :group 'editing)
73 (defgroup paren-matching nil
74 "Highlight (un)matching of parens and expressions."
75 :group 'matching)
77 ;;; next-error support framework
79 (defgroup next-error nil
80 "`next-error' support framework."
81 :group 'compilation
82 :version "22.1")
84 (defface next-error
85 '((t (:inherit region)))
86 "Face used to highlight next error locus."
87 :group 'next-error
88 :version "22.1")
90 (defcustom next-error-highlight 0.5
91 "Highlighting of locations in selected source buffers.
92 If a number, highlight the locus in `next-error' face for the given time
93 in seconds, or until the next command is executed.
94 If t, highlight the locus until the next command is executed, or until
95 some other locus replaces it.
96 If nil, don't highlight the locus in the source buffer.
97 If `fringe-arrow', indicate the locus by the fringe arrow
98 indefinitely until some other locus replaces it."
99 :type '(choice (number :tag "Highlight for specified time")
100 (const :tag "Semipermanent highlighting" t)
101 (const :tag "No highlighting" nil)
102 (const :tag "Fringe arrow" fringe-arrow))
103 :group 'next-error
104 :version "22.1")
106 (defcustom next-error-highlight-no-select 0.5
107 "Highlighting of locations in `next-error-no-select'.
108 If number, highlight the locus in `next-error' face for given time in seconds.
109 If t, highlight the locus indefinitely until some other locus replaces it.
110 If nil, don't highlight the locus in the source buffer.
111 If `fringe-arrow', indicate the locus by the fringe arrow
112 indefinitely until some other locus replaces it."
113 :type '(choice (number :tag "Highlight for specified time")
114 (const :tag "Semipermanent highlighting" t)
115 (const :tag "No highlighting" nil)
116 (const :tag "Fringe arrow" fringe-arrow))
117 :group 'next-error
118 :version "22.1")
120 (defcustom next-error-recenter nil
121 "Display the line in the visited source file recentered as specified.
122 If non-nil, the value is passed directly to `recenter'."
123 :type '(choice (integer :tag "Line to recenter to")
124 (const :tag "Center of window" (4))
125 (const :tag "No recentering" nil))
126 :group 'next-error
127 :version "23.1")
129 (defcustom next-error-hook nil
130 "List of hook functions run by `next-error' after visiting source file."
131 :type 'hook
132 :group 'next-error)
134 (defvar next-error-highlight-timer nil)
136 (defvar next-error-overlay-arrow-position nil)
137 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
138 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
140 (defvar next-error-last-buffer nil
141 "The most recent `next-error' buffer.
142 A buffer becomes most recent when its compilation, grep, or
143 similar mode is started, or when it is used with \\[next-error]
144 or \\[compile-goto-error].")
146 (defvar next-error-function nil
147 "Function to use to find the next error in the current buffer.
148 The function is called with 2 parameters:
149 ARG is an integer specifying by how many errors to move.
150 RESET is a boolean which, if non-nil, says to go back to the beginning
151 of the errors before moving.
152 Major modes providing compile-like functionality should set this variable
153 to indicate to `next-error' that this is a candidate buffer and how
154 to navigate in it.")
155 (make-variable-buffer-local 'next-error-function)
157 (defvar next-error-move-function nil
158 "Function to use to move to an error locus.
159 It takes two arguments, a buffer position in the error buffer
160 and a buffer position in the error locus buffer.
161 The buffer for the error locus should already be current.
162 nil means use goto-char using the second argument position.")
163 (make-variable-buffer-local 'next-error-move-function)
165 (defsubst next-error-buffer-p (buffer
166 &optional avoid-current
167 extra-test-inclusive
168 extra-test-exclusive)
169 "Return non-nil if BUFFER is a `next-error' capable buffer.
170 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
171 return nil.
173 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
174 BUFFER would not normally qualify. If it returns non-nil, BUFFER
175 is considered `next-error' capable, anyway, and the function
176 returns non-nil.
178 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
179 buffer would normally qualify. If it returns nil, BUFFER is
180 rejected, and the function returns nil."
181 (and (buffer-name buffer) ;First make sure it's live.
182 (not (and avoid-current (eq buffer (current-buffer))))
183 (with-current-buffer buffer
184 (if next-error-function ; This is the normal test.
185 ;; Optionally reject some buffers.
186 (if extra-test-exclusive
187 (funcall extra-test-exclusive)
189 ;; Optionally accept some other buffers.
190 (and extra-test-inclusive
191 (funcall extra-test-inclusive))))))
193 (defun next-error-find-buffer (&optional avoid-current
194 extra-test-inclusive
195 extra-test-exclusive)
196 "Return a `next-error' capable buffer.
198 If AVOID-CURRENT is non-nil, treat the current buffer
199 as an absolute last resort only.
201 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
202 that normally would not qualify. If it returns t, the buffer
203 in question is treated as usable.
205 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
206 that would normally be considered usable. If it returns nil,
207 that buffer is rejected."
209 ;; 1. If one window on the selected frame displays such buffer, return it.
210 (let ((window-buffers
211 (delete-dups
212 (delq nil (mapcar (lambda (w)
213 (if (next-error-buffer-p
214 (window-buffer w)
215 avoid-current
216 extra-test-inclusive extra-test-exclusive)
217 (window-buffer w)))
218 (window-list))))))
219 (if (eq (length window-buffers) 1)
220 (car window-buffers)))
221 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
222 (if (and next-error-last-buffer
223 (next-error-buffer-p next-error-last-buffer avoid-current
224 extra-test-inclusive extra-test-exclusive))
225 next-error-last-buffer)
226 ;; 3. If the current buffer is acceptable, choose it.
227 (if (next-error-buffer-p (current-buffer) avoid-current
228 extra-test-inclusive extra-test-exclusive)
229 (current-buffer))
230 ;; 4. Look for any acceptable buffer.
231 (let ((buffers (buffer-list)))
232 (while (and buffers
233 (not (next-error-buffer-p
234 (car buffers) avoid-current
235 extra-test-inclusive extra-test-exclusive)))
236 (setq buffers (cdr buffers)))
237 (car buffers))
238 ;; 5. Use the current buffer as a last resort if it qualifies,
239 ;; even despite AVOID-CURRENT.
240 (and avoid-current
241 (next-error-buffer-p (current-buffer) nil
242 extra-test-inclusive extra-test-exclusive)
243 (progn
244 (message "This is the only buffer with error message locations")
245 (current-buffer)))
246 ;; 6. Give up.
247 (error "No buffers contain error message locations")))
249 (defun next-error (&optional arg reset)
250 "Visit next `next-error' message and corresponding source code.
252 If all the error messages parsed so far have been processed already,
253 the message buffer is checked for new ones.
255 A prefix ARG specifies how many error messages to move;
256 negative means move back to previous error messages.
257 Just \\[universal-argument] as a prefix means reparse the error message buffer
258 and start at the first error.
260 The RESET argument specifies that we should restart from the beginning.
262 \\[next-error] normally uses the most recently started
263 compilation, grep, or occur buffer. It can also operate on any
264 buffer with output from the \\[compile], \\[grep] commands, or,
265 more generally, on any buffer in Compilation mode or with
266 Compilation Minor mode enabled, or any buffer in which
267 `next-error-function' is bound to an appropriate function.
268 To specify use of a particular buffer for error messages, type
269 \\[next-error] in that buffer when it is the only one displayed
270 in the current frame.
272 Once \\[next-error] has chosen the buffer for error messages, it
273 runs `next-error-hook' with `run-hooks', and stays with that buffer
274 until you use it in some other buffer which uses Compilation mode
275 or Compilation Minor mode.
277 To control which errors are matched, customize the variable
278 `compilation-error-regexp-alist'."
279 (interactive "P")
280 (if (consp arg) (setq reset t arg nil))
281 (when (setq next-error-last-buffer (next-error-find-buffer))
282 ;; we know here that next-error-function is a valid symbol we can funcall
283 (with-current-buffer next-error-last-buffer
284 (funcall next-error-function (prefix-numeric-value arg) reset)
285 (when next-error-recenter
286 (recenter next-error-recenter))
287 (run-hooks 'next-error-hook))))
289 (defun next-error-internal ()
290 "Visit the source code corresponding to the `next-error' message at point."
291 (setq next-error-last-buffer (current-buffer))
292 ;; we know here that next-error-function is a valid symbol we can funcall
293 (with-current-buffer next-error-last-buffer
294 (funcall next-error-function 0 nil)
295 (when next-error-recenter
296 (recenter next-error-recenter))
297 (run-hooks 'next-error-hook)))
299 (defalias 'goto-next-locus 'next-error)
300 (defalias 'next-match 'next-error)
302 (defun previous-error (&optional n)
303 "Visit previous `next-error' message and corresponding source code.
305 Prefix arg N says how many error messages to move backwards (or
306 forwards, if negative).
308 This operates on the output from the \\[compile] and \\[grep] commands."
309 (interactive "p")
310 (next-error (- (or n 1))))
312 (defun first-error (&optional n)
313 "Restart at the first error.
314 Visit corresponding source code.
315 With prefix arg N, visit the source code of the Nth error.
316 This operates on the output from the \\[compile] command, for instance."
317 (interactive "p")
318 (next-error n t))
320 (defun next-error-no-select (&optional n)
321 "Move point to the next error in the `next-error' buffer and highlight match.
322 Prefix arg N says how many error messages to move forwards (or
323 backwards, if negative).
324 Finds and highlights the source line like \\[next-error], but does not
325 select the source buffer."
326 (interactive "p")
327 (let ((next-error-highlight next-error-highlight-no-select))
328 (next-error n))
329 (pop-to-buffer next-error-last-buffer))
331 (defun previous-error-no-select (&optional n)
332 "Move point to the previous error in the `next-error' buffer and highlight match.
333 Prefix arg N says how many error messages to move backwards (or
334 forwards, if negative).
335 Finds and highlights the source line like \\[previous-error], but does not
336 select the source buffer."
337 (interactive "p")
338 (next-error-no-select (- (or n 1))))
340 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
341 (defvar next-error-follow-last-line nil)
343 (define-minor-mode next-error-follow-minor-mode
344 "Minor mode for compilation, occur and diff modes.
345 With a prefix argument ARG, enable mode if ARG is positive, and
346 disable it otherwise. If called from Lisp, enable mode if ARG is
347 omitted or nil.
348 When turned on, cursor motion in the compilation, grep, occur or diff
349 buffer causes automatic display of the corresponding source code location."
350 :group 'next-error :init-value nil :lighter " Fol"
351 (if (not next-error-follow-minor-mode)
352 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
353 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
354 (make-local-variable 'next-error-follow-last-line)))
356 ;; Used as a `post-command-hook' by `next-error-follow-mode'
357 ;; for the *Compilation* *grep* and *Occur* buffers.
358 (defun next-error-follow-mode-post-command-hook ()
359 (unless (equal next-error-follow-last-line (line-number-at-pos))
360 (setq next-error-follow-last-line (line-number-at-pos))
361 (condition-case nil
362 (let ((compilation-context-lines nil))
363 (setq compilation-current-error (point))
364 (next-error-no-select 0))
365 (error t))))
370 (defun fundamental-mode ()
371 "Major mode not specialized for anything in particular.
372 Other major modes are defined by comparison with this one."
373 (interactive)
374 (kill-all-local-variables)
375 (run-mode-hooks))
377 ;; Special major modes to view specially formatted data rather than files.
379 (defvar special-mode-map
380 (let ((map (make-sparse-keymap)))
381 (suppress-keymap map)
382 (define-key map "q" 'quit-window)
383 (define-key map " " 'scroll-up-command)
384 (define-key map [?\S-\ ] 'scroll-down-command)
385 (define-key map "\C-?" 'scroll-down-command)
386 (define-key map "?" 'describe-mode)
387 (define-key map "h" 'describe-mode)
388 (define-key map ">" 'end-of-buffer)
389 (define-key map "<" 'beginning-of-buffer)
390 (define-key map "g" 'revert-buffer)
391 map))
393 (put 'special-mode 'mode-class 'special)
394 (define-derived-mode special-mode nil "Special"
395 "Parent major mode from which special major modes should inherit."
396 (setq buffer-read-only t))
398 ;; Making and deleting lines.
400 (defvar self-insert-uses-region-functions nil
401 "Special hook to tell if `self-insert-command' will use the region.
402 It must be called via `run-hook-with-args-until-success' with no arguments.
403 Any `post-self-insert-command' which consumes the region should
404 register a function on this hook so that things like `delete-selection-mode'
405 can refrain from consuming the region.")
407 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
408 "Propertized string representing a hard newline character.")
410 (defun newline (&optional arg interactive)
411 "Insert a newline, and move to left margin of the new line if it's blank.
412 If option `use-hard-newlines' is non-nil, the newline is marked with the
413 text-property `hard'.
414 With ARG, insert that many newlines.
416 If `electric-indent-mode' is enabled, this indents the final new line
417 that it adds, and reindents the preceding line. To just insert
418 a newline, use \\[electric-indent-just-newline].
420 Calls `auto-fill-function' if the current column number is greater
421 than the value of `fill-column' and ARG is nil.
422 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
423 (interactive "*P\np")
424 (barf-if-buffer-read-only)
425 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
426 ;; Set last-command-event to tell self-insert what to insert.
427 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
428 (beforepos (point))
429 (last-command-event ?\n)
430 ;; Don't auto-fill if we have a numeric argument.
431 (auto-fill-function (if arg nil auto-fill-function))
432 (arg (prefix-numeric-value arg))
433 (postproc
434 ;; Do the rest in post-self-insert-hook, because we want to do it
435 ;; *before* other functions on that hook.
436 (lambda ()
437 ;; We are not going to insert any newlines if arg is
438 ;; non-positive.
439 (or (and (numberp arg) (<= arg 0))
440 (cl-assert (eq ?\n (char-before))))
441 ;; Mark the newline(s) `hard'.
442 (if use-hard-newlines
443 (set-hard-newline-properties
444 (- (point) arg) (point)))
445 ;; If the newline leaves the previous line blank, and we
446 ;; have a left margin, delete that from the blank line.
447 (save-excursion
448 (goto-char beforepos)
449 (beginning-of-line)
450 (and (looking-at "[ \t]$")
451 (> (current-left-margin) 0)
452 (delete-region (point)
453 (line-end-position))))
454 ;; Indent the line after the newline, except in one case:
455 ;; when we added the newline at the beginning of a line which
456 ;; starts a page.
457 (or was-page-start
458 (move-to-left-margin nil t)))))
459 (unwind-protect
460 (if (not interactive)
461 ;; FIXME: For non-interactive uses, many calls actually
462 ;; just want (insert "\n"), so maybe we should do just
463 ;; that, so as to avoid the risk of filling or running
464 ;; abbrevs unexpectedly.
465 (let ((post-self-insert-hook (list postproc)))
466 (self-insert-command arg))
467 (unwind-protect
468 (progn
469 (add-hook 'post-self-insert-hook postproc nil t)
470 (self-insert-command arg))
471 ;; We first used let-binding to protect the hook, but that
472 ;; was naive since add-hook affects the symbol-default
473 ;; value of the variable, whereas the let-binding might
474 ;; only protect the buffer-local value.
475 (remove-hook 'post-self-insert-hook postproc t)))
476 (cl-assert (not (member postproc post-self-insert-hook)))
477 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
478 nil)
480 (defun set-hard-newline-properties (from to)
481 (let ((sticky (get-text-property from 'rear-nonsticky)))
482 (put-text-property from to 'hard 't)
483 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
484 (if (and (listp sticky) (not (memq 'hard sticky)))
485 (put-text-property from (point) 'rear-nonsticky
486 (cons 'hard sticky)))))
488 (defun open-line (n)
489 "Insert a newline and leave point before it.
490 If there is a fill prefix and/or a `left-margin', insert them on
491 the new line if the line would have been blank.
492 With arg N, insert N newlines."
493 (interactive "*p")
494 (let* ((do-fill-prefix (and fill-prefix (bolp)))
495 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
496 (loc (point-marker))
497 ;; Don't expand an abbrev before point.
498 (abbrev-mode nil))
499 (newline n)
500 (goto-char loc)
501 (while (> n 0)
502 (cond ((bolp)
503 (if do-left-margin (indent-to (current-left-margin)))
504 (if do-fill-prefix (insert-and-inherit fill-prefix))))
505 (forward-line 1)
506 (setq n (1- n)))
507 (goto-char loc)
508 ;; Necessary in case a margin or prefix was inserted.
509 (end-of-line)))
511 (defun split-line (&optional arg)
512 "Split current line, moving portion beyond point vertically down.
513 If the current line starts with `fill-prefix', insert it on the new
514 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
516 When called from Lisp code, ARG may be a prefix string to copy."
517 (interactive "*P")
518 (skip-chars-forward " \t")
519 (let* ((col (current-column))
520 (pos (point))
521 ;; What prefix should we check for (nil means don't).
522 (prefix (cond ((stringp arg) arg)
523 (arg nil)
524 (t fill-prefix)))
525 ;; Does this line start with it?
526 (have-prfx (and prefix
527 (save-excursion
528 (beginning-of-line)
529 (looking-at (regexp-quote prefix))))))
530 (newline 1)
531 (if have-prfx (insert-and-inherit prefix))
532 (indent-to col 0)
533 (goto-char pos)))
535 (defun delete-indentation (&optional arg)
536 "Join this line to previous and fix up whitespace at join.
537 If there is a fill prefix, delete it from the beginning of this line.
538 With argument, join this line to following line."
539 (interactive "*P")
540 (beginning-of-line)
541 (if arg (forward-line 1))
542 (if (eq (preceding-char) ?\n)
543 (progn
544 (delete-region (point) (1- (point)))
545 ;; If the second line started with the fill prefix,
546 ;; delete the prefix.
547 (if (and fill-prefix
548 (<= (+ (point) (length fill-prefix)) (point-max))
549 (string= fill-prefix
550 (buffer-substring (point)
551 (+ (point) (length fill-prefix)))))
552 (delete-region (point) (+ (point) (length fill-prefix))))
553 (fixup-whitespace))))
555 (defalias 'join-line #'delete-indentation) ; easier to find
557 (defun delete-blank-lines ()
558 "On blank line, delete all surrounding blank lines, leaving just one.
559 On isolated blank line, delete that one.
560 On nonblank line, delete any immediately following blank lines."
561 (interactive "*")
562 (let (thisblank singleblank)
563 (save-excursion
564 (beginning-of-line)
565 (setq thisblank (looking-at "[ \t]*$"))
566 ;; Set singleblank if there is just one blank line here.
567 (setq singleblank
568 (and thisblank
569 (not (looking-at "[ \t]*\n[ \t]*$"))
570 (or (bobp)
571 (progn (forward-line -1)
572 (not (looking-at "[ \t]*$")))))))
573 ;; Delete preceding blank lines, and this one too if it's the only one.
574 (if thisblank
575 (progn
576 (beginning-of-line)
577 (if singleblank (forward-line 1))
578 (delete-region (point)
579 (if (re-search-backward "[^ \t\n]" nil t)
580 (progn (forward-line 1) (point))
581 (point-min)))))
582 ;; Delete following blank lines, unless the current line is blank
583 ;; and there are no following blank lines.
584 (if (not (and thisblank singleblank))
585 (save-excursion
586 (end-of-line)
587 (forward-line 1)
588 (delete-region (point)
589 (if (re-search-forward "[^ \t\n]" nil t)
590 (progn (beginning-of-line) (point))
591 (point-max)))))
592 ;; Handle the special case where point is followed by newline and eob.
593 ;; Delete the line, leaving point at eob.
594 (if (looking-at "^[ \t]*\n\\'")
595 (delete-region (point) (point-max)))))
597 (defcustom delete-trailing-lines t
598 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
599 Trailing lines are deleted only if `delete-trailing-whitespace'
600 is called on the entire buffer (rather than an active region)."
601 :type 'boolean
602 :group 'editing
603 :version "24.3")
605 (defun delete-trailing-whitespace (&optional start end)
606 "Delete trailing whitespace between START and END.
607 If called interactively, START and END are the start/end of the
608 region if the mark is active, or of the buffer's accessible
609 portion if the mark is inactive.
611 This command deletes whitespace characters after the last
612 non-whitespace character in each line between START and END. It
613 does not consider formfeed characters to be whitespace.
615 If this command acts on the entire buffer (i.e. if called
616 interactively with the mark inactive, or called from Lisp with
617 END nil), it also deletes all trailing lines at the end of the
618 buffer if the variable `delete-trailing-lines' is non-nil."
619 (interactive (progn
620 (barf-if-buffer-read-only)
621 (if (use-region-p)
622 (list (region-beginning) (region-end))
623 (list nil nil))))
624 (save-match-data
625 (save-excursion
626 (let ((end-marker (and end (copy-marker end))))
627 (goto-char (or start (point-min)))
628 (with-syntax-table (make-syntax-table (syntax-table))
629 ;; Don't delete formfeeds, even if they are considered whitespace.
630 (modify-syntax-entry ?\f "_")
631 ;; Treating \n as non-whitespace makes things easier.
632 (modify-syntax-entry ?\n "_")
633 (while (re-search-forward "\\s-+$" end-marker t)
634 (delete-region (match-beginning 0) (match-end 0))))
635 (if end
636 (set-marker end-marker nil)
637 ;; Delete trailing empty lines.
638 (and delete-trailing-lines
639 ;; Really the end of buffer.
640 (= (goto-char (point-max)) (1+ (buffer-size)))
641 (<= (skip-chars-backward "\n") -2)
642 (delete-region (1+ (point)) (point-max)))))))
643 ;; Return nil for the benefit of `write-file-functions'.
644 nil)
646 (defun newline-and-indent ()
647 "Insert a newline, then indent according to major mode.
648 Indentation is done using the value of `indent-line-function'.
649 In programming language modes, this is the same as TAB.
650 In some text modes, where TAB inserts a tab, this command indents to the
651 column specified by the function `current-left-margin'."
652 (interactive "*")
653 (delete-horizontal-space t)
654 (newline nil t)
655 (indent-according-to-mode))
657 (defun reindent-then-newline-and-indent ()
658 "Reindent current line, insert newline, then indent the new line.
659 Indentation of both lines is done according to the current major mode,
660 which means calling the current value of `indent-line-function'.
661 In programming language modes, this is the same as TAB.
662 In some text modes, where TAB inserts a tab, this indents to the
663 column specified by the function `current-left-margin'."
664 (interactive "*")
665 (let ((pos (point)))
666 ;; Be careful to insert the newline before indenting the line.
667 ;; Otherwise, the indentation might be wrong.
668 (newline)
669 (save-excursion
670 (goto-char pos)
671 ;; We are at EOL before the call to indent-according-to-mode, and
672 ;; after it we usually are as well, but not always. We tried to
673 ;; address it with `save-excursion' but that uses a normal marker
674 ;; whereas we need `move after insertion', so we do the save/restore
675 ;; by hand.
676 (setq pos (copy-marker pos t))
677 (indent-according-to-mode)
678 (goto-char pos)
679 ;; Remove the trailing white-space after indentation because
680 ;; indentation may introduce the whitespace.
681 (delete-horizontal-space t))
682 (indent-according-to-mode)))
684 (defcustom read-quoted-char-radix 8
685 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
686 Legitimate radix values are 8, 10 and 16."
687 :type '(choice (const 8) (const 10) (const 16))
688 :group 'editing-basics)
690 (defun read-quoted-char (&optional prompt)
691 "Like `read-char', but do not allow quitting.
692 Also, if the first character read is an octal digit,
693 we read any number of octal digits and return the
694 specified character code. Any nondigit terminates the sequence.
695 If the terminator is RET, it is discarded;
696 any other terminator is used itself as input.
698 The optional argument PROMPT specifies a string to use to prompt the user.
699 The variable `read-quoted-char-radix' controls which radix to use
700 for numeric input."
701 (let ((message-log-max nil)
702 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
703 help-event-list)))
704 done (first t) (code 0) translated)
705 (while (not done)
706 (let ((inhibit-quit first)
707 ;; Don't let C-h or other help chars get the help
708 ;; message--only help function keys. See bug#16617.
709 (help-char nil)
710 (help-event-list help-events)
711 (help-form
712 "Type the special character you want to use,
713 or the octal character code.
714 RET terminates the character code and is discarded;
715 any other non-digit terminates the character code and is then used as input."))
716 (setq translated (read-key (and prompt (format "%s-" prompt))))
717 (if inhibit-quit (setq quit-flag nil)))
718 (if (integerp translated)
719 (setq translated (char-resolve-modifiers translated)))
720 (cond ((null translated))
721 ((not (integerp translated))
722 (setq unread-command-events
723 (nconc (listify-key-sequence (this-single-command-raw-keys))
724 unread-command-events)
725 done t))
726 ((/= (logand translated ?\M-\^@) 0)
727 ;; Turn a meta-character into a character with the 0200 bit set.
728 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
729 done t))
730 ((and (<= ?0 translated)
731 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
732 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
733 (and prompt (setq prompt (message "%s %c" prompt translated))))
734 ((and (<= ?a (downcase translated))
735 (< (downcase translated)
736 (+ ?a -10 (min 36 read-quoted-char-radix))))
737 (setq code (+ (* code read-quoted-char-radix)
738 (+ 10 (- (downcase translated) ?a))))
739 (and prompt (setq prompt (message "%s %c" prompt translated))))
740 ((and (not first) (eq translated ?\C-m))
741 (setq done t))
742 ((not first)
743 (setq unread-command-events
744 (nconc (listify-key-sequence (this-single-command-raw-keys))
745 unread-command-events)
746 done t))
747 (t (setq code translated
748 done t)))
749 (setq first nil))
750 code))
752 (defun quoted-insert (arg)
753 "Read next input character and insert it.
754 This is useful for inserting control characters.
755 With argument, insert ARG copies of the character.
757 If the first character you type after this command is an octal digit,
758 you should type a sequence of octal digits which specify a character code.
759 Any nondigit terminates the sequence. If the terminator is a RET,
760 it is discarded; any other terminator is used itself as input.
761 The variable `read-quoted-char-radix' specifies the radix for this feature;
762 set it to 10 or 16 to use decimal or hex instead of octal.
764 In overwrite mode, this function inserts the character anyway, and
765 does not handle octal digits specially. This means that if you use
766 overwrite as your normal editing mode, you can use this function to
767 insert characters when necessary.
769 In binary overwrite mode, this function does overwrite, and octal
770 digits are interpreted as a character code. This is intended to be
771 useful for editing binary files."
772 (interactive "*p")
773 (let* ((char
774 ;; Avoid "obsolete" warnings for translation-table-for-input.
775 (with-no-warnings
776 (let (translation-table-for-input input-method-function)
777 (if (or (not overwrite-mode)
778 (eq overwrite-mode 'overwrite-mode-binary))
779 (read-quoted-char)
780 (read-char))))))
781 ;; This used to assume character codes 0240 - 0377 stand for
782 ;; characters in some single-byte character set, and converted them
783 ;; to Emacs characters. But in 23.1 this feature is deprecated
784 ;; in favor of inserting the corresponding Unicode characters.
785 ;; (if (and enable-multibyte-characters
786 ;; (>= char ?\240)
787 ;; (<= char ?\377))
788 ;; (setq char (unibyte-char-to-multibyte char)))
789 (unless (characterp char)
790 (user-error "%s is not a valid character"
791 (key-description (vector char))))
792 (if (> arg 0)
793 (if (eq overwrite-mode 'overwrite-mode-binary)
794 (delete-char arg)))
795 (while (> arg 0)
796 (insert-and-inherit char)
797 (setq arg (1- arg)))))
799 (defun forward-to-indentation (&optional arg)
800 "Move forward ARG lines and position at first nonblank character."
801 (interactive "^p")
802 (forward-line (or arg 1))
803 (skip-chars-forward " \t"))
805 (defun backward-to-indentation (&optional arg)
806 "Move backward ARG lines and position at first nonblank character."
807 (interactive "^p")
808 (forward-line (- (or arg 1)))
809 (skip-chars-forward " \t"))
811 (defun back-to-indentation ()
812 "Move point to the first non-whitespace character on this line."
813 (interactive "^")
814 (beginning-of-line 1)
815 (skip-syntax-forward " " (line-end-position))
816 ;; Move back over chars that have whitespace syntax but have the p flag.
817 (backward-prefix-chars))
819 (defun fixup-whitespace ()
820 "Fixup white space between objects around point.
821 Leave one space or none, according to the context."
822 (interactive "*")
823 (save-excursion
824 (delete-horizontal-space)
825 (if (or (looking-at "^\\|\\s)")
826 (save-excursion (forward-char -1)
827 (looking-at "$\\|\\s(\\|\\s'")))
829 (insert ?\s))))
831 (defun delete-horizontal-space (&optional backward-only)
832 "Delete all spaces and tabs around point.
833 If BACKWARD-ONLY is non-nil, only delete them before point."
834 (interactive "*P")
835 (let ((orig-pos (point)))
836 (delete-region
837 (if backward-only
838 orig-pos
839 (progn
840 (skip-chars-forward " \t")
841 (constrain-to-field nil orig-pos t)))
842 (progn
843 (skip-chars-backward " \t")
844 (constrain-to-field nil orig-pos)))))
846 (defun just-one-space (&optional n)
847 "Delete all spaces and tabs around point, leaving one space (or N spaces).
848 If N is negative, delete newlines as well, leaving -N spaces.
849 See also `cycle-spacing'."
850 (interactive "*p")
851 (cycle-spacing n nil 'single-shot))
853 (defvar cycle-spacing--context nil
854 "Store context used in consecutive calls to `cycle-spacing' command.
855 The first time `cycle-spacing' runs, it saves in this variable:
856 its N argument, the original point position, and the original spacing
857 around point.")
859 (defun cycle-spacing (&optional n preserve-nl-back mode)
860 "Manipulate whitespace around point in a smart way.
861 In interactive use, this function behaves differently in successive
862 consecutive calls.
864 The first call in a sequence acts like `just-one-space'.
865 It deletes all spaces and tabs around point, leaving one space
866 \(or N spaces). N is the prefix argument. If N is negative,
867 it deletes newlines as well, leaving -N spaces.
868 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
870 The second call in a sequence deletes all spaces.
872 The third call in a sequence restores the original whitespace (and point).
874 If MODE is `single-shot', it only performs the first step in the sequence.
875 If MODE is `fast' and the first step would not result in any change
876 \(i.e., there are exactly (abs N) spaces around point),
877 the function goes straight to the second step.
879 Repeatedly calling the function with different values of N starts a
880 new sequence each time."
881 (interactive "*p")
882 (let ((orig-pos (point))
883 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
884 (num (abs (or n 1))))
885 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
886 (constrain-to-field nil orig-pos)
887 (cond
888 ;; Command run for the first time, single-shot mode or different argument
889 ((or (eq 'single-shot mode)
890 (not (equal last-command this-command))
891 (not cycle-spacing--context)
892 (not (eq (car cycle-spacing--context) n)))
893 (let* ((start (point))
894 (num (- num (skip-chars-forward " " (+ num (point)))))
895 (mid (point))
896 (end (progn
897 (skip-chars-forward skip-characters)
898 (constrain-to-field nil orig-pos t))))
899 (setq cycle-spacing--context ;; Save for later.
900 ;; Special handling for case where there was no space at all.
901 (unless (= start end)
902 (cons n (cons orig-pos (buffer-substring start (point))))))
903 ;; If this run causes no change in buffer content, delete all spaces,
904 ;; otherwise delete all excess spaces.
905 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
906 start mid) end)
907 (insert (make-string num ?\s))))
909 ;; Command run for the second time.
910 ((not (equal orig-pos (point)))
911 (delete-region (point) orig-pos))
913 ;; Command run for the third time.
915 (insert (cddr cycle-spacing--context))
916 (goto-char (cadr cycle-spacing--context))
917 (setq cycle-spacing--context nil)))))
919 (defun beginning-of-buffer (&optional arg)
920 "Move point to the beginning of the buffer.
921 With numeric arg N, put point N/10 of the way from the beginning.
922 If the buffer is narrowed, this command uses the beginning of the
923 accessible part of the buffer.
925 Push mark at previous position, unless either a \\[universal-argument] prefix
926 is supplied, or Transient Mark mode is enabled and the mark is active."
927 (declare (interactive-only "use `(goto-char (point-min))' instead."))
928 (interactive "^P")
929 (or (consp arg)
930 (region-active-p)
931 (push-mark))
932 (let ((size (- (point-max) (point-min))))
933 (goto-char (if (and arg (not (consp arg)))
934 (+ (point-min)
935 (if (> size 10000)
936 ;; Avoid overflow for large buffer sizes!
937 (* (prefix-numeric-value arg)
938 (/ size 10))
939 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
940 (point-min))))
941 (if (and arg (not (consp arg))) (forward-line 1)))
943 (defun end-of-buffer (&optional arg)
944 "Move point to the end of the buffer.
945 With numeric arg N, put point N/10 of the way from the end.
946 If the buffer is narrowed, this command uses the end of the
947 accessible part of the buffer.
949 Push mark at previous position, unless either a \\[universal-argument] prefix
950 is supplied, or Transient Mark mode is enabled and the mark is active."
951 (declare (interactive-only "use `(goto-char (point-max))' instead."))
952 (interactive "^P")
953 (or (consp arg) (region-active-p) (push-mark))
954 (let ((size (- (point-max) (point-min))))
955 (goto-char (if (and arg (not (consp arg)))
956 (- (point-max)
957 (if (> size 10000)
958 ;; Avoid overflow for large buffer sizes!
959 (* (prefix-numeric-value arg)
960 (/ size 10))
961 (/ (* size (prefix-numeric-value arg)) 10)))
962 (point-max))))
963 ;; If we went to a place in the middle of the buffer,
964 ;; adjust it to the beginning of a line.
965 (cond ((and arg (not (consp arg))) (forward-line 1))
966 ((and (eq (current-buffer) (window-buffer))
967 (> (point) (window-end nil t)))
968 ;; If the end of the buffer is not already on the screen,
969 ;; then scroll specially to put it near, but not at, the bottom.
970 (overlay-recenter (point))
971 (recenter -3))))
973 (defcustom delete-active-region t
974 "Whether single-char deletion commands delete an active region.
975 This has an effect only if Transient Mark mode is enabled, and
976 affects `delete-forward-char' and `delete-backward-char', though
977 not `delete-char'.
979 If the value is the symbol `kill', the active region is killed
980 instead of deleted."
981 :type '(choice (const :tag "Delete active region" t)
982 (const :tag "Kill active region" kill)
983 (const :tag "Do ordinary deletion" nil))
984 :group 'killing
985 :version "24.1")
987 (defvar region-extract-function
988 (lambda (delete)
989 (when (region-beginning)
990 (cond
991 ((eq delete 'bounds)
992 (list (cons (region-beginning) (region-end))))
993 ((eq delete 'delete-only)
994 (delete-region (region-beginning) (region-end)))
996 (filter-buffer-substring (region-beginning) (region-end) delete)))))
997 "Function to get the region's content.
998 Called with one argument DELETE.
999 If DELETE is `delete-only', then only delete the region and the return value
1000 is undefined. If DELETE is nil, just return the content as a string.
1001 If DELETE is `bounds', then don't delete, but just return the
1002 boundaries of the region as a list of (START . END) positions.
1003 If anything else, delete the region and return its content as a string,
1004 after filtering it with `filter-buffer-substring'.")
1006 (defvar region-insert-function
1007 (lambda (lines)
1008 (let ((first t))
1009 (while lines
1010 (or first
1011 (insert ?\n))
1012 (insert-for-yank (car lines))
1013 (setq lines (cdr lines)
1014 first nil))))
1015 "Function to insert the region's content.
1016 Called with one argument LINES.
1017 Insert the region as a list of lines.")
1019 (defun delete-backward-char (n &optional killflag)
1020 "Delete the previous N characters (following if N is negative).
1021 If Transient Mark mode is enabled, the mark is active, and N is 1,
1022 delete the text in the region and deactivate the mark instead.
1023 To disable this, set option `delete-active-region' to nil.
1025 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1026 kill ring) instead of delete. Interactively, N is the prefix
1027 arg, and KILLFLAG is set if N is explicitly specified.
1029 When killing, the killed text is filtered by
1030 `filter-buffer-substring' before it is saved in the kill ring, so
1031 the actual saved text might be different from what was killed.
1033 In Overwrite mode, single character backward deletion may replace
1034 tabs with spaces so as to back over columns, unless point is at
1035 the end of the line."
1036 (declare (interactive-only delete-char))
1037 (interactive "p\nP")
1038 (unless (integerp n)
1039 (signal 'wrong-type-argument (list 'integerp n)))
1040 (cond ((and (use-region-p)
1041 delete-active-region
1042 (= n 1))
1043 ;; If a region is active, kill or delete it.
1044 (if (eq delete-active-region 'kill)
1045 (kill-region (region-beginning) (region-end) 'region)
1046 (funcall region-extract-function 'delete-only)))
1047 ;; In Overwrite mode, maybe untabify while deleting
1048 ((null (or (null overwrite-mode)
1049 (<= n 0)
1050 (memq (char-before) '(?\t ?\n))
1051 (eobp)
1052 (eq (char-after) ?\n)))
1053 (let ((ocol (current-column)))
1054 (delete-char (- n) killflag)
1055 (save-excursion
1056 (insert-char ?\s (- ocol (current-column)) nil))))
1057 ;; Otherwise, do simple deletion.
1058 (t (delete-char (- n) killflag))))
1060 (defun delete-forward-char (n &optional killflag)
1061 "Delete the following N characters (previous if N is negative).
1062 If Transient Mark mode is enabled, the mark is active, and N is 1,
1063 delete the text in the region and deactivate the mark instead.
1064 To disable this, set variable `delete-active-region' to nil.
1066 Optional second arg KILLFLAG non-nil means to kill (save in kill
1067 ring) instead of delete. Interactively, N is the prefix arg, and
1068 KILLFLAG is set if N was explicitly specified.
1070 When killing, the killed text is filtered by
1071 `filter-buffer-substring' before it is saved in the kill ring, so
1072 the actual saved text might be different from what was killed."
1073 (declare (interactive-only delete-char))
1074 (interactive "p\nP")
1075 (unless (integerp n)
1076 (signal 'wrong-type-argument (list 'integerp n)))
1077 (cond ((and (use-region-p)
1078 delete-active-region
1079 (= n 1))
1080 ;; If a region is active, kill or delete it.
1081 (if (eq delete-active-region 'kill)
1082 (kill-region (region-beginning) (region-end) 'region)
1083 (funcall region-extract-function 'delete-only)))
1085 ;; Otherwise, do simple deletion.
1086 (t (delete-char n killflag))))
1088 (defun mark-whole-buffer ()
1089 "Put point at beginning and mark at end of buffer.
1090 If narrowing is in effect, only uses the accessible part of the buffer.
1091 You probably should not use this function in Lisp programs;
1092 it is usually a mistake for a Lisp function to use any subroutine
1093 that uses or sets the mark."
1094 (declare (interactive-only t))
1095 (interactive)
1096 (push-mark (point))
1097 (push-mark (point-max) nil t)
1098 ;; This is really `point-min' in most cases, but if we're in the
1099 ;; minibuffer, this is at the end of the prompt.
1100 (goto-char (minibuffer-prompt-end)))
1103 ;; Counting lines, one way or another.
1105 (defun goto-line (line &optional buffer)
1106 "Go to LINE, counting from line 1 at beginning of buffer.
1107 If called interactively, a numeric prefix argument specifies
1108 LINE; without a numeric prefix argument, read LINE from the
1109 minibuffer.
1111 If optional argument BUFFER is non-nil, switch to that buffer and
1112 move to line LINE there. If called interactively with \\[universal-argument]
1113 as argument, BUFFER is the most recently selected other buffer.
1115 Prior to moving point, this function sets the mark (without
1116 activating it), unless Transient Mark mode is enabled and the
1117 mark is already active.
1119 This function is usually the wrong thing to use in a Lisp program.
1120 What you probably want instead is something like:
1121 (goto-char (point-min))
1122 (forward-line (1- N))
1123 If at all possible, an even better solution is to use char counts
1124 rather than line counts."
1125 (declare (interactive-only forward-line))
1126 (interactive
1127 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1128 (list (prefix-numeric-value current-prefix-arg))
1129 ;; Look for a default, a number in the buffer at point.
1130 (let* ((default
1131 (save-excursion
1132 (skip-chars-backward "0-9")
1133 (if (looking-at "[0-9]")
1134 (string-to-number
1135 (buffer-substring-no-properties
1136 (point)
1137 (progn (skip-chars-forward "0-9")
1138 (point)))))))
1139 ;; Decide if we're switching buffers.
1140 (buffer
1141 (if (consp current-prefix-arg)
1142 (other-buffer (current-buffer) t)))
1143 (buffer-prompt
1144 (if buffer
1145 (concat " in " (buffer-name buffer))
1146 "")))
1147 ;; Read the argument, offering that number (if any) as default.
1148 (list (read-number (format "Goto line%s: " buffer-prompt)
1149 (list default (line-number-at-pos)))
1150 buffer))))
1151 ;; Switch to the desired buffer, one way or another.
1152 (if buffer
1153 (let ((window (get-buffer-window buffer)))
1154 (if window (select-window window)
1155 (switch-to-buffer-other-window buffer))))
1156 ;; Leave mark at previous position
1157 (or (region-active-p) (push-mark))
1158 ;; Move to the specified line number in that buffer.
1159 (save-restriction
1160 (widen)
1161 (goto-char (point-min))
1162 (if (eq selective-display t)
1163 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1164 (forward-line (1- line)))))
1166 (defun count-words-region (start end &optional arg)
1167 "Count the number of words in the region.
1168 If called interactively, print a message reporting the number of
1169 lines, words, and characters in the region (whether or not the
1170 region is active); with prefix ARG, report for the entire buffer
1171 rather than the region.
1173 If called from Lisp, return the number of words between positions
1174 START and END."
1175 (interactive (if current-prefix-arg
1176 (list nil nil current-prefix-arg)
1177 (list (region-beginning) (region-end) nil)))
1178 (cond ((not (called-interactively-p 'any))
1179 (count-words start end))
1180 (arg
1181 (count-words--buffer-message))
1183 (count-words--message "Region" start end))))
1185 (defun count-words (start end)
1186 "Count words between START and END.
1187 If called interactively, START and END are normally the start and
1188 end of the buffer; but if the region is active, START and END are
1189 the start and end of the region. Print a message reporting the
1190 number of lines, words, and chars.
1192 If called from Lisp, return the number of words between START and
1193 END, without printing any message."
1194 (interactive (list nil nil))
1195 (cond ((not (called-interactively-p 'any))
1196 (let ((words 0))
1197 (save-excursion
1198 (save-restriction
1199 (narrow-to-region start end)
1200 (goto-char (point-min))
1201 (while (forward-word-strictly 1)
1202 (setq words (1+ words)))))
1203 words))
1204 ((use-region-p)
1205 (call-interactively 'count-words-region))
1207 (count-words--buffer-message))))
1209 (defun count-words--buffer-message ()
1210 (count-words--message
1211 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1212 (point-min) (point-max)))
1214 (defun count-words--message (str start end)
1215 (let ((lines (count-lines start end))
1216 (words (count-words start end))
1217 (chars (- end start)))
1218 (message "%s has %d line%s, %d word%s, and %d character%s."
1220 lines (if (= lines 1) "" "s")
1221 words (if (= words 1) "" "s")
1222 chars (if (= chars 1) "" "s"))))
1224 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1226 (defun what-line ()
1227 "Print the current buffer line number and narrowed line number of point."
1228 (interactive)
1229 (let ((start (point-min))
1230 (n (line-number-at-pos)))
1231 (if (= start 1)
1232 (message "Line %d" n)
1233 (save-excursion
1234 (save-restriction
1235 (widen)
1236 (message "line %d (narrowed line %d)"
1237 (+ n (line-number-at-pos start) -1) n))))))
1239 (defun count-lines (start end)
1240 "Return number of lines between START and END.
1241 This is usually the number of newlines between them,
1242 but can be one more if START is not equal to END
1243 and the greater of them is not at the start of a line."
1244 (save-excursion
1245 (save-restriction
1246 (narrow-to-region start end)
1247 (goto-char (point-min))
1248 (if (eq selective-display t)
1249 (save-match-data
1250 (let ((done 0))
1251 (while (re-search-forward "[\n\C-m]" nil t 40)
1252 (setq done (+ 40 done)))
1253 (while (re-search-forward "[\n\C-m]" nil t 1)
1254 (setq done (+ 1 done)))
1255 (goto-char (point-max))
1256 (if (and (/= start end)
1257 (not (bolp)))
1258 (1+ done)
1259 done)))
1260 (- (buffer-size) (forward-line (buffer-size)))))))
1262 (defun line-number-at-pos (&optional pos)
1263 "Return (narrowed) buffer line number at position POS.
1264 If POS is nil, use current buffer location.
1265 Counting starts at (point-min), so the value refers
1266 to the contents of the accessible portion of the buffer."
1267 (let ((opoint (or pos (point))) start)
1268 (save-excursion
1269 (goto-char (point-min))
1270 (setq start (point))
1271 (goto-char opoint)
1272 (forward-line 0)
1273 (1+ (count-lines start (point))))))
1275 (defun what-cursor-position (&optional detail)
1276 "Print info on cursor position (on screen and within buffer).
1277 Also describe the character after point, and give its character code
1278 in octal, decimal and hex.
1280 For a non-ASCII multibyte character, also give its encoding in the
1281 buffer's selected coding system if the coding system encodes the
1282 character safely. If the character is encoded into one byte, that
1283 code is shown in hex. If the character is encoded into more than one
1284 byte, just \"...\" is shown.
1286 In addition, with prefix argument, show details about that character
1287 in *Help* buffer. See also the command `describe-char'."
1288 (interactive "P")
1289 (let* ((char (following-char))
1290 (bidi-fixer
1291 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1292 ;; start a directional embedding, which could completely
1293 ;; disrupt the rest of the line (e.g., RLO will display the
1294 ;; rest of the line right-to-left). So we put an invisible
1295 ;; PDF character after these characters, to end the
1296 ;; embedding, which eliminates any effects on the rest of
1297 ;; the line. For RLE and RLO we also append an invisible
1298 ;; LRM, to avoid reordering the following numerical
1299 ;; characters. For LRI/RLI/FSI we append a PDI.
1300 (cond ((memq char '(?\x202a ?\x202d))
1301 (propertize (string ?\x202c) 'invisible t))
1302 ((memq char '(?\x202b ?\x202e))
1303 (propertize (string ?\x202c ?\x200e) 'invisible t))
1304 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1305 (propertize (string ?\x2069) 'invisible t))
1306 ;; Strong right-to-left characters cause reordering of
1307 ;; the following numerical characters which show the
1308 ;; codepoint, so append LRM to countermand that.
1309 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1310 (propertize (string ?\x200e) 'invisible t))
1312 "")))
1313 (beg (point-min))
1314 (end (point-max))
1315 (pos (point))
1316 (total (buffer-size))
1317 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1318 (hscroll (if (= (window-hscroll) 0)
1320 (format " Hscroll=%d" (window-hscroll))))
1321 (col (current-column)))
1322 (if (= pos end)
1323 (if (or (/= beg 1) (/= end (1+ total)))
1324 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1325 pos total percent beg end col hscroll)
1326 (message "point=%d of %d (EOB) column=%d%s"
1327 pos total col hscroll))
1328 (let ((coding buffer-file-coding-system)
1329 encoded encoding-msg display-prop under-display)
1330 (if (or (not coding)
1331 (eq (coding-system-type coding) t))
1332 (setq coding (default-value 'buffer-file-coding-system)))
1333 (if (eq (char-charset char) 'eight-bit)
1334 (setq encoding-msg
1335 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1336 ;; Check if the character is displayed with some `display'
1337 ;; text property. In that case, set under-display to the
1338 ;; buffer substring covered by that property.
1339 (setq display-prop (get-char-property pos 'display))
1340 (if display-prop
1341 (let ((to (or (next-single-char-property-change pos 'display)
1342 (point-max))))
1343 (if (< to (+ pos 4))
1344 (setq under-display "")
1345 (setq under-display "..."
1346 to (+ pos 4)))
1347 (setq under-display
1348 (concat (buffer-substring-no-properties pos to)
1349 under-display)))
1350 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1351 (setq encoding-msg
1352 (if display-prop
1353 (if (not (stringp display-prop))
1354 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1355 char char char under-display)
1356 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1357 char char char under-display display-prop))
1358 (if encoded
1359 (format "(%d, #o%o, #x%x, file %s)"
1360 char char char
1361 (if (> (length encoded) 1)
1362 "..."
1363 (encoded-string-description encoded coding)))
1364 (format "(%d, #o%o, #x%x)" char char char)))))
1365 (if detail
1366 ;; We show the detailed information about CHAR.
1367 (describe-char (point)))
1368 (if (or (/= beg 1) (/= end (1+ total)))
1369 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1370 (if (< char 256)
1371 (single-key-description char)
1372 (buffer-substring-no-properties (point) (1+ (point))))
1373 bidi-fixer
1374 encoding-msg pos total percent beg end col hscroll)
1375 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1376 (if enable-multibyte-characters
1377 (if (< char 128)
1378 (single-key-description char)
1379 (buffer-substring-no-properties (point) (1+ (point))))
1380 (single-key-description char))
1381 bidi-fixer encoding-msg pos total percent col hscroll))))))
1383 ;; Initialize read-expression-map. It is defined at C level.
1384 (defvar read-expression-map
1385 (let ((m (make-sparse-keymap)))
1386 (define-key m "\M-\t" 'completion-at-point)
1387 ;; Might as well bind TAB to completion, since inserting a TAB char is
1388 ;; much too rarely useful.
1389 (define-key m "\t" 'completion-at-point)
1390 (set-keymap-parent m minibuffer-local-map)
1393 (defun read-minibuffer (prompt &optional initial-contents)
1394 "Return a Lisp object read using the minibuffer, unevaluated.
1395 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1396 is a string to insert in the minibuffer before reading.
1397 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1398 Such arguments are used as in `read-from-minibuffer'.)"
1399 ;; Used for interactive spec `x'.
1400 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1401 t 'minibuffer-history))
1403 (defun eval-minibuffer (prompt &optional initial-contents)
1404 "Return value of Lisp expression read using the minibuffer.
1405 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1406 is a string to insert in the minibuffer before reading.
1407 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1408 Such arguments are used as in `read-from-minibuffer'.)"
1409 ;; Used for interactive spec `X'.
1410 (eval (read--expression prompt initial-contents)))
1412 (defvar minibuffer-completing-symbol nil
1413 "Non-nil means completing a Lisp symbol in the minibuffer.")
1414 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1416 (defvar minibuffer-default nil
1417 "The current default value or list of default values in the minibuffer.
1418 The functions `read-from-minibuffer' and `completing-read' bind
1419 this variable locally.")
1421 (defcustom eval-expression-print-level 4
1422 "Value for `print-level' while printing value in `eval-expression'.
1423 A value of nil means no limit."
1424 :group 'lisp
1425 :type '(choice (const :tag "No Limit" nil) integer)
1426 :version "21.1")
1428 (defcustom eval-expression-print-length 12
1429 "Value for `print-length' while printing value in `eval-expression'.
1430 A value of nil means no limit."
1431 :group 'lisp
1432 :type '(choice (const :tag "No Limit" nil) integer)
1433 :version "21.1")
1435 (defcustom eval-expression-debug-on-error t
1436 "If non-nil set `debug-on-error' to t in `eval-expression'.
1437 If nil, don't change the value of `debug-on-error'."
1438 :group 'lisp
1439 :type 'boolean
1440 :version "21.1")
1442 (defun eval-expression-print-format (value)
1443 "If VALUE in an integer, return a specially formatted string.
1444 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1445 If VALUE is not an integer, nil is returned.
1446 This function is used by functions like `prin1' that display the
1447 result of expression evaluation."
1448 (if (and (integerp value)
1449 (or (eq standard-output t)
1450 (zerop (prefix-numeric-value current-prefix-arg))))
1451 (let ((char-string
1452 (if (and (characterp value)
1453 (char-displayable-p value))
1454 (prin1-char value))))
1455 (if char-string
1456 (format " (#o%o, #x%x, %s)" value value char-string)
1457 (format " (#o%o, #x%x)" value value)))))
1459 (defvar eval-expression-minibuffer-setup-hook nil
1460 "Hook run by `eval-expression' when entering the minibuffer.")
1462 (defun read--expression (prompt &optional initial-contents)
1463 (let ((minibuffer-completing-symbol t))
1464 (minibuffer-with-setup-hook
1465 (lambda ()
1466 ;; FIXME: call emacs-lisp-mode?
1467 (add-function :before-until (local 'eldoc-documentation-function)
1468 #'elisp-eldoc-documentation-function)
1469 (add-hook 'completion-at-point-functions
1470 #'elisp-completion-at-point nil t)
1471 (run-hooks 'eval-expression-minibuffer-setup-hook))
1472 (read-from-minibuffer prompt initial-contents
1473 read-expression-map t
1474 'read-expression-history))))
1476 ;; We define this, rather than making `eval' interactive,
1477 ;; for the sake of completion of names like eval-region, eval-buffer.
1478 (defun eval-expression (exp &optional insert-value)
1479 "Evaluate EXP and print value in the echo area.
1480 When called interactively, read an Emacs Lisp expression and evaluate it.
1481 Value is also consed on to front of the variable `values'.
1482 If the resulting value is an integer, it will be printed in
1483 several additional formats (octal, hexadecimal, and character).
1484 Optional argument INSERT-VALUE non-nil (interactively, with
1485 prefix argument) means insert the result into the current buffer
1486 instead of printing it in the echo area.
1488 Normally, this function truncates long output according to the value
1489 of the variables `eval-expression-print-length' and
1490 `eval-expression-print-level'. With a prefix argument of zero,
1491 however, there is no such truncation.
1493 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1494 minibuffer.
1496 If `eval-expression-debug-on-error' is non-nil, which is the default,
1497 this command arranges for all errors to enter the debugger."
1498 (interactive
1499 (list (read--expression "Eval: ")
1500 current-prefix-arg))
1502 (if (null eval-expression-debug-on-error)
1503 (push (eval exp lexical-binding) values)
1504 (let ((old-value (make-symbol "t")) new-value)
1505 ;; Bind debug-on-error to something unique so that we can
1506 ;; detect when evalled code changes it.
1507 (let ((debug-on-error old-value))
1508 (push (eval (macroexpand-all exp) lexical-binding) values)
1509 (setq new-value debug-on-error))
1510 ;; If evalled code has changed the value of debug-on-error,
1511 ;; propagate that change to the global binding.
1512 (unless (eq old-value new-value)
1513 (setq debug-on-error new-value))))
1515 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1516 eval-expression-print-length))
1517 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1518 eval-expression-print-level))
1519 (deactivate-mark))
1520 (if insert-value
1521 (with-no-warnings
1522 (let ((standard-output (current-buffer)))
1523 (prog1
1524 (prin1 (car values))
1525 (when (zerop (prefix-numeric-value insert-value))
1526 (let ((str (eval-expression-print-format (car values))))
1527 (if str (princ str)))))))
1528 (prog1
1529 (prin1 (car values) t)
1530 (let ((str (eval-expression-print-format (car values))))
1531 (if str (princ str t)))))))
1533 (defun edit-and-eval-command (prompt command)
1534 "Prompting with PROMPT, let user edit COMMAND and eval result.
1535 COMMAND is a Lisp expression. Let user edit that expression in
1536 the minibuffer, then read and evaluate the result."
1537 (let ((command
1538 (let ((print-level nil)
1539 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1540 (unwind-protect
1541 (read-from-minibuffer prompt
1542 (prin1-to-string command)
1543 read-expression-map t
1544 'command-history)
1545 ;; If command was added to command-history as a string,
1546 ;; get rid of that. We want only evaluable expressions there.
1547 (if (stringp (car command-history))
1548 (setq command-history (cdr command-history)))))))
1550 ;; If command to be redone does not match front of history,
1551 ;; add it to the history.
1552 (or (equal command (car command-history))
1553 (setq command-history (cons command command-history)))
1554 (eval command)))
1556 (defun repeat-complex-command (arg)
1557 "Edit and re-evaluate last complex command, or ARGth from last.
1558 A complex command is one which used the minibuffer.
1559 The command is placed in the minibuffer as a Lisp form for editing.
1560 The result is executed, repeating the command as changed.
1561 If the command has been changed or is not the most recent previous
1562 command it is added to the front of the command history.
1563 You can use the minibuffer history commands \
1564 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1565 to get different commands to edit and resubmit."
1566 (interactive "p")
1567 (let ((elt (nth (1- arg) command-history))
1568 newcmd)
1569 (if elt
1570 (progn
1571 (setq newcmd
1572 (let ((print-level nil)
1573 (minibuffer-history-position arg)
1574 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1575 (unwind-protect
1576 (read-from-minibuffer
1577 "Redo: " (prin1-to-string elt) read-expression-map t
1578 (cons 'command-history arg))
1580 ;; If command was added to command-history as a
1581 ;; string, get rid of that. We want only
1582 ;; evaluable expressions there.
1583 (if (stringp (car command-history))
1584 (setq command-history (cdr command-history))))))
1586 ;; If command to be redone does not match front of history,
1587 ;; add it to the history.
1588 (or (equal newcmd (car command-history))
1589 (setq command-history (cons newcmd command-history)))
1590 (apply #'funcall-interactively
1591 (car newcmd)
1592 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1593 (if command-history
1594 (error "Argument %d is beyond length of command history" arg)
1595 (error "There are no previous complex commands to repeat")))))
1598 (defvar extended-command-history nil)
1599 (defvar execute-extended-command--last-typed nil)
1601 (defun read-extended-command ()
1602 "Read command name to invoke in `execute-extended-command'."
1603 (minibuffer-with-setup-hook
1604 (lambda ()
1605 (add-hook 'post-self-insert-hook
1606 (lambda ()
1607 (setq execute-extended-command--last-typed
1608 (minibuffer-contents)))
1609 nil 'local)
1610 (set (make-local-variable 'minibuffer-default-add-function)
1611 (lambda ()
1612 ;; Get a command name at point in the original buffer
1613 ;; to propose it after M-n.
1614 (with-current-buffer (window-buffer (minibuffer-selected-window))
1615 (and (commandp (function-called-at-point))
1616 (format "%S" (function-called-at-point)))))))
1617 ;; Read a string, completing from and restricting to the set of
1618 ;; all defined commands. Don't provide any initial input.
1619 ;; Save the command read on the extended-command history list.
1620 (completing-read
1621 (concat (cond
1622 ((eq current-prefix-arg '-) "- ")
1623 ((and (consp current-prefix-arg)
1624 (eq (car current-prefix-arg) 4)) "C-u ")
1625 ((and (consp current-prefix-arg)
1626 (integerp (car current-prefix-arg)))
1627 (format "%d " (car current-prefix-arg)))
1628 ((integerp current-prefix-arg)
1629 (format "%d " current-prefix-arg)))
1630 ;; This isn't strictly correct if `execute-extended-command'
1631 ;; is bound to anything else (e.g. [menu]).
1632 ;; It could use (key-description (this-single-command-keys)),
1633 ;; but actually a prompt other than "M-x" would be confusing,
1634 ;; because "M-x" is a well-known prompt to read a command
1635 ;; and it serves as a shorthand for "Extended command: ".
1636 "M-x ")
1637 (lambda (string pred action)
1638 (let ((pred
1639 (if (memq action '(nil t))
1640 ;; Exclude obsolete commands from completions.
1641 (lambda (sym)
1642 (and (funcall pred sym)
1643 (or (equal string (symbol-name sym))
1644 (not (get sym 'byte-obsolete-info)))))
1645 pred)))
1646 (complete-with-action action obarray string pred)))
1647 #'commandp t nil 'extended-command-history)))
1649 (defcustom suggest-key-bindings t
1650 "Non-nil means show the equivalent key-binding when M-x command has one.
1651 The value can be a length of time to show the message for.
1652 If the value is non-nil and not a number, we wait 2 seconds."
1653 :group 'keyboard
1654 :type '(choice (const :tag "off" nil)
1655 (integer :tag "time" 2)
1656 (other :tag "on")))
1658 (defcustom extended-command-suggest-shorter t
1659 "If non-nil, show a shorter M-x invocation when there is one."
1660 :group 'keyboard
1661 :type 'boolean
1662 :version "25.2")
1664 (defun execute-extended-command--shorter-1 (name length)
1665 (cond
1666 ((zerop length) (list ""))
1667 ((equal name "") nil)
1669 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1670 (execute-extended-command--shorter-1
1671 (substring name 1) (1- length)))
1672 (when (string-match "\\`\\(-\\)?[^-]*" name)
1673 (execute-extended-command--shorter-1
1674 (substring name (match-end 0)) length))))))
1676 (defun execute-extended-command--shorter (name typed)
1677 (let ((candidates '())
1678 (max (length typed))
1679 (len 1)
1680 binding)
1681 (while (and (not binding)
1682 (progn
1683 (unless candidates
1684 (setq len (1+ len))
1685 (setq candidates (execute-extended-command--shorter-1
1686 name len)))
1687 ;; Don't show the help message if the binding isn't
1688 ;; significantly shorter than the M-x command the user typed.
1689 (< len (- max 5))))
1690 (let ((candidate (pop candidates)))
1691 (when (equal name
1692 (car-safe (completion-try-completion
1693 candidate obarray 'commandp len)))
1694 (setq binding candidate))))
1695 binding))
1697 (defun execute-extended-command (prefixarg &optional command-name typed)
1698 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1699 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1700 "Read a command name, then read the arguments and call the command.
1701 To pass a prefix argument to the command you are
1702 invoking, give a prefix argument to `execute-extended-command'."
1703 (declare (interactive-only command-execute))
1704 ;; FIXME: Remember the actual text typed by the user before completion,
1705 ;; so that we don't later on suggest the same shortening.
1706 (interactive
1707 (let ((execute-extended-command--last-typed nil))
1708 (list current-prefix-arg
1709 (read-extended-command)
1710 execute-extended-command--last-typed)))
1711 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1712 (unless command-name
1713 (let ((current-prefix-arg prefixarg) ; for prompt
1714 (execute-extended-command--last-typed nil))
1715 (setq command-name (read-extended-command))
1716 (setq typed execute-extended-command--last-typed)))
1717 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1718 (binding (and suggest-key-bindings
1719 (not executing-kbd-macro)
1720 (where-is-internal function overriding-local-map t))))
1721 (unless (commandp function)
1722 (error "`%s' is not a valid command name" command-name))
1723 (setq this-command function)
1724 ;; Normally `real-this-command' should never be changed, but here we really
1725 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1726 ;; binding" for <cmd>, so the command the user really wanted to run is
1727 ;; `function' and not `execute-extended-command'. The difference is
1728 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1729 (setq real-this-command function)
1730 (let ((prefix-arg prefixarg))
1731 (command-execute function 'record))
1732 ;; If enabled, show which key runs this command.
1733 ;; But first wait, and skip the message if there is input.
1734 (let* ((waited
1735 ;; If this command displayed something in the echo area;
1736 ;; wait a few seconds, then display our suggestion message.
1737 ;; FIXME: Wait *after* running post-command-hook!
1738 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1739 ;; find a better answer anyway!
1740 (when suggest-key-bindings
1741 (sit-for (cond
1742 ((zerop (length (current-message))) 0)
1743 ((numberp suggest-key-bindings) suggest-key-bindings)
1744 (t 2))))))
1745 (when (and waited (not (consp unread-command-events)))
1746 (unless (or (not extended-command-suggest-shorter)
1747 binding executing-kbd-macro (not (symbolp function))
1748 (<= (length (symbol-name function)) 2))
1749 ;; There's no binding for CMD. Let's try and find the shortest
1750 ;; string to use in M-x.
1751 ;; FIXME: Can be slow. Cache it maybe?
1752 (while-no-input
1753 (setq binding (execute-extended-command--shorter
1754 (symbol-name function) typed))))
1755 (when binding
1756 (with-temp-message
1757 (format-message "You can run the command `%s' with %s"
1758 function
1759 (if (stringp binding)
1760 (concat "M-x " binding " RET")
1761 (key-description binding)))
1762 (sit-for (if (numberp suggest-key-bindings)
1763 suggest-key-bindings
1764 2))))))))
1766 (defun command-execute (cmd &optional record-flag keys special)
1767 ;; BEWARE: Called directly from the C code.
1768 "Execute CMD as an editor command.
1769 CMD must be a symbol that satisfies the `commandp' predicate.
1770 Optional second arg RECORD-FLAG non-nil
1771 means unconditionally put this command in the variable `command-history'.
1772 Otherwise, that is done only if an arg is read using the minibuffer.
1773 The argument KEYS specifies the value to use instead of (this-command-keys)
1774 when reading the arguments; if it is nil, (this-command-keys) is used.
1775 The argument SPECIAL, if non-nil, means that this command is executing
1776 a special event, so ignore the prefix argument and don't clear it."
1777 (setq debug-on-next-call nil)
1778 (let ((prefixarg (unless special
1779 ;; FIXME: This should probably be done around
1780 ;; pre-command-hook rather than here!
1781 (prog1 prefix-arg
1782 (setq current-prefix-arg prefix-arg)
1783 (setq prefix-arg nil)
1784 (when current-prefix-arg
1785 (prefix-command-update))))))
1786 (if (and (symbolp cmd)
1787 (get cmd 'disabled)
1788 disabled-command-function)
1789 ;; FIXME: Weird calling convention!
1790 (run-hooks 'disabled-command-function)
1791 (let ((final cmd))
1792 (while
1793 (progn
1794 (setq final (indirect-function final))
1795 (if (autoloadp final)
1796 (setq final (autoload-do-load final cmd)))))
1797 (cond
1798 ((arrayp final)
1799 ;; If requested, place the macro in the command history. For
1800 ;; other sorts of commands, call-interactively takes care of this.
1801 (when record-flag
1802 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1803 ;; Don't keep command history around forever.
1804 (when (and (numberp history-length) (> history-length 0))
1805 (let ((cell (nthcdr history-length command-history)))
1806 (if (consp cell) (setcdr cell nil)))))
1807 (execute-kbd-macro final prefixarg))
1809 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1810 (prog1 (call-interactively cmd record-flag keys)
1811 (when (and (symbolp cmd)
1812 (get cmd 'byte-obsolete-info)
1813 (not (get cmd 'command-execute-obsolete-warned)))
1814 (put cmd 'command-execute-obsolete-warned t)
1815 (message "%s" (macroexp--obsolete-warning
1816 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1818 (defvar minibuffer-history nil
1819 "Default minibuffer history list.
1820 This is used for all minibuffer input
1821 except when an alternate history list is specified.
1823 Maximum length of the history list is determined by the value
1824 of `history-length', which see.")
1825 (defvar minibuffer-history-sexp-flag nil
1826 "Control whether history list elements are expressions or strings.
1827 If the value of this variable equals current minibuffer depth,
1828 they are expressions; otherwise they are strings.
1829 \(That convention is designed to do the right thing for
1830 recursive uses of the minibuffer.)")
1831 (setq minibuffer-history-variable 'minibuffer-history)
1832 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1833 (defvar minibuffer-history-search-history nil)
1835 (defvar minibuffer-text-before-history nil
1836 "Text that was in this minibuffer before any history commands.
1837 This is nil if there have not yet been any history commands
1838 in this use of the minibuffer.")
1840 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1842 (defun minibuffer-history-initialize ()
1843 (setq minibuffer-text-before-history nil))
1845 (defun minibuffer-avoid-prompt (_new _old)
1846 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1847 (declare (obsolete cursor-intangible-mode "25.1"))
1848 (constrain-to-field nil (point-max)))
1850 (defcustom minibuffer-history-case-insensitive-variables nil
1851 "Minibuffer history variables for which matching should ignore case.
1852 If a history variable is a member of this list, then the
1853 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1854 commands ignore case when searching it, regardless of `case-fold-search'."
1855 :type '(repeat variable)
1856 :group 'minibuffer)
1858 (defun previous-matching-history-element (regexp n)
1859 "Find the previous history element that matches REGEXP.
1860 \(Previous history elements refer to earlier actions.)
1861 With prefix argument N, search for Nth previous match.
1862 If N is negative, find the next or Nth next match.
1863 Normally, history elements are matched case-insensitively if
1864 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1865 makes the search case-sensitive.
1866 See also `minibuffer-history-case-insensitive-variables'."
1867 (interactive
1868 (let* ((enable-recursive-minibuffers t)
1869 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1871 minibuffer-local-map
1873 'minibuffer-history-search-history
1874 (car minibuffer-history-search-history))))
1875 ;; Use the last regexp specified, by default, if input is empty.
1876 (list (if (string= regexp "")
1877 (if minibuffer-history-search-history
1878 (car minibuffer-history-search-history)
1879 (user-error "No previous history search regexp"))
1880 regexp)
1881 (prefix-numeric-value current-prefix-arg))))
1882 (unless (zerop n)
1883 (if (and (zerop minibuffer-history-position)
1884 (null minibuffer-text-before-history))
1885 (setq minibuffer-text-before-history
1886 (minibuffer-contents-no-properties)))
1887 (let ((history (symbol-value minibuffer-history-variable))
1888 (case-fold-search
1889 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1890 ;; On some systems, ignore case for file names.
1891 (if (memq minibuffer-history-variable
1892 minibuffer-history-case-insensitive-variables)
1894 ;; Respect the user's setting for case-fold-search:
1895 case-fold-search)
1896 nil))
1897 prevpos
1898 match-string
1899 match-offset
1900 (pos minibuffer-history-position))
1901 (while (/= n 0)
1902 (setq prevpos pos)
1903 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1904 (when (= pos prevpos)
1905 (user-error (if (= pos 1)
1906 "No later matching history item"
1907 "No earlier matching history item")))
1908 (setq match-string
1909 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1910 (let ((print-level nil))
1911 (prin1-to-string (nth (1- pos) history)))
1912 (nth (1- pos) history)))
1913 (setq match-offset
1914 (if (< n 0)
1915 (and (string-match regexp match-string)
1916 (match-end 0))
1917 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1918 (match-beginning 1))))
1919 (when match-offset
1920 (setq n (+ n (if (< n 0) 1 -1)))))
1921 (setq minibuffer-history-position pos)
1922 (goto-char (point-max))
1923 (delete-minibuffer-contents)
1924 (insert match-string)
1925 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1926 (if (memq (car (car command-history)) '(previous-matching-history-element
1927 next-matching-history-element))
1928 (setq command-history (cdr command-history))))
1930 (defun next-matching-history-element (regexp n)
1931 "Find the next history element that matches REGEXP.
1932 \(The next history element refers to a more recent action.)
1933 With prefix argument N, search for Nth next match.
1934 If N is negative, find the previous or Nth previous match.
1935 Normally, history elements are matched case-insensitively if
1936 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1937 makes the search case-sensitive."
1938 (interactive
1939 (let* ((enable-recursive-minibuffers t)
1940 (regexp (read-from-minibuffer "Next 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 (previous-matching-history-element regexp (- n)))
1955 (defvar minibuffer-temporary-goal-position nil)
1957 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1958 "Function run by `goto-history-element' before consuming default values.
1959 This is useful to dynamically add more elements to the list of default values
1960 when `goto-history-element' reaches the end of this list.
1961 Before calling this function `goto-history-element' sets the variable
1962 `minibuffer-default-add-done' to t, so it will call this function only
1963 once. In special cases, when this function needs to be called more
1964 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1965 overriding the setting of this variable to t in `goto-history-element'.")
1967 (defvar minibuffer-default-add-done nil
1968 "When nil, add more elements to the end of the list of default values.
1969 The value nil causes `goto-history-element' to add more elements to
1970 the list of defaults when it reaches the end of this list. It does
1971 this by calling a function defined by `minibuffer-default-add-function'.")
1973 (make-variable-buffer-local 'minibuffer-default-add-done)
1975 (defun minibuffer-default-add-completions ()
1976 "Return a list of all completions without the default value.
1977 This function is used to add all elements of the completion table to
1978 the end of the list of defaults just after the default value."
1979 (let ((def minibuffer-default)
1980 (all (all-completions ""
1981 minibuffer-completion-table
1982 minibuffer-completion-predicate)))
1983 (if (listp def)
1984 (append def all)
1985 (cons def (delete def all)))))
1987 (defun goto-history-element (nabs)
1988 "Puts element of the minibuffer history in the minibuffer.
1989 The argument NABS specifies the absolute history position."
1990 (interactive "p")
1991 (when (and (not minibuffer-default-add-done)
1992 (functionp minibuffer-default-add-function)
1993 (< nabs (- (if (listp minibuffer-default)
1994 (length minibuffer-default)
1995 1))))
1996 (setq minibuffer-default-add-done t
1997 minibuffer-default (funcall minibuffer-default-add-function)))
1998 (let ((minimum (if minibuffer-default
1999 (- (if (listp minibuffer-default)
2000 (length minibuffer-default)
2003 elt minibuffer-returned-to-present)
2004 (if (and (zerop minibuffer-history-position)
2005 (null minibuffer-text-before-history))
2006 (setq minibuffer-text-before-history
2007 (minibuffer-contents-no-properties)))
2008 (if (< nabs minimum)
2009 (user-error (if minibuffer-default
2010 "End of defaults; no next item"
2011 "End of history; no default available")))
2012 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2013 (length (symbol-value minibuffer-history-variable))
2015 (user-error "Beginning of history; no preceding item"))
2016 (unless (memq last-command '(next-history-element
2017 previous-history-element))
2018 (let ((prompt-end (minibuffer-prompt-end)))
2019 (set (make-local-variable 'minibuffer-temporary-goal-position)
2020 (cond ((<= (point) prompt-end) prompt-end)
2021 ((eobp) nil)
2022 (t (point))))))
2023 (goto-char (point-max))
2024 (delete-minibuffer-contents)
2025 (setq minibuffer-history-position nabs)
2026 (cond ((< nabs 0)
2027 (setq elt (if (listp minibuffer-default)
2028 (nth (1- (abs nabs)) minibuffer-default)
2029 minibuffer-default)))
2030 ((= nabs 0)
2031 (setq elt (or minibuffer-text-before-history ""))
2032 (setq minibuffer-returned-to-present t)
2033 (setq minibuffer-text-before-history nil))
2034 (t (setq elt (nth (1- minibuffer-history-position)
2035 (symbol-value minibuffer-history-variable)))))
2036 (insert
2037 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2038 (not minibuffer-returned-to-present))
2039 (let ((print-level nil))
2040 (prin1-to-string elt))
2041 elt))
2042 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2044 (defun next-history-element (n)
2045 "Puts next element of the minibuffer history in the minibuffer.
2046 With argument N, it uses the Nth following element."
2047 (interactive "p")
2048 (or (zerop n)
2049 (goto-history-element (- minibuffer-history-position n))))
2051 (defun previous-history-element (n)
2052 "Puts previous element of the minibuffer history in the minibuffer.
2053 With argument N, it uses the Nth previous element."
2054 (interactive "p")
2055 (or (zerop n)
2056 (goto-history-element (+ minibuffer-history-position n))))
2058 (defun next-line-or-history-element (&optional arg)
2059 "Move cursor vertically down ARG lines, or to the next history element.
2060 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2061 next element of the minibuffer history in the minibuffer."
2062 (interactive "^p")
2063 (or arg (setq arg 1))
2064 (let* ((old-point (point))
2065 ;; Remember the original goal column of possibly multi-line input
2066 ;; excluding the length of the prompt on the first line.
2067 (prompt-end (minibuffer-prompt-end))
2068 (old-column (unless (and (eolp) (> (point) prompt-end))
2069 (if (= (line-number-at-pos) 1)
2070 (max (- (current-column) (1- prompt-end)) 0)
2071 (current-column)))))
2072 (condition-case nil
2073 (with-no-warnings
2074 (next-line arg))
2075 (end-of-buffer
2076 ;; Restore old position since `line-move-visual' moves point to
2077 ;; the end of the line when it fails to go to the next line.
2078 (goto-char old-point)
2079 (next-history-element arg)
2080 ;; Reset `temporary-goal-column' because a correct value is not
2081 ;; calculated when `next-line' above fails by bumping against
2082 ;; the bottom of the minibuffer (bug#22544).
2083 (setq temporary-goal-column 0)
2084 ;; Restore the original goal column on the last line
2085 ;; of possibly multi-line input.
2086 (goto-char (point-max))
2087 (when old-column
2088 (if (= (line-number-at-pos) 1)
2089 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2090 (move-to-column old-column)))))))
2092 (defun previous-line-or-history-element (&optional arg)
2093 "Move cursor vertically up ARG lines, or to the previous history element.
2094 When point moves over the top line of multi-line minibuffer, puts ARGth
2095 previous element of the minibuffer history in the minibuffer."
2096 (interactive "^p")
2097 (or arg (setq arg 1))
2098 (let* ((old-point (point))
2099 ;; Remember the original goal column of possibly multi-line input
2100 ;; excluding the length of the prompt on the first line.
2101 (prompt-end (minibuffer-prompt-end))
2102 (old-column (unless (and (eolp) (> (point) prompt-end))
2103 (if (= (line-number-at-pos) 1)
2104 (max (- (current-column) (1- prompt-end)) 0)
2105 (current-column)))))
2106 (condition-case nil
2107 (with-no-warnings
2108 (previous-line arg))
2109 (beginning-of-buffer
2110 ;; Restore old position since `line-move-visual' moves point to
2111 ;; the beginning of the line when it fails to go to the previous line.
2112 (goto-char old-point)
2113 (previous-history-element arg)
2114 ;; Reset `temporary-goal-column' because a correct value is not
2115 ;; calculated when `previous-line' above fails by bumping against
2116 ;; the top of the minibuffer (bug#22544).
2117 (setq temporary-goal-column 0)
2118 ;; Restore the original goal column on the first line
2119 ;; of possibly multi-line input.
2120 (goto-char (minibuffer-prompt-end))
2121 (if old-column
2122 (if (= (line-number-at-pos) 1)
2123 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2124 (move-to-column old-column))
2125 ;; Put the cursor at the end of the visual line instead of the
2126 ;; logical line, so the next `previous-line-or-history-element'
2127 ;; would move to the previous history element, not to a possible upper
2128 ;; visual line from the end of logical line in `line-move-visual' mode.
2129 (end-of-visual-line)
2130 ;; Since `end-of-visual-line' puts the cursor at the beginning
2131 ;; of the next visual line, move it one char back to the end
2132 ;; of the first visual line (bug#22544).
2133 (unless (eolp) (backward-char 1)))))))
2135 (defun next-complete-history-element (n)
2136 "Get next history element which completes the minibuffer before the point.
2137 The contents of the minibuffer after the point are deleted, and replaced
2138 by the new completion."
2139 (interactive "p")
2140 (let ((point-at-start (point)))
2141 (next-matching-history-element
2142 (concat
2143 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2145 ;; next-matching-history-element always puts us at (point-min).
2146 ;; Move to the position we were at before changing the buffer contents.
2147 ;; This is still sensible, because the text before point has not changed.
2148 (goto-char point-at-start)))
2150 (defun previous-complete-history-element (n)
2152 Get previous history element which completes the minibuffer before the point.
2153 The contents of the minibuffer after the point are deleted, and replaced
2154 by the new completion."
2155 (interactive "p")
2156 (next-complete-history-element (- n)))
2158 ;; For compatibility with the old subr of the same name.
2159 (defun minibuffer-prompt-width ()
2160 "Return the display width of the minibuffer prompt.
2161 Return 0 if current buffer is not a minibuffer."
2162 ;; Return the width of everything before the field at the end of
2163 ;; the buffer; this should be 0 for normal buffers.
2164 (1- (minibuffer-prompt-end)))
2166 ;; isearch minibuffer history
2167 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2169 (defvar minibuffer-history-isearch-message-overlay)
2170 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2172 (defun minibuffer-history-isearch-setup ()
2173 "Set up a minibuffer for using isearch to search the minibuffer history.
2174 Intended to be added to `minibuffer-setup-hook'."
2175 (set (make-local-variable 'isearch-search-fun-function)
2176 'minibuffer-history-isearch-search)
2177 (set (make-local-variable 'isearch-message-function)
2178 'minibuffer-history-isearch-message)
2179 (set (make-local-variable 'isearch-wrap-function)
2180 'minibuffer-history-isearch-wrap)
2181 (set (make-local-variable 'isearch-push-state-function)
2182 'minibuffer-history-isearch-push-state)
2183 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2185 (defun minibuffer-history-isearch-end ()
2186 "Clean up the minibuffer after terminating isearch in the minibuffer."
2187 (if minibuffer-history-isearch-message-overlay
2188 (delete-overlay minibuffer-history-isearch-message-overlay)))
2190 (defun minibuffer-history-isearch-search ()
2191 "Return the proper search function, for isearch in minibuffer history."
2192 (lambda (string bound noerror)
2193 (let ((search-fun
2194 ;; Use standard functions to search within minibuffer text
2195 (isearch-search-fun-default))
2196 found)
2197 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2198 ;; searching forward. Lazy-highlight calls this lambda with the
2199 ;; bound arg, so skip the minibuffer prompt.
2200 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2201 (goto-char (minibuffer-prompt-end)))
2203 ;; 1. First try searching in the initial minibuffer text
2204 (funcall search-fun string
2205 (if isearch-forward bound (minibuffer-prompt-end))
2206 noerror)
2207 ;; 2. If the above search fails, start putting next/prev history
2208 ;; elements in the minibuffer successively, and search the string
2209 ;; in them. Do this only when bound is nil (i.e. not while
2210 ;; lazy-highlighting search strings in the current minibuffer text).
2211 (unless bound
2212 (condition-case nil
2213 (progn
2214 (while (not found)
2215 (cond (isearch-forward
2216 (next-history-element 1)
2217 (goto-char (minibuffer-prompt-end)))
2219 (previous-history-element 1)
2220 (goto-char (point-max))))
2221 (setq isearch-barrier (point) isearch-opoint (point))
2222 ;; After putting the next/prev history element, search
2223 ;; the string in them again, until next-history-element
2224 ;; or previous-history-element raises an error at the
2225 ;; beginning/end of history.
2226 (setq found (funcall search-fun string
2227 (unless isearch-forward
2228 ;; For backward search, don't search
2229 ;; in the minibuffer prompt
2230 (minibuffer-prompt-end))
2231 noerror)))
2232 ;; Return point of the new search result
2233 (point))
2234 ;; Return nil when next(prev)-history-element fails
2235 (error nil)))))))
2237 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2238 "Display the minibuffer history search prompt.
2239 If there are no search errors, this function displays an overlay with
2240 the isearch prompt which replaces the original minibuffer prompt.
2241 Otherwise, it displays the standard isearch message returned from
2242 the function `isearch-message'."
2243 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2244 ;; Use standard function `isearch-message' when not in the minibuffer,
2245 ;; or search fails, or has an error (like incomplete regexp).
2246 ;; This function overwrites minibuffer text with isearch message,
2247 ;; so it's possible to see what is wrong in the search string.
2248 (isearch-message c-q-hack ellipsis)
2249 ;; Otherwise, put the overlay with the standard isearch prompt over
2250 ;; the initial minibuffer prompt.
2251 (if (overlayp minibuffer-history-isearch-message-overlay)
2252 (move-overlay minibuffer-history-isearch-message-overlay
2253 (point-min) (minibuffer-prompt-end))
2254 (setq minibuffer-history-isearch-message-overlay
2255 (make-overlay (point-min) (minibuffer-prompt-end)))
2256 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2257 (overlay-put minibuffer-history-isearch-message-overlay
2258 'display (isearch-message-prefix c-q-hack ellipsis))
2259 ;; And clear any previous isearch message.
2260 (message "")))
2262 (defun minibuffer-history-isearch-wrap ()
2263 "Wrap the minibuffer history search when search fails.
2264 Move point to the first history element for a forward search,
2265 or to the last history element for a backward search."
2266 ;; When `minibuffer-history-isearch-search' fails on reaching the
2267 ;; beginning/end of the history, wrap the search to the first/last
2268 ;; minibuffer history element.
2269 (if isearch-forward
2270 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2271 (goto-history-element 0))
2272 (setq isearch-success t)
2273 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2275 (defun minibuffer-history-isearch-push-state ()
2276 "Save a function restoring the state of minibuffer history search.
2277 Save `minibuffer-history-position' to the additional state parameter
2278 in the search status stack."
2279 (let ((pos minibuffer-history-position))
2280 (lambda (cmd)
2281 (minibuffer-history-isearch-pop-state cmd pos))))
2283 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2284 "Restore the minibuffer history search state.
2285 Go to the history element by the absolute history position HIST-POS."
2286 (goto-history-element hist-pos))
2289 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2290 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2292 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2293 "Table mapping redo records to the corresponding undo one.
2294 A redo record for undo-in-region maps to t.
2295 A redo record for ordinary undo maps to the following (earlier) undo.")
2297 (defvar undo-in-region nil
2298 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2300 (defvar undo-no-redo nil
2301 "If t, `undo' doesn't go through redo entries.")
2303 (defvar pending-undo-list nil
2304 "Within a run of consecutive undo commands, list remaining to be undone.
2305 If t, we undid all the way to the end of it.")
2307 (defun undo (&optional arg)
2308 "Undo some previous changes.
2309 Repeat this command to undo more changes.
2310 A numeric ARG serves as a repeat count.
2312 In Transient Mark mode when the mark is active, only undo changes within
2313 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2314 as an argument limits undo to changes within the current region."
2315 (interactive "*P")
2316 ;; Make last-command indicate for the next command that this was an undo.
2317 ;; That way, another undo will undo more.
2318 ;; If we get to the end of the undo history and get an error,
2319 ;; another undo command will find the undo history empty
2320 ;; and will get another error. To begin undoing the undos,
2321 ;; you must type some other command.
2322 (let* ((modified (buffer-modified-p))
2323 ;; For an indirect buffer, look in the base buffer for the
2324 ;; auto-save data.
2325 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2326 (recent-save (with-current-buffer base-buffer
2327 (recent-auto-save-p)))
2328 message)
2329 ;; If we get an error in undo-start,
2330 ;; the next command should not be a "consecutive undo".
2331 ;; So set `this-command' to something other than `undo'.
2332 (setq this-command 'undo-start)
2334 (unless (and (eq last-command 'undo)
2335 (or (eq pending-undo-list t)
2336 ;; If something (a timer or filter?) changed the buffer
2337 ;; since the previous command, don't continue the undo seq.
2338 (let ((list buffer-undo-list))
2339 (while (eq (car list) nil)
2340 (setq list (cdr list)))
2341 ;; If the last undo record made was made by undo
2342 ;; it shows nothing else happened in between.
2343 (gethash list undo-equiv-table))))
2344 (setq undo-in-region
2345 (or (region-active-p) (and arg (not (numberp arg)))))
2346 (if undo-in-region
2347 (undo-start (region-beginning) (region-end))
2348 (undo-start))
2349 ;; get rid of initial undo boundary
2350 (undo-more 1))
2351 ;; If we got this far, the next command should be a consecutive undo.
2352 (setq this-command 'undo)
2353 ;; Check to see whether we're hitting a redo record, and if
2354 ;; so, ask the user whether she wants to skip the redo/undo pair.
2355 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2356 (or (eq (selected-window) (minibuffer-window))
2357 (setq message (format "%s%s!"
2358 (if (or undo-no-redo (not equiv))
2359 "Undo" "Redo")
2360 (if undo-in-region " in region" ""))))
2361 (when (and (consp equiv) undo-no-redo)
2362 ;; The equiv entry might point to another redo record if we have done
2363 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2364 (while (let ((next (gethash equiv undo-equiv-table)))
2365 (if next (setq equiv next))))
2366 (setq pending-undo-list equiv)))
2367 (undo-more
2368 (if (numberp arg)
2369 (prefix-numeric-value arg)
2371 ;; Record the fact that the just-generated undo records come from an
2372 ;; undo operation--that is, they are redo records.
2373 ;; In the ordinary case (not within a region), map the redo
2374 ;; record to the following undos.
2375 ;; I don't know how to do that in the undo-in-region case.
2376 (let ((list buffer-undo-list))
2377 ;; Strip any leading undo boundaries there might be, like we do
2378 ;; above when checking.
2379 (while (eq (car list) nil)
2380 (setq list (cdr list)))
2381 (puthash list
2382 ;; Prevent identity mapping. This can happen if
2383 ;; consecutive nils are erroneously in undo list.
2384 (if (or undo-in-region (eq list pending-undo-list))
2386 pending-undo-list)
2387 undo-equiv-table))
2388 ;; Don't specify a position in the undo record for the undo command.
2389 ;; Instead, undoing this should move point to where the change is.
2390 (let ((tail buffer-undo-list)
2391 (prev nil))
2392 (while (car tail)
2393 (when (integerp (car tail))
2394 (let ((pos (car tail)))
2395 (if prev
2396 (setcdr prev (cdr tail))
2397 (setq buffer-undo-list (cdr tail)))
2398 (setq tail (cdr tail))
2399 (while (car tail)
2400 (if (eq pos (car tail))
2401 (if prev
2402 (setcdr prev (cdr tail))
2403 (setq buffer-undo-list (cdr tail)))
2404 (setq prev tail))
2405 (setq tail (cdr tail)))
2406 (setq tail nil)))
2407 (setq prev tail tail (cdr tail))))
2408 ;; Record what the current undo list says,
2409 ;; so the next command can tell if the buffer was modified in between.
2410 (and modified (not (buffer-modified-p))
2411 (with-current-buffer base-buffer
2412 (delete-auto-save-file-if-necessary recent-save)))
2413 ;; Display a message announcing success.
2414 (if message
2415 (message "%s" message))))
2417 (defun buffer-disable-undo (&optional buffer)
2418 "Make BUFFER stop keeping undo information.
2419 No argument or nil as argument means do this for the current buffer."
2420 (interactive)
2421 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2422 (setq buffer-undo-list t)))
2424 (defun undo-only (&optional arg)
2425 "Undo some previous changes.
2426 Repeat this command to undo more changes.
2427 A numeric ARG serves as a repeat count.
2428 Contrary to `undo', this will not redo a previous undo."
2429 (interactive "*p")
2430 (let ((undo-no-redo t)) (undo arg)))
2432 (defvar undo-in-progress nil
2433 "Non-nil while performing an undo.
2434 Some change-hooks test this variable to do something different.")
2436 (defun undo-more (n)
2437 "Undo back N undo-boundaries beyond what was already undone recently.
2438 Call `undo-start' to get ready to undo recent changes,
2439 then call `undo-more' one or more times to undo them."
2440 (or (listp pending-undo-list)
2441 (user-error (concat "No further undo information"
2442 (and undo-in-region " for region"))))
2443 (let ((undo-in-progress t))
2444 ;; Note: The following, while pulling elements off
2445 ;; `pending-undo-list' will call primitive change functions which
2446 ;; will push more elements onto `buffer-undo-list'.
2447 (setq pending-undo-list (primitive-undo n pending-undo-list))
2448 (if (null pending-undo-list)
2449 (setq pending-undo-list t))))
2451 (defun primitive-undo (n list)
2452 "Undo N records from the front of the list LIST.
2453 Return what remains of the list."
2455 ;; This is a good feature, but would make undo-start
2456 ;; unable to do what is expected.
2457 ;;(when (null (car (list)))
2458 ;; ;; If the head of the list is a boundary, it is the boundary
2459 ;; ;; preceding this command. Get rid of it and don't count it.
2460 ;; (setq list (cdr list))))
2462 (let ((arg n)
2463 ;; In a writable buffer, enable undoing read-only text that is
2464 ;; so because of text properties.
2465 (inhibit-read-only t)
2466 ;; Don't let `intangible' properties interfere with undo.
2467 (inhibit-point-motion-hooks t)
2468 ;; We use oldlist only to check for EQ. ++kfs
2469 (oldlist buffer-undo-list)
2470 (did-apply nil)
2471 (next nil))
2472 (while (> arg 0)
2473 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2474 ;; Handle an integer by setting point to that value.
2475 (pcase next
2476 ((pred integerp) (goto-char next))
2477 ;; Element (t . TIME) records previous modtime.
2478 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2479 ;; UNKNOWN_MODTIME_NSECS.
2480 (`(t . ,time)
2481 ;; If this records an obsolete save
2482 ;; (not matching the actual disk file)
2483 ;; then don't mark unmodified.
2484 (when (or (equal time (visited-file-modtime))
2485 (and (consp time)
2486 (equal (list (car time) (cdr time))
2487 (visited-file-modtime))))
2488 (when (fboundp 'unlock-buffer)
2489 (unlock-buffer))
2490 (set-buffer-modified-p nil)))
2491 ;; Element (nil PROP VAL BEG . END) is property change.
2492 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2493 (when (or (> (point-min) beg) (< (point-max) end))
2494 (error "Changes to be undone are outside visible portion of buffer"))
2495 (put-text-property beg end prop val))
2496 ;; Element (BEG . END) means range was inserted.
2497 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2498 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2499 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2500 (when (or (> (point-min) beg) (< (point-max) end))
2501 (error "Changes to be undone are outside visible portion of buffer"))
2502 ;; Set point first thing, so that undoing this undo
2503 ;; does not send point back to where it is now.
2504 (goto-char beg)
2505 (delete-region beg end))
2506 ;; Element (apply FUN . ARGS) means call FUN to undo.
2507 (`(apply . ,fun-args)
2508 (let ((currbuff (current-buffer)))
2509 (if (integerp (car fun-args))
2510 ;; Long format: (apply DELTA START END FUN . ARGS).
2511 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2512 (start-mark (copy-marker start nil))
2513 (end-mark (copy-marker end t)))
2514 (when (or (> (point-min) start) (< (point-max) end))
2515 (error "Changes to be undone are outside visible portion of buffer"))
2516 (apply fun args) ;; Use `save-current-buffer'?
2517 ;; Check that the function did what the entry
2518 ;; said it would do.
2519 (unless (and (= start start-mark)
2520 (= (+ delta end) end-mark))
2521 (error "Changes to be undone by function different than announced"))
2522 (set-marker start-mark nil)
2523 (set-marker end-mark nil))
2524 (apply fun-args))
2525 (unless (eq currbuff (current-buffer))
2526 (error "Undo function switched buffer"))
2527 (setq did-apply t)))
2528 ;; Element (STRING . POS) means STRING was deleted.
2529 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2530 (when (let ((apos (abs pos)))
2531 (or (< apos (point-min)) (> apos (point-max))))
2532 (error "Changes to be undone are outside visible portion of buffer"))
2533 (let (valid-marker-adjustments)
2534 ;; Check that marker adjustments which were recorded
2535 ;; with the (STRING . POS) record are still valid, ie
2536 ;; the markers haven't moved. We check their validity
2537 ;; before reinserting the string so as we don't need to
2538 ;; mind marker insertion-type.
2539 (while (and (markerp (car-safe (car list)))
2540 (integerp (cdr-safe (car list))))
2541 (let* ((marker-adj (pop list))
2542 (m (car marker-adj)))
2543 (and (eq (marker-buffer m) (current-buffer))
2544 (= pos m)
2545 (push marker-adj valid-marker-adjustments))))
2546 ;; Insert string and adjust point
2547 (if (< pos 0)
2548 (progn
2549 (goto-char (- pos))
2550 (insert string))
2551 (goto-char pos)
2552 (insert string)
2553 (goto-char pos))
2554 ;; Adjust the valid marker adjustments
2555 (dolist (adj valid-marker-adjustments)
2556 (set-marker (car adj)
2557 (- (car adj) (cdr adj))))))
2558 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2559 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2560 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2561 next)
2562 ;; Even though these elements are not expected in the undo
2563 ;; list, adjust them to be conservative for the 24.4
2564 ;; release. (Bug#16818)
2565 (when (marker-buffer marker)
2566 (set-marker marker
2567 (- marker offset)
2568 (marker-buffer marker))))
2569 (_ (error "Unrecognized entry in undo list %S" next))))
2570 (setq arg (1- arg)))
2571 ;; Make sure an apply entry produces at least one undo entry,
2572 ;; so the test in `undo' for continuing an undo series
2573 ;; will work right.
2574 (if (and did-apply
2575 (eq oldlist buffer-undo-list))
2576 (setq buffer-undo-list
2577 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2578 list)
2580 ;; Deep copy of a list
2581 (defun undo-copy-list (list)
2582 "Make a copy of undo list LIST."
2583 (mapcar 'undo-copy-list-1 list))
2585 (defun undo-copy-list-1 (elt)
2586 (if (consp elt)
2587 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2588 elt))
2590 (defun undo-start (&optional beg end)
2591 "Set `pending-undo-list' to the front of the undo list.
2592 The next call to `undo-more' will undo the most recently made change.
2593 If BEG and END are specified, then only undo elements
2594 that apply to text between BEG and END are used; other undo elements
2595 are ignored. If BEG and END are nil, all undo elements are used."
2596 (if (eq buffer-undo-list t)
2597 (user-error "No undo information in this buffer"))
2598 (setq pending-undo-list
2599 (if (and beg end (not (= beg end)))
2600 (undo-make-selective-list (min beg end) (max beg end))
2601 buffer-undo-list)))
2603 ;; The positions given in elements of the undo list are the positions
2604 ;; as of the time that element was recorded to undo history. In
2605 ;; general, subsequent buffer edits render those positions invalid in
2606 ;; the current buffer, unless adjusted according to the intervening
2607 ;; undo elements.
2609 ;; Undo in region is a use case that requires adjustments to undo
2610 ;; elements. It must adjust positions of elements in the region based
2611 ;; on newer elements not in the region so as they may be correctly
2612 ;; applied in the current buffer. undo-make-selective-list
2613 ;; accomplishes this with its undo-deltas list of adjustments. An
2614 ;; example undo history from oldest to newest:
2616 ;; buf pos:
2617 ;; 123456789 buffer-undo-list undo-deltas
2618 ;; --------- ---------------- -----------
2619 ;; aaa (1 . 4) (1 . -3)
2620 ;; aaba (3 . 4) N/A (in region)
2621 ;; ccaaba (1 . 3) (1 . -2)
2622 ;; ccaabaddd (7 . 10) (7 . -3)
2623 ;; ccaabdd ("ad" . 6) (6 . 2)
2624 ;; ccaabaddd (6 . 8) (6 . -2)
2625 ;; | |<-- region: "caab", from 2 to 6
2627 ;; When the user starts a run of undos in region,
2628 ;; undo-make-selective-list is called to create the full list of in
2629 ;; region elements. Each element is adjusted forward chronologically
2630 ;; through undo-deltas to determine if it is in the region.
2632 ;; In the above example, the insertion of "b" is (3 . 4) in the
2633 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2634 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2635 ;; . 6) is assessed as in the region and placed in the selective list.
2636 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2637 ;; due to the selected element. The "b" insertion is the only element
2638 ;; fully in the region, so in this example undo-make-selective-list
2639 ;; returns (nil (5 . 6)).
2641 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2642 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2643 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2644 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2645 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2647 ;; More interesting is how to adjust the "ddd" insertion due to the
2648 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2649 ;; If the reinsertion was a manual retyping of "ad", then the total
2650 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2651 ;; the reinsertion was due to undo, one might expect the first "d"
2652 ;; character would again be a part of the "ddd" text, meaning its
2653 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2655 ;; undo-make-selective-list assumes in this situation that "ad" was a
2656 ;; new edit, even if it was inserted because of an undo.
2657 ;; Consequently, if the user undos in region "8 to 10" of the
2658 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2659 ;; "ccaabad", as though the first "d" became detached from the
2660 ;; original "ddd" insertion. This quirk is a FIXME.
2662 (defun undo-make-selective-list (start end)
2663 "Return a list of undo elements for the region START to END.
2664 The elements come from `buffer-undo-list', but we keep only the
2665 elements inside this region, and discard those outside this
2666 region. The elements' positions are adjusted so as the returned
2667 list can be applied to the current buffer."
2668 (let ((ulist buffer-undo-list)
2669 ;; A list of position adjusted undo elements in the region.
2670 (selective-list (list nil))
2671 ;; A list of undo-deltas for out of region undo elements.
2672 undo-deltas
2673 undo-elt)
2674 (while ulist
2675 (when undo-no-redo
2676 (while (gethash ulist undo-equiv-table)
2677 (setq ulist (gethash ulist undo-equiv-table))))
2678 (setq undo-elt (car ulist))
2679 (cond
2680 ((null undo-elt)
2681 ;; Don't put two nils together in the list
2682 (when (car selective-list)
2683 (push nil selective-list)))
2684 ((and (consp undo-elt) (eq (car undo-elt) t))
2685 ;; This is a "was unmodified" element. Keep it
2686 ;; if we have kept everything thus far.
2687 (when (not undo-deltas)
2688 (push undo-elt selective-list)))
2689 ;; Skip over marker adjustments, instead relying
2690 ;; on finding them after (TEXT . POS) elements
2691 ((markerp (car-safe undo-elt))
2692 nil)
2694 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2695 undo-deltas)))
2696 (if (undo-elt-in-region adjusted-undo-elt start end)
2697 (progn
2698 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2699 (push adjusted-undo-elt selective-list)
2700 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2701 ;; kept. primitive-undo may discard them later.
2702 (when (and (stringp (car-safe adjusted-undo-elt))
2703 (integerp (cdr-safe adjusted-undo-elt)))
2704 (let ((list-i (cdr ulist)))
2705 (while (markerp (car-safe (car list-i)))
2706 (push (pop list-i) selective-list)))))
2707 (let ((delta (undo-delta undo-elt)))
2708 (when (/= 0 (cdr delta))
2709 (push delta undo-deltas)))))))
2710 (pop ulist))
2711 (nreverse selective-list)))
2713 (defun undo-elt-in-region (undo-elt start end)
2714 "Determine whether UNDO-ELT falls inside the region START ... END.
2715 If it crosses the edge, we return nil.
2717 Generally this function is not useful for determining
2718 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2719 because markers can be arbitrarily relocated. Instead, pass the
2720 marker adjustment's corresponding (TEXT . POS) element."
2721 (cond ((integerp undo-elt)
2722 (and (>= undo-elt start)
2723 (<= undo-elt end)))
2724 ((eq undo-elt nil)
2726 ((atom undo-elt)
2727 nil)
2728 ((stringp (car undo-elt))
2729 ;; (TEXT . POSITION)
2730 (and (>= (abs (cdr undo-elt)) start)
2731 (<= (abs (cdr undo-elt)) end)))
2732 ((and (consp undo-elt) (markerp (car undo-elt)))
2733 ;; (MARKER . ADJUSTMENT)
2734 (<= start (car undo-elt) end))
2735 ((null (car undo-elt))
2736 ;; (nil PROPERTY VALUE BEG . END)
2737 (let ((tail (nthcdr 3 undo-elt)))
2738 (and (>= (car tail) start)
2739 (<= (cdr tail) end))))
2740 ((integerp (car undo-elt))
2741 ;; (BEGIN . END)
2742 (and (>= (car undo-elt) start)
2743 (<= (cdr undo-elt) end)))))
2745 (defun undo-elt-crosses-region (undo-elt start end)
2746 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2747 This assumes we have already decided that UNDO-ELT
2748 is not *inside* the region START...END."
2749 (declare (obsolete nil "25.1"))
2750 (cond ((atom undo-elt) nil)
2751 ((null (car undo-elt))
2752 ;; (nil PROPERTY VALUE BEG . END)
2753 (let ((tail (nthcdr 3 undo-elt)))
2754 (and (< (car tail) end)
2755 (> (cdr tail) start))))
2756 ((integerp (car undo-elt))
2757 ;; (BEGIN . END)
2758 (and (< (car undo-elt) end)
2759 (> (cdr undo-elt) start)))))
2761 (defun undo-adjust-elt (elt deltas)
2762 "Return adjustment of undo element ELT by the undo DELTAS
2763 list."
2764 (pcase elt
2765 ;; POSITION
2766 ((pred integerp)
2767 (undo-adjust-pos elt deltas))
2768 ;; (BEG . END)
2769 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2770 (undo-adjust-beg-end beg end deltas))
2771 ;; (TEXT . POSITION)
2772 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2773 (cons text (* (if (< pos 0) -1 1)
2774 (undo-adjust-pos (abs pos) deltas))))
2775 ;; (nil PROPERTY VALUE BEG . END)
2776 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2777 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2778 ;; (apply DELTA START END FUN . ARGS)
2779 ;; FIXME
2780 ;; All others return same elt
2781 (_ elt)))
2783 ;; (BEG . END) can adjust to the same positions, commonly when an
2784 ;; insertion was undone and they are out of region, for example:
2786 ;; buf pos:
2787 ;; 123456789 buffer-undo-list undo-deltas
2788 ;; --------- ---------------- -----------
2789 ;; [...]
2790 ;; abbaa (2 . 4) (2 . -2)
2791 ;; aaa ("bb" . 2) (2 . 2)
2792 ;; [...]
2794 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2795 ;; undo. Further adjustments to such an element should be the same as
2796 ;; for (TEXT . POSITION) elements. The options are:
2798 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2799 ;; analogous to marker insertion-type t.
2801 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2802 ;; marker insertion-type nil.
2804 ;; There was no strong reason to prefer one or the other, except that
2805 ;; the first is more consistent with prior undo in region behavior.
2806 (defun undo-adjust-beg-end (beg end deltas)
2807 "Return cons of adjustments to BEG and END by the undo DELTAS
2808 list."
2809 (let ((adj-beg (undo-adjust-pos beg deltas)))
2810 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2811 (cons adj-beg
2812 (max adj-beg (undo-adjust-pos end deltas t)))))
2814 (defun undo-adjust-pos (pos deltas &optional use-<)
2815 "Return adjustment of POS by the undo DELTAS list, comparing
2816 with < or <= based on USE-<."
2817 (dolist (d deltas pos)
2818 (when (if use-<
2819 (< (car d) pos)
2820 (<= (car d) pos))
2821 (setq pos
2822 ;; Don't allow pos to become less than the undo-delta
2823 ;; position. This edge case is described in the overview
2824 ;; comments.
2825 (max (car d) (- pos (cdr d)))))))
2827 ;; Return the first affected buffer position and the delta for an undo element
2828 ;; delta is defined as the change in subsequent buffer positions if we *did*
2829 ;; the undo.
2830 (defun undo-delta (undo-elt)
2831 (if (consp undo-elt)
2832 (cond ((stringp (car undo-elt))
2833 ;; (TEXT . POSITION)
2834 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2835 ((integerp (car undo-elt))
2836 ;; (BEGIN . END)
2837 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2839 '(0 . 0)))
2840 '(0 . 0)))
2842 ;;; Default undo-boundary addition
2844 ;; This section adds a new undo-boundary at either after a command is
2845 ;; called or in some cases on a timer called after a change is made in
2846 ;; any buffer.
2847 (defvar-local undo-auto--last-boundary-cause nil
2848 "Describe the cause of the last undo-boundary.
2850 If `explicit', the last boundary was caused by an explicit call to
2851 `undo-boundary', that is one not called by the code in this
2852 section.
2854 If it is equal to `timer', then the last boundary was inserted
2855 by `undo-auto--boundary-timer'.
2857 If it is equal to `command', then the last boundary was inserted
2858 automatically after a command, that is by the code defined in
2859 this section.
2861 If it is equal to a list, then the last boundary was inserted by
2862 an amalgamating command. The car of the list is the number of
2863 times an amalgamating command has been called, and the cdr are the
2864 buffers that were changed during the last command.")
2866 (defvar undo-auto-current-boundary-timer nil
2867 "Current timer which will run `undo-auto--boundary-timer' or nil.
2869 If set to non-nil, this will effectively disable the timer.")
2871 (defvar undo-auto--this-command-amalgamating nil
2872 "Non-nil if `this-command' should be amalgamated.
2873 This variable is set to nil by `undo-auto--boundaries' and is set
2874 by `undo-auto-amalgamate'." )
2876 (defun undo-auto--needs-boundary-p ()
2877 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2878 (car-safe buffer-undo-list))
2880 (defun undo-auto--last-boundary-amalgamating-number ()
2881 "Return the number of amalgamating last commands or nil.
2882 Amalgamating commands are, by default, either
2883 `self-insert-command' and `delete-char', but can be any command
2884 that calls `undo-auto-amalgamate'."
2885 (car-safe undo-auto--last-boundary-cause))
2887 (defun undo-auto--ensure-boundary (cause)
2888 "Add an `undo-boundary' to the current buffer if needed.
2889 REASON describes the reason that the boundary is being added; see
2890 `undo-auto--last-boundary' for more information."
2891 (when (and
2892 (undo-auto--needs-boundary-p))
2893 (let ((last-amalgamating
2894 (undo-auto--last-boundary-amalgamating-number)))
2895 (undo-boundary)
2896 (setq undo-auto--last-boundary-cause
2897 (if (eq 'amalgamate cause)
2898 (cons
2899 (if last-amalgamating (1+ last-amalgamating) 0)
2900 undo-auto--undoably-changed-buffers)
2901 cause)))))
2903 (defun undo-auto--boundaries (cause)
2904 "Check recently changed buffers and add a boundary if necessary.
2905 REASON describes the reason that the boundary is being added; see
2906 `undo-last-boundary' for more information."
2907 ;; (Bug #23785) All commands should ensure that there is an undo
2908 ;; boundary whether they have changed the current buffer or not.
2909 (when (eq cause 'command)
2910 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2911 (dolist (b undo-auto--undoably-changed-buffers)
2912 (when (buffer-live-p b)
2913 (with-current-buffer b
2914 (undo-auto--ensure-boundary cause))))
2915 (setq undo-auto--undoably-changed-buffers nil))
2917 (defun undo-auto--boundary-timer ()
2918 "Timer which will run `undo--auto-boundary-timer'."
2919 (setq undo-auto-current-boundary-timer nil)
2920 (undo-auto--boundaries 'timer))
2922 (defun undo-auto--boundary-ensure-timer ()
2923 "Ensure that the `undo-auto-boundary-timer' is set."
2924 (unless undo-auto-current-boundary-timer
2925 (setq undo-auto-current-boundary-timer
2926 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2928 (defvar undo-auto--undoably-changed-buffers nil
2929 "List of buffers that have changed recently.
2931 This list is maintained by `undo-auto--undoable-change' and
2932 `undo-auto--boundaries' and can be affected by changes to their
2933 default values.")
2935 (defun undo-auto--add-boundary ()
2936 "Add an `undo-boundary' in appropriate buffers."
2937 (undo-auto--boundaries
2938 (let ((amal undo-auto--this-command-amalgamating))
2939 (setq undo-auto--this-command-amalgamating nil)
2940 (if amal
2941 'amalgamate
2942 'command))))
2944 (defun undo-auto-amalgamate ()
2945 "Amalgamate undo if necessary.
2946 This function can be called before an amalgamating command. It
2947 removes the previous `undo-boundary' if a series of such calls
2948 have been made. By default `self-insert-command' and
2949 `delete-char' are the only amalgamating commands, although this
2950 function could be called by any command wishing to have this
2951 behavior."
2952 (let ((last-amalgamating-count
2953 (undo-auto--last-boundary-amalgamating-number)))
2954 (setq undo-auto--this-command-amalgamating t)
2955 (when
2956 last-amalgamating-count
2958 (and
2959 (< last-amalgamating-count 20)
2960 (eq this-command last-command))
2961 ;; Amalgamate all buffers that have changed.
2962 (dolist (b (cdr undo-auto--last-boundary-cause))
2963 (when (buffer-live-p b)
2964 (with-current-buffer
2966 (when
2967 ;; The head of `buffer-undo-list' is nil.
2968 ;; `car-safe' doesn't work because
2969 ;; `buffer-undo-list' need not be a list!
2970 (and (listp buffer-undo-list)
2971 (not (car buffer-undo-list)))
2972 (setq buffer-undo-list
2973 (cdr buffer-undo-list))))))
2974 (setq undo-auto--last-boundary-cause 0)))))
2976 (defun undo-auto--undoable-change ()
2977 "Called after every undoable buffer change."
2978 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
2979 (undo-auto--boundary-ensure-timer))
2980 ;; End auto-boundary section
2982 (defun undo-amalgamate-change-group (handle)
2983 "Amalgamate changes in change-group since HANDLE.
2984 Remove all undo boundaries between the state of HANDLE and now.
2985 HANDLE is as returned by `prepare-change-group'."
2986 (dolist (elt handle)
2987 (with-current-buffer (car elt)
2988 (setq elt (cdr elt))
2989 (when (consp buffer-undo-list)
2990 (let ((old-car (car-safe elt))
2991 (old-cdr (cdr-safe elt)))
2992 (unwind-protect
2993 (progn
2994 ;; Temporarily truncate the undo log at ELT.
2995 (when (consp elt)
2996 (setcar elt t) (setcdr elt nil))
2997 (when
2998 (or (null elt) ;The undo-log was empty.
2999 ;; `elt' is still in the log: normal case.
3000 (eq elt (last buffer-undo-list))
3001 ;; `elt' is not in the log any more, but that's because
3002 ;; the log is "all new", so we should remove all
3003 ;; boundaries from it.
3004 (not (eq (last buffer-undo-list) (last old-cdr))))
3005 (cl-callf (lambda (x) (delq nil x))
3006 (if (car buffer-undo-list)
3007 buffer-undo-list
3008 ;; Preserve the undo-boundaries at either ends of the
3009 ;; change-groups.
3010 (cdr buffer-undo-list)))))
3011 ;; Reset the modified cons cell ELT to its original content.
3012 (when (consp elt)
3013 (setcar elt old-car)
3014 (setcdr elt old-cdr))))))))
3017 (defcustom undo-ask-before-discard nil
3018 "If non-nil ask about discarding undo info for the current command.
3019 Normally, Emacs discards the undo info for the current command if
3020 it exceeds `undo-outer-limit'. But if you set this option
3021 non-nil, it asks in the echo area whether to discard the info.
3022 If you answer no, there is a slight risk that Emacs might crash, so
3023 only do it if you really want to undo the command.
3025 This option is mainly intended for debugging. You have to be
3026 careful if you use it for other purposes. Garbage collection is
3027 inhibited while the question is asked, meaning that Emacs might
3028 leak memory. So you should make sure that you do not wait
3029 excessively long before answering the question."
3030 :type 'boolean
3031 :group 'undo
3032 :version "22.1")
3034 (defvar undo-extra-outer-limit nil
3035 "If non-nil, an extra level of size that's ok in an undo item.
3036 We don't ask the user about truncating the undo list until the
3037 current item gets bigger than this amount.
3039 This variable only matters if `undo-ask-before-discard' is non-nil.")
3040 (make-variable-buffer-local 'undo-extra-outer-limit)
3042 ;; When the first undo batch in an undo list is longer than
3043 ;; undo-outer-limit, this function gets called to warn the user that
3044 ;; the undo info for the current command was discarded. Garbage
3045 ;; collection is inhibited around the call, so it had better not do a
3046 ;; lot of consing.
3047 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3048 (defun undo-outer-limit-truncate (size)
3049 (if undo-ask-before-discard
3050 (when (or (null undo-extra-outer-limit)
3051 (> size undo-extra-outer-limit))
3052 ;; Don't ask the question again unless it gets even bigger.
3053 ;; This applies, in particular, if the user quits from the question.
3054 ;; Such a quit quits out of GC, but something else will call GC
3055 ;; again momentarily. It will call this function again,
3056 ;; but we don't want to ask the question again.
3057 (setq undo-extra-outer-limit (+ size 50000))
3058 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3059 (yes-or-no-p (format-message
3060 "Buffer `%s' undo info is %d bytes long; discard it? "
3061 (buffer-name) size)))
3062 (progn (setq buffer-undo-list nil)
3063 (setq undo-extra-outer-limit nil)
3065 nil))
3066 (display-warning '(undo discard-info)
3067 (concat
3068 (format-message
3069 "Buffer `%s' undo info was %d bytes long.\n"
3070 (buffer-name) size)
3071 "The undo info was discarded because it exceeded \
3072 `undo-outer-limit'.
3074 This is normal if you executed a command that made a huge change
3075 to the buffer. In that case, to prevent similar problems in the
3076 future, set `undo-outer-limit' to a value that is large enough to
3077 cover the maximum size of normal changes you expect a single
3078 command to make, but not so large that it might exceed the
3079 maximum memory allotted to Emacs.
3081 If you did not execute any such command, the situation is
3082 probably due to a bug and you should report it.
3084 You can disable the popping up of this buffer by adding the entry
3085 \(undo discard-info) to the user option `warning-suppress-types',
3086 which is defined in the `warnings' library.\n")
3087 :warning)
3088 (setq buffer-undo-list nil)
3091 (defcustom password-word-equivalents
3092 '("password" "passcode" "passphrase" "pass phrase"
3093 ; These are sorted according to the GNU en_US locale.
3094 "암호" ; ko
3095 "パスワード" ; ja
3096 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3097 "ពាក្យសម្ងាត់" ; km
3098 "adgangskode" ; da
3099 "contraseña" ; es
3100 "contrasenya" ; ca
3101 "geslo" ; sl
3102 "hasło" ; pl
3103 "heslo" ; cs, sk
3104 "iphasiwedi" ; zu
3105 "jelszó" ; hu
3106 "lösenord" ; sv
3107 "lozinka" ; hr, sr
3108 "mật khẩu" ; vi
3109 "mot de passe" ; fr
3110 "parola" ; tr
3111 "pasahitza" ; eu
3112 "passord" ; nb
3113 "passwort" ; de
3114 "pasvorto" ; eo
3115 "salasana" ; fi
3116 "senha" ; pt
3117 "slaptažodis" ; lt
3118 "wachtwoord" ; nl
3119 "كلمة السر" ; ar
3120 "ססמה" ; he
3121 "лозинка" ; sr
3122 "пароль" ; kk, ru, uk
3123 "गुप्तशब्द" ; mr
3124 "शब्दकूट" ; hi
3125 "પાસવર્ડ" ; gu
3126 "సంకేతపదము" ; te
3127 "ਪਾਸਵਰਡ" ; pa
3128 "ಗುಪ್ತಪದ" ; kn
3129 "கடவுச்சொல்" ; ta
3130 "അടയാളവാക്ക്" ; ml
3131 "গুপ্তশব্দ" ; as
3132 "পাসওয়ার্ড" ; bn_IN
3133 "රහස්පදය" ; si
3134 "密码" ; zh_CN
3135 "密碼" ; zh_TW
3137 "List of words equivalent to \"password\".
3138 This is used by Shell mode and other parts of Emacs to recognize
3139 password prompts, including prompts in languages other than
3140 English. Different case choices should not be assumed to be
3141 included; callers should bind `case-fold-search' to t."
3142 :type '(repeat string)
3143 :version "24.4"
3144 :group 'processes)
3146 (defvar shell-command-history nil
3147 "History list for some commands that read shell commands.
3149 Maximum length of the history list is determined by the value
3150 of `history-length', which see.")
3152 (defvar shell-command-switch (purecopy "-c")
3153 "Switch used to have the shell execute its command line argument.")
3155 (defvar shell-command-default-error-buffer nil
3156 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3157 This buffer is used when `shell-command' or `shell-command-on-region'
3158 is run interactively. A value of nil means that output to stderr and
3159 stdout will be intermixed in the output stream.")
3161 (declare-function mailcap-file-default-commands "mailcap" (files))
3162 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3164 (defun minibuffer-default-add-shell-commands ()
3165 "Return a list of all commands associated with the current file.
3166 This function is used to add all related commands retrieved by `mailcap'
3167 to the end of the list of defaults just after the default value."
3168 (interactive)
3169 (let* ((filename (if (listp minibuffer-default)
3170 (car minibuffer-default)
3171 minibuffer-default))
3172 (commands (and filename (require 'mailcap nil t)
3173 (mailcap-file-default-commands (list filename)))))
3174 (setq commands (mapcar (lambda (command)
3175 (concat command " " filename))
3176 commands))
3177 (if (listp minibuffer-default)
3178 (append minibuffer-default commands)
3179 (cons minibuffer-default commands))))
3181 (declare-function shell-completion-vars "shell" ())
3183 (defvar minibuffer-local-shell-command-map
3184 (let ((map (make-sparse-keymap)))
3185 (set-keymap-parent map minibuffer-local-map)
3186 (define-key map "\t" 'completion-at-point)
3187 map)
3188 "Keymap used for completing shell commands in minibuffer.")
3190 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3191 "Read a shell command from the minibuffer.
3192 The arguments are the same as the ones of `read-from-minibuffer',
3193 except READ and KEYMAP are missing and HIST defaults
3194 to `shell-command-history'."
3195 (require 'shell)
3196 (minibuffer-with-setup-hook
3197 (lambda ()
3198 (shell-completion-vars)
3199 (set (make-local-variable 'minibuffer-default-add-function)
3200 'minibuffer-default-add-shell-commands))
3201 (apply 'read-from-minibuffer prompt initial-contents
3202 minibuffer-local-shell-command-map
3204 (or hist 'shell-command-history)
3205 args)))
3207 (defcustom async-shell-command-buffer 'confirm-new-buffer
3208 "What to do when the output buffer is used by another shell command.
3209 This option specifies how to resolve the conflict where a new command
3210 wants to direct its output to the buffer `*Async Shell Command*',
3211 but this buffer is already taken by another running shell command.
3213 The value `confirm-kill-process' is used to ask for confirmation before
3214 killing the already running process and running a new process
3215 in the same buffer, `confirm-new-buffer' for confirmation before running
3216 the command in a new buffer with a name other than the default buffer name,
3217 `new-buffer' for doing the same without confirmation,
3218 `confirm-rename-buffer' for confirmation before renaming the existing
3219 output buffer and running a new command in the default buffer,
3220 `rename-buffer' for doing the same without confirmation."
3221 :type '(choice (const :tag "Confirm killing of running command"
3222 confirm-kill-process)
3223 (const :tag "Confirm creation of a new buffer"
3224 confirm-new-buffer)
3225 (const :tag "Create a new buffer"
3226 new-buffer)
3227 (const :tag "Confirm renaming of existing buffer"
3228 confirm-rename-buffer)
3229 (const :tag "Rename the existing buffer"
3230 rename-buffer))
3231 :group 'shell
3232 :version "24.3")
3234 (defun shell-command--save-pos-or-erase ()
3235 "Store a buffer position or erase the buffer.
3236 See `shell-command-dont-erase-buffer'."
3237 (let ((sym shell-command-dont-erase-buffer)
3238 pos)
3239 (setq buffer-read-only nil)
3240 ;; Setting buffer-read-only to nil doesn't suffice
3241 ;; if some text has a non-nil read-only property,
3242 ;; which comint sometimes adds for prompts.
3243 (setq pos
3244 (cond ((eq sym 'save-point) (point))
3245 ((eq sym 'beg-last-out) (point-max))
3246 ((not sym)
3247 (let ((inhibit-read-only t))
3248 (erase-buffer) nil))))
3249 (when pos
3250 (goto-char (point-max))
3251 (push (cons (current-buffer) pos)
3252 shell-command-saved-pos))))
3254 (defun shell-command--set-point-after-cmd (&optional buffer)
3255 "Set point in BUFFER after command complete.
3256 BUFFER is the output buffer of the command; if nil, then defaults
3257 to the current BUFFER.
3258 Set point to the `cdr' of the element in `shell-command-saved-pos'
3259 whose `car' is BUFFER."
3260 (when shell-command-dont-erase-buffer
3261 (let* ((sym shell-command-dont-erase-buffer)
3262 (buf (or buffer (current-buffer)))
3263 (pos (alist-get buf shell-command-saved-pos)))
3264 (setq shell-command-saved-pos
3265 (assq-delete-all buf shell-command-saved-pos))
3266 (when (buffer-live-p buf)
3267 (let ((win (car (get-buffer-window-list buf)))
3268 (pmax (with-current-buffer buf (point-max))))
3269 (unless (and pos (memq sym '(save-point beg-last-out)))
3270 (setq pos pmax))
3271 ;; Set point in the window displaying buf, if any; otherwise
3272 ;; display buf temporary in selected frame and set the point.
3273 (if win
3274 (set-window-point win pos)
3275 (save-window-excursion
3276 (let ((win (display-buffer
3278 '(nil (inhibit-switch-frame . t)))))
3279 (set-window-point win pos)))))))))
3281 (defun async-shell-command (command &optional output-buffer error-buffer)
3282 "Execute string COMMAND asynchronously in background.
3284 Like `shell-command', but adds `&' at the end of COMMAND
3285 to execute it asynchronously.
3287 The output appears in the buffer `*Async Shell Command*'.
3288 That buffer is in shell mode.
3290 You can configure `async-shell-command-buffer' to specify what to do in
3291 case when `*Async Shell Command*' buffer is already taken by another
3292 running shell command. To run COMMAND without displaying the output
3293 in a window you can configure `display-buffer-alist' to use the action
3294 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3296 In Elisp, you will often be better served by calling `start-process'
3297 directly, since it offers more control and does not impose the use of a
3298 shell (with its need to quote arguments)."
3299 (interactive
3300 (list
3301 (read-shell-command "Async shell command: " nil nil
3302 (let ((filename
3303 (cond
3304 (buffer-file-name)
3305 ((eq major-mode 'dired-mode)
3306 (dired-get-filename nil t)))))
3307 (and filename (file-relative-name filename))))
3308 current-prefix-arg
3309 shell-command-default-error-buffer))
3310 (unless (string-match "&[ \t]*\\'" command)
3311 (setq command (concat command " &")))
3312 (shell-command command output-buffer error-buffer))
3314 (defun shell-command (command &optional output-buffer error-buffer)
3315 "Execute string COMMAND in inferior shell; display output, if any.
3316 With prefix argument, insert the COMMAND's output at point.
3318 Interactively, prompt for COMMAND in the minibuffer.
3320 If COMMAND ends in `&', execute it asynchronously.
3321 The output appears in the buffer `*Async Shell Command*'.
3322 That buffer is in shell mode. You can also use
3323 `async-shell-command' that automatically adds `&'.
3325 Otherwise, COMMAND is executed synchronously. The output appears in
3326 the buffer `*Shell Command Output*'. If the output is short enough to
3327 display in the echo area (which is determined by the variables
3328 `resize-mini-windows' and `max-mini-window-height'), it is shown
3329 there, but it is nonetheless available in buffer `*Shell Command
3330 Output*' even though that buffer is not automatically displayed.
3332 To specify a coding system for converting non-ASCII characters
3333 in the shell command output, use \\[universal-coding-system-argument] \
3334 before this command.
3336 Noninteractive callers can specify coding systems by binding
3337 `coding-system-for-read' and `coding-system-for-write'.
3339 The optional second argument OUTPUT-BUFFER, if non-nil,
3340 says to put the output in some other buffer.
3341 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3342 and insert the output there; a non-nil value of
3343 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3344 If OUTPUT-BUFFER is not a buffer and not nil, insert the output
3345 in current buffer after point leaving mark after it.
3346 This cannot be done asynchronously.
3348 If the command terminates without error, but generates output,
3349 and you did not specify \"insert it in the current buffer\",
3350 the output can be displayed in the echo area or in its buffer.
3351 If the output is short enough to display in the echo area
3352 \(determined by the variable `max-mini-window-height' if
3353 `resize-mini-windows' is non-nil), it is shown there.
3354 Otherwise,the buffer containing the output is displayed.
3356 If there is output and an error, and you did not specify \"insert it
3357 in the current buffer\", a message about the error goes at the end
3358 of the output.
3360 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3361 or buffer name to which to direct the command's standard error output.
3362 If it is nil, error output is mingled with regular output.
3363 In an interactive call, the variable `shell-command-default-error-buffer'
3364 specifies the value of ERROR-BUFFER.
3366 In Elisp, you will often be better served by calling `call-process' or
3367 `start-process' directly, since it offers more control and does not impose
3368 the use of a shell (with its need to quote arguments)."
3370 (interactive
3371 (list
3372 (read-shell-command "Shell command: " nil nil
3373 (let ((filename
3374 (cond
3375 (buffer-file-name)
3376 ((eq major-mode 'dired-mode)
3377 (dired-get-filename nil t)))))
3378 (and filename (file-relative-name filename))))
3379 current-prefix-arg
3380 shell-command-default-error-buffer))
3381 ;; Look for a handler in case default-directory is a remote file name.
3382 (let ((handler
3383 (find-file-name-handler (directory-file-name default-directory)
3384 'shell-command)))
3385 (if handler
3386 (funcall handler 'shell-command command output-buffer error-buffer)
3387 (if (and output-buffer
3388 (not (or (bufferp output-buffer) (stringp output-buffer))))
3389 ;; Output goes in current buffer.
3390 (let ((error-file
3391 (if error-buffer
3392 (make-temp-file
3393 (expand-file-name "scor"
3394 (or small-temporary-file-directory
3395 temporary-file-directory)))
3396 nil)))
3397 (barf-if-buffer-read-only)
3398 (push-mark nil t)
3399 ;; We do not use -f for csh; we will not support broken use of
3400 ;; .cshrcs. Even the BSD csh manual says to use
3401 ;; "if ($?prompt) exit" before things which are not useful
3402 ;; non-interactively. Besides, if someone wants their other
3403 ;; aliases for shell commands then they can still have them.
3404 (call-process shell-file-name nil
3405 (if error-file
3406 (list t error-file)
3408 nil shell-command-switch command)
3409 (when (and error-file (file-exists-p error-file))
3410 (if (< 0 (nth 7 (file-attributes error-file)))
3411 (with-current-buffer (get-buffer-create error-buffer)
3412 (let ((pos-from-end (- (point-max) (point))))
3413 (or (bobp)
3414 (insert "\f\n"))
3415 ;; Do no formatting while reading error file,
3416 ;; because that can run a shell command, and we
3417 ;; don't want that to cause an infinite recursion.
3418 (format-insert-file error-file nil)
3419 ;; Put point after the inserted errors.
3420 (goto-char (- (point-max) pos-from-end)))
3421 (display-buffer (current-buffer))))
3422 (delete-file error-file))
3423 ;; This is like exchange-point-and-mark, but doesn't
3424 ;; activate the mark. It is cleaner to avoid activation,
3425 ;; even though the command loop would deactivate the mark
3426 ;; because we inserted text.
3427 (goto-char (prog1 (mark t)
3428 (set-marker (mark-marker) (point)
3429 (current-buffer)))))
3430 ;; Output goes in a separate buffer.
3431 ;; Preserve the match data in case called from a program.
3432 ;; FIXME: It'd be ridiculous for an Elisp function to call
3433 ;; shell-command and assume that it won't mess the match-data!
3434 (save-match-data
3435 (if (string-match "[ \t]*&[ \t]*\\'" command)
3436 ;; Command ending with ampersand means asynchronous.
3437 (let ((buffer (get-buffer-create
3438 (or output-buffer "*Async Shell Command*")))
3439 (directory default-directory)
3440 proc)
3441 ;; Remove the ampersand.
3442 (setq command (substring command 0 (match-beginning 0)))
3443 ;; Ask the user what to do with already running process.
3444 (setq proc (get-buffer-process buffer))
3445 (when proc
3446 (cond
3447 ((eq async-shell-command-buffer 'confirm-kill-process)
3448 ;; If will kill a process, query first.
3449 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3450 (kill-process proc)
3451 (error "Shell command in progress")))
3452 ((eq async-shell-command-buffer 'confirm-new-buffer)
3453 ;; If will create a new buffer, query first.
3454 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3455 (setq buffer (generate-new-buffer
3456 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3457 output-buffer "*Async Shell Command*")))
3458 (error "Shell command in progress")))
3459 ((eq async-shell-command-buffer 'new-buffer)
3460 ;; It will create a new buffer.
3461 (setq buffer (generate-new-buffer
3462 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3463 output-buffer "*Async Shell Command*"))))
3464 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3465 ;; If will rename the buffer, query first.
3466 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3467 (progn
3468 (with-current-buffer buffer
3469 (rename-uniquely))
3470 (setq buffer (get-buffer-create
3471 (or output-buffer "*Async Shell Command*"))))
3472 (error "Shell command in progress")))
3473 ((eq async-shell-command-buffer 'rename-buffer)
3474 ;; It will rename the buffer.
3475 (with-current-buffer buffer
3476 (rename-uniquely))
3477 (setq buffer (get-buffer-create
3478 (or output-buffer "*Async Shell Command*"))))))
3479 (with-current-buffer buffer
3480 (display-buffer buffer '(nil (allow-no-window . t)))
3481 (shell-command--save-pos-or-erase)
3482 (setq default-directory directory)
3483 (setq proc (start-process "Shell" buffer shell-file-name
3484 shell-command-switch command))
3485 (setq mode-line-process '(":%s"))
3486 (require 'shell) (shell-mode)
3487 (set-process-sentinel proc 'shell-command-sentinel)
3488 ;; Use the comint filter for proper handling of carriage motion
3489 ;; (see `comint-inhibit-carriage-motion'),.
3490 (set-process-filter proc 'comint-output-filter)
3492 ;; Otherwise, command is executed synchronously.
3493 (shell-command-on-region (point) (point) command
3494 output-buffer nil error-buffer)))))))
3496 (defun display-message-or-buffer (message &optional buffer-name action frame)
3497 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3498 MESSAGE may be either a string or a buffer.
3500 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3501 for maximum height of the echo area, as defined by `max-mini-window-height'
3502 if `resize-mini-windows' is non-nil.
3504 Returns either the string shown in the echo area, or when a pop-up
3505 buffer is used, the window used to display it.
3507 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3508 name of the buffer used to display it in the case where a pop-up buffer
3509 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3510 string and it is displayed in the echo area, it is not specified whether
3511 the contents are inserted into the buffer anyway.
3513 Optional arguments ACTION and FRAME are as for `display-buffer',
3514 and are only used if a pop-up buffer is displayed."
3515 (cond ((and (stringp message) (not (string-match "\n" message)))
3516 ;; Trivial case where we can use the echo area
3517 (message "%s" message))
3518 ((and (stringp message)
3519 (= (string-match "\n" message) (1- (length message))))
3520 ;; Trivial case where we can just remove single trailing newline
3521 (message "%s" (substring message 0 (1- (length message)))))
3523 ;; General case
3524 (with-current-buffer
3525 (if (bufferp message)
3526 message
3527 (get-buffer-create (or buffer-name "*Message*")))
3529 (unless (bufferp message)
3530 (erase-buffer)
3531 (insert message))
3533 (let ((lines
3534 (if (= (buffer-size) 0)
3536 (count-screen-lines nil nil nil (minibuffer-window)))))
3537 (cond ((= lines 0))
3538 ((and (or (<= lines 1)
3539 (<= lines
3540 (if resize-mini-windows
3541 (cond ((floatp max-mini-window-height)
3542 (* (frame-height)
3543 max-mini-window-height))
3544 ((integerp max-mini-window-height)
3545 max-mini-window-height)
3548 1)))
3549 ;; Don't use the echo area if the output buffer is
3550 ;; already displayed in the selected frame.
3551 (not (get-buffer-window (current-buffer))))
3552 ;; Echo area
3553 (goto-char (point-max))
3554 (when (bolp)
3555 (backward-char 1))
3556 (message "%s" (buffer-substring (point-min) (point))))
3558 ;; Buffer
3559 (goto-char (point-min))
3560 (display-buffer (current-buffer) action frame))))))))
3563 ;; We have a sentinel to prevent insertion of a termination message
3564 ;; in the buffer itself, and to set the point in the buffer when
3565 ;; `shell-command-dont-erase-buffer' is non-nil.
3566 (defun shell-command-sentinel (process signal)
3567 (when (memq (process-status process) '(exit signal))
3568 (shell-command--set-point-after-cmd (process-buffer process))
3569 (message "%s: %s."
3570 (car (cdr (cdr (process-command process))))
3571 (substring signal 0 -1))))
3573 (defun shell-command-on-region (start end command
3574 &optional output-buffer replace
3575 error-buffer display-error-buffer
3576 region-noncontiguous-p)
3577 "Execute string COMMAND in inferior shell with region as input.
3578 Normally display output (if any) in temp buffer `*Shell Command Output*';
3579 Prefix arg means replace the region with it. Return the exit code of
3580 COMMAND.
3582 To specify a coding system for converting non-ASCII characters
3583 in the input and output to the shell command, use \\[universal-coding-system-argument]
3584 before this command. By default, the input (from the current buffer)
3585 is encoded using coding-system specified by `process-coding-system-alist',
3586 falling back to `default-process-coding-system' if no match for COMMAND
3587 is found in `process-coding-system-alist'.
3589 Noninteractive callers can specify coding systems by binding
3590 `coding-system-for-read' and `coding-system-for-write'.
3592 If the command generates output, the output may be displayed
3593 in the echo area or in a buffer.
3594 If the output is short enough to display in the echo area
3595 \(determined by the variable `max-mini-window-height' if
3596 `resize-mini-windows' is non-nil), it is shown there.
3597 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3598 The output is available in that buffer in both cases.
3600 If there is output and an error, a message about the error
3601 appears at the end of the output.
3603 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3604 command's output. If the value is a buffer or buffer name,
3605 erase that buffer and insert the output there; a non-nil value of
3606 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3607 If the value is nil, use the buffer `*Shell Command Output*'.
3608 Any other non-nil value means to insert the output in the
3609 current buffer after START.
3611 Optional fifth arg REPLACE, if non-nil, means to insert the
3612 output in place of text from START to END, putting point and mark
3613 around it.
3615 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3616 or buffer name to which to direct the command's standard error
3617 output. If nil, error output is mingled with regular output.
3618 When called interactively, `shell-command-default-error-buffer'
3619 is used for ERROR-BUFFER.
3621 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3622 display the error buffer if there were any errors. When called
3623 interactively, this is t."
3624 (interactive (let (string)
3625 (unless (mark)
3626 (user-error "The mark is not set now, so there is no region"))
3627 ;; Do this before calling region-beginning
3628 ;; and region-end, in case subprocess output
3629 ;; relocates them while we are in the minibuffer.
3630 (setq string (read-shell-command "Shell command on region: "))
3631 ;; call-interactively recognizes region-beginning and
3632 ;; region-end specially, leaving them in the history.
3633 (list (region-beginning) (region-end)
3634 string
3635 current-prefix-arg
3636 current-prefix-arg
3637 shell-command-default-error-buffer
3639 (region-noncontiguous-p))))
3640 (let ((error-file
3641 (if error-buffer
3642 (make-temp-file
3643 (expand-file-name "scor"
3644 (or small-temporary-file-directory
3645 temporary-file-directory)))
3646 nil))
3647 exit-status)
3648 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3649 (if region-noncontiguous-p
3650 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3651 output)
3652 (with-temp-buffer
3653 (insert input)
3654 (call-process-region (point-min) (point-max)
3655 shell-file-name t t
3656 nil shell-command-switch
3657 command)
3658 (setq output (split-string (buffer-string) "\n")))
3659 (goto-char start)
3660 (funcall region-insert-function output))
3661 (if (or replace
3662 (and output-buffer
3663 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3664 ;; Replace specified region with output from command.
3665 (let ((swap (and replace (< start end))))
3666 ;; Don't muck with mark unless REPLACE says we should.
3667 (goto-char start)
3668 (and replace (push-mark (point) 'nomsg))
3669 (setq exit-status
3670 (call-shell-region start end command replace
3671 (if error-file
3672 (list t error-file)
3673 t)))
3674 ;; It is rude to delete a buffer which the command is not using.
3675 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3676 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3677 ;; (kill-buffer shell-buffer)))
3678 ;; Don't muck with mark unless REPLACE says we should.
3679 (and replace swap (exchange-point-and-mark)))
3680 ;; No prefix argument: put the output in a temp buffer,
3681 ;; replacing its entire contents.
3682 (let ((buffer (get-buffer-create
3683 (or output-buffer "*Shell Command Output*"))))
3684 (unwind-protect
3685 (if (and (eq buffer (current-buffer))
3686 (or (not shell-command-dont-erase-buffer)
3687 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3688 (not (region-active-p)))))
3689 ;; If the input is the same buffer as the output,
3690 ;; delete everything but the specified region,
3691 ;; then replace that region with the output.
3692 (progn (setq buffer-read-only nil)
3693 (delete-region (max start end) (point-max))
3694 (delete-region (point-min) (min start end))
3695 (setq exit-status
3696 (call-process-region (point-min) (point-max)
3697 shell-file-name t
3698 (if error-file
3699 (list t error-file)
3701 nil shell-command-switch
3702 command)))
3703 ;; Clear the output buffer, then run the command with
3704 ;; output there.
3705 (let ((directory default-directory))
3706 (with-current-buffer buffer
3707 (if (not output-buffer)
3708 (setq default-directory directory))
3709 (shell-command--save-pos-or-erase)))
3710 (setq exit-status
3711 (call-shell-region start end command nil
3712 (if error-file
3713 (list buffer error-file)
3714 buffer))))
3715 ;; Report the output.
3716 (with-current-buffer buffer
3717 (setq mode-line-process
3718 (cond ((null exit-status)
3719 " - Error")
3720 ((stringp exit-status)
3721 (format " - Signal [%s]" exit-status))
3722 ((not (equal 0 exit-status))
3723 (format " - Exit [%d]" exit-status)))))
3724 (if (with-current-buffer buffer (> (point-max) (point-min)))
3725 ;; There's some output, display it
3726 (progn
3727 (display-message-or-buffer buffer)
3728 (shell-command--set-point-after-cmd buffer))
3729 ;; No output; error?
3730 (let ((output
3731 (if (and error-file
3732 (< 0 (nth 7 (file-attributes error-file))))
3733 (format "some error output%s"
3734 (if shell-command-default-error-buffer
3735 (format " to the \"%s\" buffer"
3736 shell-command-default-error-buffer)
3737 ""))
3738 "no output")))
3739 (cond ((null exit-status)
3740 (message "(Shell command failed with error)"))
3741 ((equal 0 exit-status)
3742 (message "(Shell command succeeded with %s)"
3743 output))
3744 ((stringp exit-status)
3745 (message "(Shell command killed by signal %s)"
3746 exit-status))
3748 (message "(Shell command failed with code %d and %s)"
3749 exit-status output))))
3750 ;; Don't kill: there might be useful info in the undo-log.
3751 ;; (kill-buffer buffer)
3752 )))))
3754 (when (and error-file (file-exists-p error-file))
3755 (if (< 0 (nth 7 (file-attributes error-file)))
3756 (with-current-buffer (get-buffer-create error-buffer)
3757 (let ((pos-from-end (- (point-max) (point))))
3758 (or (bobp)
3759 (insert "\f\n"))
3760 ;; Do no formatting while reading error file,
3761 ;; because that can run a shell command, and we
3762 ;; don't want that to cause an infinite recursion.
3763 (format-insert-file error-file nil)
3764 ;; Put point after the inserted errors.
3765 (goto-char (- (point-max) pos-from-end)))
3766 (and display-error-buffer
3767 (display-buffer (current-buffer)))))
3768 (delete-file error-file))
3769 exit-status))
3771 (defun shell-command-to-string (command)
3772 "Execute shell command COMMAND and return its output as a string."
3773 (with-output-to-string
3774 (with-current-buffer
3775 standard-output
3776 (process-file shell-file-name nil t nil shell-command-switch command))))
3778 (defun process-file (program &optional infile buffer display &rest args)
3779 "Process files synchronously in a separate process.
3780 Similar to `call-process', but may invoke a file handler based on
3781 `default-directory'. The current working directory of the
3782 subprocess is `default-directory'.
3784 File names in INFILE and BUFFER are handled normally, but file
3785 names in ARGS should be relative to `default-directory', as they
3786 are passed to the process verbatim. (This is a difference to
3787 `call-process' which does not support file handlers for INFILE
3788 and BUFFER.)
3790 Some file handlers might not support all variants, for example
3791 they might behave as if DISPLAY was nil, regardless of the actual
3792 value passed."
3793 (let ((fh (find-file-name-handler default-directory 'process-file))
3794 lc stderr-file)
3795 (unwind-protect
3796 (if fh (apply fh 'process-file program infile buffer display args)
3797 (when infile (setq lc (file-local-copy infile)))
3798 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3799 (make-temp-file "emacs")))
3800 (prog1
3801 (apply 'call-process program
3802 (or lc infile)
3803 (if stderr-file (list (car buffer) stderr-file) buffer)
3804 display args)
3805 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3806 (when stderr-file (delete-file stderr-file))
3807 (when lc (delete-file lc)))))
3809 (defvar process-file-side-effects t
3810 "Whether a call of `process-file' changes remote files.
3812 By default, this variable is always set to t, meaning that a
3813 call of `process-file' could potentially change any file on a
3814 remote host. When set to nil, a file handler could optimize
3815 its behavior with respect to remote file attribute caching.
3817 You should only ever change this variable with a let-binding;
3818 never with `setq'.")
3820 (defun start-file-process (name buffer program &rest program-args)
3821 "Start a program in a subprocess. Return the process object for it.
3823 Similar to `start-process', but may invoke a file handler based on
3824 `default-directory'. See Info node `(elisp)Magic File Names'.
3826 This handler ought to run PROGRAM, perhaps on the local host,
3827 perhaps on a remote host that corresponds to `default-directory'.
3828 In the latter case, the local part of `default-directory' becomes
3829 the working directory of the process.
3831 PROGRAM and PROGRAM-ARGS might be file names. They are not
3832 objects of file handler invocation. File handlers might not
3833 support pty association, if PROGRAM is nil."
3834 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3835 (if fh (apply fh 'start-file-process name buffer program program-args)
3836 (apply 'start-process name buffer program program-args))))
3838 ;;;; Process menu
3840 (defvar tabulated-list-format)
3841 (defvar tabulated-list-entries)
3842 (defvar tabulated-list-sort-key)
3843 (declare-function tabulated-list-init-header "tabulated-list" ())
3844 (declare-function tabulated-list-print "tabulated-list"
3845 (&optional remember-pos update))
3847 (defvar process-menu-query-only nil)
3849 (defvar process-menu-mode-map
3850 (let ((map (make-sparse-keymap)))
3851 (define-key map [?d] 'process-menu-delete-process)
3852 map))
3854 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3855 "Major mode for listing the processes called by Emacs."
3856 (setq tabulated-list-format [("Process" 15 t)
3857 ("PID" 7 t)
3858 ("Status" 7 t)
3859 ("Buffer" 15 t)
3860 ("TTY" 12 t)
3861 ("Command" 0 t)])
3862 (make-local-variable 'process-menu-query-only)
3863 (setq tabulated-list-sort-key (cons "Process" nil))
3864 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3865 (tabulated-list-init-header))
3867 (defun process-menu-delete-process ()
3868 "Kill process at point in a `list-processes' buffer."
3869 (interactive)
3870 (let ((pos (point)))
3871 (delete-process (tabulated-list-get-id))
3872 (revert-buffer)
3873 (goto-char (min pos (point-max)))
3874 (if (eobp)
3875 (forward-line -1)
3876 (beginning-of-line))))
3878 (defun list-processes--refresh ()
3879 "Recompute the list of processes for the Process List buffer.
3880 Also, delete any process that is exited or signaled."
3881 (setq tabulated-list-entries nil)
3882 (dolist (p (process-list))
3883 (cond ((memq (process-status p) '(exit signal closed))
3884 (delete-process p))
3885 ((or (not process-menu-query-only)
3886 (process-query-on-exit-flag p))
3887 (let* ((buf (process-buffer p))
3888 (type (process-type p))
3889 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3890 (name (process-name p))
3891 (status (symbol-name (process-status p)))
3892 (buf-label (if (buffer-live-p buf)
3893 `(,(buffer-name buf)
3894 face link
3895 help-echo ,(format-message
3896 "Visit buffer `%s'"
3897 (buffer-name buf))
3898 follow-link t
3899 process-buffer ,buf
3900 action process-menu-visit-buffer)
3901 "--"))
3902 (tty (or (process-tty-name p) "--"))
3903 (cmd
3904 (if (memq type '(network serial))
3905 (let ((contact (process-contact p t)))
3906 (if (eq type 'network)
3907 (format "(%s %s)"
3908 (if (plist-get contact :type)
3909 "datagram"
3910 "network")
3911 (if (plist-get contact :server)
3912 (format "server on %s"
3914 (plist-get contact :host)
3915 (plist-get contact :local)))
3916 (format "connection to %s"
3917 (plist-get contact :host))))
3918 (format "(serial port %s%s)"
3919 (or (plist-get contact :port) "?")
3920 (let ((speed (plist-get contact :speed)))
3921 (if speed
3922 (format " at %s b/s" speed)
3923 "")))))
3924 (mapconcat 'identity (process-command p) " "))))
3925 (push (list p (vector name pid status buf-label tty cmd))
3926 tabulated-list-entries))))))
3928 (defun process-menu-visit-buffer (button)
3929 (display-buffer (button-get button 'process-buffer)))
3931 (defun list-processes (&optional query-only buffer)
3932 "Display a list of all processes that are Emacs sub-processes.
3933 If optional argument QUERY-ONLY is non-nil, only processes with
3934 the query-on-exit flag set are listed.
3935 Any process listed as exited or signaled is actually eliminated
3936 after the listing is made.
3937 Optional argument BUFFER specifies a buffer to use, instead of
3938 \"*Process List*\".
3939 The return value is always nil.
3941 This function lists only processes that were launched by Emacs. To
3942 see other processes running on the system, use `list-system-processes'."
3943 (interactive)
3944 (or (fboundp 'process-list)
3945 (error "Asynchronous subprocesses are not supported on this system"))
3946 (unless (bufferp buffer)
3947 (setq buffer (get-buffer-create "*Process List*")))
3948 (with-current-buffer buffer
3949 (process-menu-mode)
3950 (setq process-menu-query-only query-only)
3951 (list-processes--refresh)
3952 (tabulated-list-print))
3953 (display-buffer buffer)
3954 nil)
3956 ;;;; Prefix commands
3958 (setq prefix-command--needs-update nil)
3959 (setq prefix-command--last-echo nil)
3961 (defun internal-echo-keystrokes-prefix ()
3962 ;; BEWARE: Called directly from C code.
3963 ;; If the return value is non-nil, it means we are in the middle of
3964 ;; a command with prefix, such as a command invoked with prefix-arg.
3965 (if (not prefix-command--needs-update)
3966 prefix-command--last-echo
3967 (setq prefix-command--last-echo
3968 (let ((strs nil))
3969 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3970 (lambda (fun) (push (funcall fun) strs)))
3971 (setq strs (delq nil strs))
3972 (when strs (mapconcat #'identity strs " "))))))
3974 (defvar prefix-command-echo-keystrokes-functions nil
3975 "Abnormal hook which constructs the description of the current prefix state.
3976 Each function is called with no argument, should return a string or nil.")
3978 (defun prefix-command-update ()
3979 "Update state of prefix commands.
3980 Call it whenever you change the \"prefix command state\"."
3981 (setq prefix-command--needs-update t))
3983 (defvar prefix-command-preserve-state-hook nil
3984 "Normal hook run when a command needs to preserve the prefix.")
3986 (defun prefix-command-preserve-state ()
3987 "Pass the current prefix command state to the next command.
3988 Should be called by all prefix commands.
3989 Runs `prefix-command-preserve-state-hook'."
3990 (run-hooks 'prefix-command-preserve-state-hook)
3991 ;; If the current command is a prefix command, we don't want the next (real)
3992 ;; command to have `last-command' set to, say, `universal-argument'.
3993 (setq this-command last-command)
3994 (setq real-this-command real-last-command)
3995 (prefix-command-update))
3997 (defun reset-this-command-lengths ()
3998 (declare (obsolete prefix-command-preserve-state "25.1"))
3999 nil)
4001 ;;;;; The main prefix command.
4003 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4005 (add-hook 'prefix-command-echo-keystrokes-functions
4006 #'universal-argument--description)
4007 (defun universal-argument--description ()
4008 (when prefix-arg
4009 (concat "C-u"
4010 (pcase prefix-arg
4011 (`(-) " -")
4012 (`(,(and (pred integerp) n))
4013 (let ((str ""))
4014 (while (and (> n 4) (= (mod n 4) 0))
4015 (setq str (concat str " C-u"))
4016 (setq n (/ n 4)))
4017 (if (= n 4) str (format " %s" prefix-arg))))
4018 (_ (format " %s" prefix-arg))))))
4020 (add-hook 'prefix-command-preserve-state-hook
4021 #'universal-argument--preserve)
4022 (defun universal-argument--preserve ()
4023 (setq prefix-arg current-prefix-arg))
4025 (defvar universal-argument-map
4026 (let ((map (make-sparse-keymap))
4027 (universal-argument-minus
4028 ;; For backward compatibility, minus with no modifiers is an ordinary
4029 ;; command if digits have already been entered.
4030 `(menu-item "" negative-argument
4031 :filter ,(lambda (cmd)
4032 (if (integerp prefix-arg) nil cmd)))))
4033 (define-key map [switch-frame]
4034 (lambda (e) (interactive "e")
4035 (handle-switch-frame e) (universal-argument--mode)))
4036 (define-key map [?\C-u] 'universal-argument-more)
4037 (define-key map [?-] universal-argument-minus)
4038 (define-key map [?0] 'digit-argument)
4039 (define-key map [?1] 'digit-argument)
4040 (define-key map [?2] 'digit-argument)
4041 (define-key map [?3] 'digit-argument)
4042 (define-key map [?4] 'digit-argument)
4043 (define-key map [?5] 'digit-argument)
4044 (define-key map [?6] 'digit-argument)
4045 (define-key map [?7] 'digit-argument)
4046 (define-key map [?8] 'digit-argument)
4047 (define-key map [?9] 'digit-argument)
4048 (define-key map [kp-0] 'digit-argument)
4049 (define-key map [kp-1] 'digit-argument)
4050 (define-key map [kp-2] 'digit-argument)
4051 (define-key map [kp-3] 'digit-argument)
4052 (define-key map [kp-4] 'digit-argument)
4053 (define-key map [kp-5] 'digit-argument)
4054 (define-key map [kp-6] 'digit-argument)
4055 (define-key map [kp-7] 'digit-argument)
4056 (define-key map [kp-8] 'digit-argument)
4057 (define-key map [kp-9] 'digit-argument)
4058 (define-key map [kp-subtract] universal-argument-minus)
4059 map)
4060 "Keymap used while processing \\[universal-argument].")
4062 (defun universal-argument--mode ()
4063 (prefix-command-update)
4064 (set-transient-map universal-argument-map nil))
4066 (defun universal-argument ()
4067 "Begin a numeric argument for the following command.
4068 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4069 \\[universal-argument] following the digits or minus sign ends the argument.
4070 \\[universal-argument] without digits or minus sign provides 4 as argument.
4071 Repeating \\[universal-argument] without digits or minus sign
4072 multiplies the argument by 4 each time.
4073 For some commands, just \\[universal-argument] by itself serves as a flag
4074 which is different in effect from any particular numeric argument.
4075 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4076 (interactive)
4077 (prefix-command-preserve-state)
4078 (setq prefix-arg (list 4))
4079 (universal-argument--mode))
4081 (defun universal-argument-more (arg)
4082 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4083 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4084 (interactive "P")
4085 (prefix-command-preserve-state)
4086 (setq prefix-arg (if (consp arg)
4087 (list (* 4 (car arg)))
4088 (if (eq arg '-)
4089 (list -4)
4090 arg)))
4091 (when (consp prefix-arg) (universal-argument--mode)))
4093 (defun negative-argument (arg)
4094 "Begin a negative numeric argument for the next command.
4095 \\[universal-argument] following digits or minus sign ends the argument."
4096 (interactive "P")
4097 (prefix-command-preserve-state)
4098 (setq prefix-arg (cond ((integerp arg) (- arg))
4099 ((eq arg '-) nil)
4100 (t '-)))
4101 (universal-argument--mode))
4103 (defun digit-argument (arg)
4104 "Part of the numeric argument for the next command.
4105 \\[universal-argument] following digits or minus sign ends the argument."
4106 (interactive "P")
4107 (prefix-command-preserve-state)
4108 (let* ((char (if (integerp last-command-event)
4109 last-command-event
4110 (get last-command-event 'ascii-character)))
4111 (digit (- (logand char ?\177) ?0)))
4112 (setq prefix-arg (cond ((integerp arg)
4113 (+ (* arg 10)
4114 (if (< arg 0) (- digit) digit)))
4115 ((eq arg '-)
4116 ;; Treat -0 as just -, so that -01 will work.
4117 (if (zerop digit) '- (- digit)))
4119 digit))))
4120 (universal-argument--mode))
4123 (defvar filter-buffer-substring-functions nil
4124 "This variable is a wrapper hook around `buffer-substring--filter'.")
4125 (make-obsolete-variable 'filter-buffer-substring-functions
4126 'filter-buffer-substring-function "24.4")
4128 (defvar filter-buffer-substring-function #'buffer-substring--filter
4129 "Function to perform the filtering in `filter-buffer-substring'.
4130 The function is called with the same 3 arguments (BEG END DELETE)
4131 that `filter-buffer-substring' received. It should return the
4132 buffer substring between BEG and END, after filtering. If DELETE is
4133 non-nil, it should delete the text between BEG and END from the buffer.")
4135 (defvar buffer-substring-filters nil
4136 "List of filter functions for `buffer-substring--filter'.
4137 Each function must accept a single argument, a string, and return a string.
4138 The buffer substring is passed to the first function in the list,
4139 and the return value of each function is passed to the next.
4140 As a special convention, point is set to the start of the buffer text
4141 being operated on (i.e., the first argument of `buffer-substring--filter')
4142 before these functions are called.")
4143 (make-obsolete-variable 'buffer-substring-filters
4144 'filter-buffer-substring-function "24.1")
4146 (defun filter-buffer-substring (beg end &optional delete)
4147 "Return the buffer substring between BEG and END, after filtering.
4148 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4150 This calls the function that `filter-buffer-substring-function' specifies
4151 \(passing the same three arguments that it received) to do the work,
4152 and returns whatever it does. The default function does no filtering,
4153 unless a hook has been set.
4155 Use `filter-buffer-substring' instead of `buffer-substring',
4156 `buffer-substring-no-properties', or `delete-and-extract-region' when
4157 you want to allow filtering to take place. For example, major or minor
4158 modes can use `filter-buffer-substring-function' to extract characters
4159 that are special to a buffer, and should not be copied into other buffers."
4160 (funcall filter-buffer-substring-function beg end delete))
4162 (defun buffer-substring--filter (beg end &optional delete)
4163 "Default function to use for `filter-buffer-substring-function'.
4164 Its arguments and return value are as specified for `filter-buffer-substring'.
4165 This respects the wrapper hook `filter-buffer-substring-functions',
4166 and the abnormal hook `buffer-substring-filters'.
4167 No filtering is done unless a hook says to."
4168 (subr--with-wrapper-hook-no-warnings
4169 filter-buffer-substring-functions (beg end delete)
4170 (cond
4171 ((or delete buffer-substring-filters)
4172 (save-excursion
4173 (goto-char beg)
4174 (let ((string (if delete (delete-and-extract-region beg end)
4175 (buffer-substring beg end))))
4176 (dolist (filter buffer-substring-filters)
4177 (setq string (funcall filter string)))
4178 string)))
4180 (buffer-substring beg end)))))
4183 ;;;; Window system cut and paste hooks.
4185 (defvar interprogram-cut-function #'gui-select-text
4186 "Function to call to make a killed region available to other programs.
4187 Most window systems provide a facility for cutting and pasting
4188 text between different programs, such as the clipboard on X and
4189 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4191 This variable holds a function that Emacs calls whenever text is
4192 put in the kill ring, to make the new kill available to other
4193 programs. The function takes one argument, TEXT, which is a
4194 string containing the text which should be made available.")
4196 (defvar interprogram-paste-function #'gui-selection-value
4197 "Function to call to get text cut from other programs.
4198 Most window systems provide a facility for cutting and pasting
4199 text between different programs, such as the clipboard on X and
4200 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4202 This variable holds a function that Emacs calls to obtain text
4203 that other programs have provided for pasting. The function is
4204 called with no arguments. If no other program has provided text
4205 to paste, the function should return nil (in which case the
4206 caller, usually `current-kill', should use the top of the Emacs
4207 kill ring). If another program has provided text to paste, the
4208 function should return that text as a string (in which case the
4209 caller should put this string in the kill ring as the latest
4210 kill).
4212 The function may also return a list of strings if the window
4213 system supports multiple selections. The first string will be
4214 used as the pasted text, but the other will be placed in the kill
4215 ring for easy access via `yank-pop'.
4217 Note that the function should return a string only if a program
4218 other than Emacs has provided a string for pasting; if Emacs
4219 provided the most recent string, the function should return nil.
4220 If it is difficult to tell whether Emacs or some other program
4221 provided the current string, it is probably good enough to return
4222 nil if the string is equal (according to `string=') to the last
4223 text Emacs provided.")
4227 ;;;; The kill ring data structure.
4229 (defvar kill-ring nil
4230 "List of killed text sequences.
4231 Since the kill ring is supposed to interact nicely with cut-and-paste
4232 facilities offered by window systems, use of this variable should
4233 interact nicely with `interprogram-cut-function' and
4234 `interprogram-paste-function'. The functions `kill-new',
4235 `kill-append', and `current-kill' are supposed to implement this
4236 interaction; you may want to use them instead of manipulating the kill
4237 ring directly.")
4239 (defcustom kill-ring-max 60
4240 "Maximum length of kill ring before oldest elements are thrown away."
4241 :type 'integer
4242 :group 'killing)
4244 (defvar kill-ring-yank-pointer nil
4245 "The tail of the kill ring whose car is the last thing yanked.")
4247 (defcustom save-interprogram-paste-before-kill nil
4248 "Save clipboard strings into kill ring before replacing them.
4249 When one selects something in another program to paste it into Emacs,
4250 but kills something in Emacs before actually pasting it,
4251 this selection is gone unless this variable is non-nil,
4252 in which case the other program's selection is saved in the `kill-ring'
4253 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4254 :type 'boolean
4255 :group 'killing
4256 :version "23.2")
4258 (defcustom kill-do-not-save-duplicates nil
4259 "Do not add a new string to `kill-ring' if it duplicates the last one.
4260 The comparison is done using `equal-including-properties'."
4261 :type 'boolean
4262 :group 'killing
4263 :version "23.2")
4265 (defun kill-new (string &optional replace)
4266 "Make STRING the latest kill in the kill ring.
4267 Set `kill-ring-yank-pointer' to point to it.
4268 If `interprogram-cut-function' is non-nil, apply it to STRING.
4269 Optional second argument REPLACE non-nil means that STRING will replace
4270 the front of the kill ring, rather than being added to the list.
4272 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4273 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4274 STRING.
4276 When the yank handler has a non-nil PARAM element, the original STRING
4277 argument is not used by `insert-for-yank'. However, since Lisp code
4278 may access and use elements from the kill ring directly, the STRING
4279 argument should still be a \"useful\" string for such uses."
4280 (unless (and kill-do-not-save-duplicates
4281 ;; Due to text properties such as 'yank-handler that
4282 ;; can alter the contents to yank, comparison using
4283 ;; `equal' is unsafe.
4284 (equal-including-properties string (car kill-ring)))
4285 (if (fboundp 'menu-bar-update-yank-menu)
4286 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4287 (when save-interprogram-paste-before-kill
4288 (let ((interprogram-paste (and interprogram-paste-function
4289 (funcall interprogram-paste-function))))
4290 (when interprogram-paste
4291 (dolist (s (if (listp interprogram-paste)
4292 (nreverse interprogram-paste)
4293 (list interprogram-paste)))
4294 (unless (and kill-do-not-save-duplicates
4295 (equal-including-properties s (car kill-ring)))
4296 (push s kill-ring))))))
4297 (unless (and kill-do-not-save-duplicates
4298 (equal-including-properties string (car kill-ring)))
4299 (if (and replace kill-ring)
4300 (setcar kill-ring string)
4301 (push string kill-ring)
4302 (if (> (length kill-ring) kill-ring-max)
4303 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4304 (setq kill-ring-yank-pointer kill-ring)
4305 (if interprogram-cut-function
4306 (funcall interprogram-cut-function string)))
4308 ;; It has been argued that this should work similar to `self-insert-command'
4309 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4310 (defcustom kill-append-merge-undo nil
4311 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4312 :type 'boolean
4313 :group 'killing
4314 :version "25.1")
4316 (defun kill-append (string before-p)
4317 "Append STRING to the end of the latest kill in the kill ring.
4318 If BEFORE-P is non-nil, prepend STRING to the kill.
4319 Also removes the last undo boundary in the current buffer,
4320 depending on `kill-append-merge-undo'.
4321 If `interprogram-cut-function' is set, pass the resulting kill to it."
4322 (let* ((cur (car kill-ring)))
4323 (kill-new (if before-p (concat string cur) (concat cur string))
4324 (or (= (length cur) 0)
4325 (equal nil (get-text-property 0 'yank-handler cur))))
4326 (when (and kill-append-merge-undo (not buffer-read-only))
4327 (let ((prev buffer-undo-list)
4328 (next (cdr buffer-undo-list)))
4329 ;; find the next undo boundary
4330 (while (car next)
4331 (pop next)
4332 (pop prev))
4333 ;; remove this undo boundary
4334 (when prev
4335 (setcdr prev (cdr next)))))))
4337 (defcustom yank-pop-change-selection nil
4338 "Whether rotating the kill ring changes the window system selection.
4339 If non-nil, whenever the kill ring is rotated (usually via the
4340 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4341 to copy the new kill to the window system selection."
4342 :type 'boolean
4343 :group 'killing
4344 :version "23.1")
4346 (defun current-kill (n &optional do-not-move)
4347 "Rotate the yanking point by N places, and then return that kill.
4348 If N is zero and `interprogram-paste-function' is set to a
4349 function that returns a string or a list of strings, and if that
4350 function doesn't return nil, then that string (or list) is added
4351 to the front of the kill ring and the string (or first string in
4352 the list) is returned as the latest kill.
4354 If N is not zero, and if `yank-pop-change-selection' is
4355 non-nil, use `interprogram-cut-function' to transfer the
4356 kill at the new yank point into the window system selection.
4358 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4359 move the yanking point; just return the Nth kill forward."
4361 (let ((interprogram-paste (and (= n 0)
4362 interprogram-paste-function
4363 (funcall interprogram-paste-function))))
4364 (if interprogram-paste
4365 (progn
4366 ;; Disable the interprogram cut function when we add the new
4367 ;; text to the kill ring, so Emacs doesn't try to own the
4368 ;; selection, with identical text.
4369 (let ((interprogram-cut-function nil))
4370 (if (listp interprogram-paste)
4371 (mapc 'kill-new (nreverse interprogram-paste))
4372 (kill-new interprogram-paste)))
4373 (car kill-ring))
4374 (or kill-ring (error "Kill ring is empty"))
4375 (let ((ARGth-kill-element
4376 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4377 (length kill-ring))
4378 kill-ring)))
4379 (unless do-not-move
4380 (setq kill-ring-yank-pointer ARGth-kill-element)
4381 (when (and yank-pop-change-selection
4382 (> n 0)
4383 interprogram-cut-function)
4384 (funcall interprogram-cut-function (car ARGth-kill-element))))
4385 (car ARGth-kill-element)))))
4389 ;;;; Commands for manipulating the kill ring.
4391 (defcustom kill-read-only-ok nil
4392 "Non-nil means don't signal an error for killing read-only text."
4393 :type 'boolean
4394 :group 'killing)
4396 (defun kill-region (beg end &optional region)
4397 "Kill (\"cut\") text between point and mark.
4398 This deletes the text from the buffer and saves it in the kill ring.
4399 The command \\[yank] can retrieve it from there.
4400 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4402 If you want to append the killed region to the last killed text,
4403 use \\[append-next-kill] before \\[kill-region].
4405 Any command that calls this function is a \"kill command\".
4406 If the previous command was also a kill command,
4407 the text killed this time appends to the text killed last time
4408 to make one entry in the kill ring.
4410 The killed text is filtered by `filter-buffer-substring' before it is
4411 saved in the kill ring, so the actual saved text might be different
4412 from what was killed.
4414 If the buffer is read-only, Emacs will beep and refrain from deleting
4415 the text, but put the text in the kill ring anyway. This means that
4416 you can use the killing commands to copy text from a read-only buffer.
4418 Lisp programs should use this function for killing text.
4419 (To delete text, use `delete-region'.)
4420 Supply two arguments, character positions BEG and END indicating the
4421 stretch of text to be killed. If the optional argument REGION is
4422 non-nil, the function ignores BEG and END, and kills the current
4423 region instead."
4424 ;; Pass mark first, then point, because the order matters when
4425 ;; calling `kill-append'.
4426 (interactive (list (mark) (point) 'region))
4427 (unless (and beg end)
4428 (user-error "The mark is not set now, so there is no region"))
4429 (condition-case nil
4430 (let ((string (if region
4431 (funcall region-extract-function 'delete)
4432 (filter-buffer-substring beg end 'delete))))
4433 (when string ;STRING is nil if BEG = END
4434 ;; Add that string to the kill ring, one way or another.
4435 (if (eq last-command 'kill-region)
4436 (kill-append string (< end beg))
4437 (kill-new string)))
4438 (when (or string (eq last-command 'kill-region))
4439 (setq this-command 'kill-region))
4440 (setq deactivate-mark t)
4441 nil)
4442 ((buffer-read-only text-read-only)
4443 ;; The code above failed because the buffer, or some of the characters
4444 ;; in the region, are read-only.
4445 ;; We should beep, in case the user just isn't aware of this.
4446 ;; However, there's no harm in putting
4447 ;; the region's text in the kill ring, anyway.
4448 (copy-region-as-kill beg end region)
4449 ;; Set this-command now, so it will be set even if we get an error.
4450 (setq this-command 'kill-region)
4451 ;; This should barf, if appropriate, and give us the correct error.
4452 (if kill-read-only-ok
4453 (progn (message "Read only text copied to kill ring") nil)
4454 ;; Signal an error if the buffer is read-only.
4455 (barf-if-buffer-read-only)
4456 ;; If the buffer isn't read-only, the text is.
4457 (signal 'text-read-only (list (current-buffer)))))))
4459 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4460 ;; to get two copies of the text when the user accidentally types M-w and
4461 ;; then corrects it with the intended C-w.
4462 (defun copy-region-as-kill (beg end &optional region)
4463 "Save the region as if killed, but don't kill it.
4464 In Transient Mark mode, deactivate the mark.
4465 If `interprogram-cut-function' is non-nil, also save the text for a window
4466 system cut and paste.
4468 The copied text is filtered by `filter-buffer-substring' before it is
4469 saved in the kill ring, so the actual saved text might be different
4470 from what was in the buffer.
4472 When called from Lisp, save in the kill ring the stretch of text
4473 between BEG and END, unless the optional argument REGION is
4474 non-nil, in which case ignore BEG and END, and save the current
4475 region instead.
4477 This command's old key binding has been given to `kill-ring-save'."
4478 ;; Pass mark first, then point, because the order matters when
4479 ;; calling `kill-append'.
4480 (interactive (list (mark) (point)
4481 (prefix-numeric-value current-prefix-arg)))
4482 (let ((str (if region
4483 (funcall region-extract-function nil)
4484 (filter-buffer-substring beg end))))
4485 (if (eq last-command 'kill-region)
4486 (kill-append str (< end beg))
4487 (kill-new str)))
4488 (setq deactivate-mark t)
4489 nil)
4491 (defun kill-ring-save (beg end &optional region)
4492 "Save the region as if killed, but don't kill it.
4493 In Transient Mark mode, deactivate the mark.
4494 If `interprogram-cut-function' is non-nil, also save the text for a window
4495 system cut and paste.
4497 If you want to append the killed line to the last killed text,
4498 use \\[append-next-kill] before \\[kill-ring-save].
4500 The copied text is filtered by `filter-buffer-substring' before it is
4501 saved in the kill ring, so the actual saved text might be different
4502 from what was in the buffer.
4504 When called from Lisp, save in the kill ring the stretch of text
4505 between BEG and END, unless the optional argument REGION is
4506 non-nil, in which case ignore BEG and END, and save the current
4507 region instead.
4509 This command is similar to `copy-region-as-kill', except that it gives
4510 visual feedback indicating the extent of the region being copied."
4511 ;; Pass mark first, then point, because the order matters when
4512 ;; calling `kill-append'.
4513 (interactive (list (mark) (point)
4514 (prefix-numeric-value current-prefix-arg)))
4515 (copy-region-as-kill beg end region)
4516 ;; This use of called-interactively-p is correct because the code it
4517 ;; controls just gives the user visual feedback.
4518 (if (called-interactively-p 'interactive)
4519 (indicate-copied-region)))
4521 (defun indicate-copied-region (&optional message-len)
4522 "Indicate that the region text has been copied interactively.
4523 If the mark is visible in the selected window, blink the cursor
4524 between point and mark if there is currently no active region
4525 highlighting.
4527 If the mark lies outside the selected window, display an
4528 informative message containing a sample of the copied text. The
4529 optional argument MESSAGE-LEN, if non-nil, specifies the length
4530 of this sample text; it defaults to 40."
4531 (let ((mark (mark t))
4532 (point (point))
4533 ;; Inhibit quitting so we can make a quit here
4534 ;; look like a C-g typed as a command.
4535 (inhibit-quit t))
4536 (if (pos-visible-in-window-p mark (selected-window))
4537 ;; Swap point-and-mark quickly so as to show the region that
4538 ;; was selected. Don't do it if the region is highlighted.
4539 (unless (and (region-active-p)
4540 (face-background 'region))
4541 ;; Swap point and mark.
4542 (set-marker (mark-marker) (point) (current-buffer))
4543 (goto-char mark)
4544 (sit-for blink-matching-delay)
4545 ;; Swap back.
4546 (set-marker (mark-marker) mark (current-buffer))
4547 (goto-char point)
4548 ;; If user quit, deactivate the mark
4549 ;; as C-g would as a command.
4550 (and quit-flag (region-active-p)
4551 (deactivate-mark)))
4552 (let ((len (min (abs (- mark point))
4553 (or message-len 40))))
4554 (if (< point mark)
4555 ;; Don't say "killed"; that is misleading.
4556 (message "Saved text until \"%s\""
4557 (buffer-substring-no-properties (- mark len) mark))
4558 (message "Saved text from \"%s\""
4559 (buffer-substring-no-properties mark (+ mark len))))))))
4561 (defun append-next-kill (&optional interactive)
4562 "Cause following command, if it kills, to add to previous kill.
4563 If the next command kills forward from point, the kill is
4564 appended to the previous killed text. If the command kills
4565 backward, the kill is prepended. Kill commands that act on the
4566 region, such as `kill-region', are regarded as killing forward if
4567 point is after mark, and killing backward if point is before
4568 mark.
4570 If the next command is not a kill command, `append-next-kill' has
4571 no effect.
4573 The argument is used for internal purposes; do not supply one."
4574 (interactive "p")
4575 ;; We don't use (interactive-p), since that breaks kbd macros.
4576 (if interactive
4577 (progn
4578 (setq this-command 'kill-region)
4579 (message "If the next command is a kill, it will append"))
4580 (setq last-command 'kill-region)))
4582 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4583 "Character set that matches bidirectional formatting control characters.")
4585 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4586 "Character set that matches any character except bidirectional controls.")
4588 (defun squeeze-bidi-context-1 (from to category replacement)
4589 "A subroutine of `squeeze-bidi-context'.
4590 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4591 (let ((pt (copy-marker from))
4592 (limit (copy-marker to))
4593 (old-pt 0)
4594 lim1)
4595 (setq lim1 limit)
4596 (goto-char pt)
4597 (while (< pt limit)
4598 (if (> pt old-pt)
4599 (move-marker lim1
4600 (save-excursion
4601 ;; L and R categories include embedding and
4602 ;; override controls, but we don't want to
4603 ;; replace them, because that might change
4604 ;; the visual order. Likewise with PDF and
4605 ;; isolate controls.
4606 (+ pt (skip-chars-forward
4607 bidi-directional-non-controls-chars
4608 limit)))))
4609 ;; Replace any run of non-RTL characters by a single LRM.
4610 (if (null (re-search-forward category lim1 t))
4611 ;; No more characters of CATEGORY, we are done.
4612 (setq pt limit)
4613 (replace-match replacement nil t)
4614 (move-marker pt (point)))
4615 (setq old-pt pt)
4616 ;; Skip directional controls, if any.
4617 (move-marker
4618 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4620 (defun squeeze-bidi-context (from to)
4621 "Replace characters between FROM and TO while keeping bidi context.
4623 This function replaces the region of text with as few characters
4624 as possible, while preserving the effect that region will have on
4625 bidirectional display before and after the region."
4626 (let ((start (set-marker (make-marker)
4627 (if (> from 0) from (+ (point-max) from))))
4628 (end (set-marker (make-marker) to))
4629 ;; This is for when they copy text with read-only text
4630 ;; properties.
4631 (inhibit-read-only t))
4632 (if (null (marker-position end))
4633 (setq end (point-max-marker)))
4634 ;; Replace each run of non-RTL characters with a single LRM.
4635 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4636 ;; Replace each run of non-LTR characters with a single RLM. Note
4637 ;; that the \cR category includes both the Arabic Letter (AL) and
4638 ;; R characters; here we ignore the distinction between them,
4639 ;; because that distinction only affects Arabic Number (AN)
4640 ;; characters, which are weak and don't affect the reordering.
4641 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4643 (defun line-substring-with-bidi-context (start end &optional no-properties)
4644 "Return buffer text between START and END with its bidi context.
4646 START and END are assumed to belong to the same physical line
4647 of buffer text. This function prepends and appends to the text
4648 between START and END bidi control characters that preserve the
4649 visual order of that text when it is inserted at some other place."
4650 (if (or (< start (point-min))
4651 (> end (point-max)))
4652 (signal 'args-out-of-range (list (current-buffer) start end)))
4653 (let ((buf (current-buffer))
4654 substr para-dir from to)
4655 (save-excursion
4656 (goto-char start)
4657 (setq para-dir (current-bidi-paragraph-direction))
4658 (setq from (line-beginning-position)
4659 to (line-end-position))
4660 (goto-char from)
4661 ;; If we don't have any mixed directional characters in the
4662 ;; entire line, we can just copy the substring without adding
4663 ;; any context.
4664 (if (or (looking-at-p "\\CR*$")
4665 (looking-at-p "\\CL*$"))
4666 (setq substr (if no-properties
4667 (buffer-substring-no-properties start end)
4668 (buffer-substring start end)))
4669 (setq substr
4670 (with-temp-buffer
4671 (if no-properties
4672 (insert-buffer-substring-no-properties buf from to)
4673 (insert-buffer-substring buf from to))
4674 (squeeze-bidi-context 1 (1+ (- start from)))
4675 (squeeze-bidi-context (- end to) nil)
4676 (buffer-substring 1 (point-max)))))
4678 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4679 ;; (1) force the string to have the same base embedding
4680 ;; direction as the paragraph direction at the source, no matter
4681 ;; what is the paragraph direction at destination; and (2) avoid
4682 ;; affecting the visual order of the surrounding text at
4683 ;; destination if there are characters of different
4684 ;; directionality there.
4685 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4686 substr "\x2069"))))
4688 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4689 "Return portion of current buffer between START and END with bidi context.
4691 This function works similar to `buffer-substring', but it prepends and
4692 appends to the text bidi directional control characters necessary to
4693 preserve the visual appearance of the text if it is inserted at another
4694 place. This is useful when the buffer substring includes bidirectional
4695 text and control characters that cause non-trivial reordering on display.
4696 If copied verbatim, such text can have a very different visual appearance,
4697 and can also change the visual appearance of the surrounding text at the
4698 destination of the copy.
4700 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4701 the text properties."
4702 (let (line-end substr)
4703 (if (or (< start (point-min))
4704 (> end (point-max)))
4705 (signal 'args-out-of-range (list (current-buffer) start end)))
4706 (save-excursion
4707 (goto-char start)
4708 (setq line-end (min end (line-end-position)))
4709 (while (< start end)
4710 (setq substr
4711 (concat substr
4712 (if substr "\n" "")
4713 (line-substring-with-bidi-context start line-end
4714 no-properties)))
4715 (forward-line 1)
4716 (setq start (point))
4717 (setq line-end (min end (line-end-position))))
4718 substr)))
4720 ;; Yanking.
4722 (defcustom yank-handled-properties
4723 '((font-lock-face . yank-handle-font-lock-face-property)
4724 (category . yank-handle-category-property))
4725 "List of special text property handling conditions for yanking.
4726 Each element should have the form (PROP . FUN), where PROP is a
4727 property symbol and FUN is a function. When the `yank' command
4728 inserts text into the buffer, it scans the inserted text for
4729 stretches of text that have `eq' values of the text property
4730 PROP; for each such stretch of text, FUN is called with three
4731 arguments: the property's value in that text, and the start and
4732 end positions of the text.
4734 This is done prior to removing the properties specified by
4735 `yank-excluded-properties'."
4736 :group 'killing
4737 :type '(repeat (cons (symbol :tag "property symbol")
4738 function))
4739 :version "24.3")
4741 ;; This is actually used in subr.el but defcustom does not work there.
4742 (defcustom yank-excluded-properties
4743 '(category field follow-link fontified font-lock-face help-echo
4744 intangible invisible keymap local-map mouse-face read-only
4745 yank-handler)
4746 "Text properties to discard when yanking.
4747 The value should be a list of text properties to discard or t,
4748 which means to discard all text properties.
4750 See also `yank-handled-properties'."
4751 :type '(choice (const :tag "All" t) (repeat symbol))
4752 :group 'killing
4753 :version "24.3")
4755 (defvar yank-window-start nil)
4756 (defvar yank-undo-function nil
4757 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4758 Function is called with two parameters, START and END corresponding to
4759 the value of the mark and point; it is guaranteed that START <= END.
4760 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4762 (defun yank-pop (&optional arg)
4763 "Replace just-yanked stretch of killed text with a different stretch.
4764 This command is allowed only immediately after a `yank' or a `yank-pop'.
4765 At such a time, the region contains a stretch of reinserted
4766 previously-killed text. `yank-pop' deletes that text and inserts in its
4767 place a different stretch of killed text.
4769 With no argument, the previous kill is inserted.
4770 With argument N, insert the Nth previous kill.
4771 If N is negative, this is a more recent kill.
4773 The sequence of kills wraps around, so that after the oldest one
4774 comes the newest one.
4776 When this command inserts killed text into the buffer, it honors
4777 `yank-excluded-properties' and `yank-handler' as described in the
4778 doc string for `insert-for-yank-1', which see."
4779 (interactive "*p")
4780 (if (not (eq last-command 'yank))
4781 (user-error "Previous command was not a yank"))
4782 (setq this-command 'yank)
4783 (unless arg (setq arg 1))
4784 (let ((inhibit-read-only t)
4785 (before (< (point) (mark t))))
4786 (if before
4787 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4788 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4789 (setq yank-undo-function nil)
4790 (set-marker (mark-marker) (point) (current-buffer))
4791 (insert-for-yank (current-kill arg))
4792 ;; Set the window start back where it was in the yank command,
4793 ;; if possible.
4794 (set-window-start (selected-window) yank-window-start t)
4795 (if before
4796 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4797 ;; It is cleaner to avoid activation, even though the command
4798 ;; loop would deactivate the mark because we inserted text.
4799 (goto-char (prog1 (mark t)
4800 (set-marker (mark-marker) (point) (current-buffer))))))
4801 nil)
4803 (defun yank (&optional arg)
4804 "Reinsert (\"paste\") the last stretch of killed text.
4805 More precisely, reinsert the most recent kill, which is the
4806 stretch of killed text most recently killed OR yanked. Put point
4807 at the end, and set mark at the beginning without activating it.
4808 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4809 With argument N, reinsert the Nth most recent kill.
4811 When this command inserts text into the buffer, it honors the
4812 `yank-handled-properties' and `yank-excluded-properties'
4813 variables, and the `yank-handler' text property. See
4814 `insert-for-yank-1' for details.
4816 See also the command `yank-pop' (\\[yank-pop])."
4817 (interactive "*P")
4818 (setq yank-window-start (window-start))
4819 ;; If we don't get all the way thru, make last-command indicate that
4820 ;; for the following command.
4821 (setq this-command t)
4822 (push-mark (point))
4823 (insert-for-yank (current-kill (cond
4824 ((listp arg) 0)
4825 ((eq arg '-) -2)
4826 (t (1- arg)))))
4827 (if (consp arg)
4828 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4829 ;; It is cleaner to avoid activation, even though the command
4830 ;; loop would deactivate the mark because we inserted text.
4831 (goto-char (prog1 (mark t)
4832 (set-marker (mark-marker) (point) (current-buffer)))))
4833 ;; If we do get all the way thru, make this-command indicate that.
4834 (if (eq this-command t)
4835 (setq this-command 'yank))
4836 nil)
4838 (defun rotate-yank-pointer (arg)
4839 "Rotate the yanking point in the kill ring.
4840 With ARG, rotate that many kills forward (or backward, if negative)."
4841 (interactive "p")
4842 (current-kill arg))
4844 ;; Some kill commands.
4846 ;; Internal subroutine of delete-char
4847 (defun kill-forward-chars (arg)
4848 (if (listp arg) (setq arg (car arg)))
4849 (if (eq arg '-) (setq arg -1))
4850 (kill-region (point) (+ (point) arg)))
4852 ;; Internal subroutine of backward-delete-char
4853 (defun kill-backward-chars (arg)
4854 (if (listp arg) (setq arg (car arg)))
4855 (if (eq arg '-) (setq arg -1))
4856 (kill-region (point) (- (point) arg)))
4858 (defcustom backward-delete-char-untabify-method 'untabify
4859 "The method for untabifying when deleting backward.
4860 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4861 `hungry' -- delete all whitespace, both tabs and spaces;
4862 `all' -- delete all whitespace, including tabs, spaces and newlines;
4863 nil -- just delete one character."
4864 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4865 :version "20.3"
4866 :group 'killing)
4868 (defun backward-delete-char-untabify (arg &optional killp)
4869 "Delete characters backward, changing tabs into spaces.
4870 The exact behavior depends on `backward-delete-char-untabify-method'.
4871 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4872 Interactively, ARG is the prefix arg (default 1)
4873 and KILLP is t if a prefix arg was specified."
4874 (interactive "*p\nP")
4875 (when (eq backward-delete-char-untabify-method 'untabify)
4876 (let ((count arg))
4877 (save-excursion
4878 (while (and (> count 0) (not (bobp)))
4879 (if (= (preceding-char) ?\t)
4880 (let ((col (current-column)))
4881 (forward-char -1)
4882 (setq col (- col (current-column)))
4883 (insert-char ?\s col)
4884 (delete-char 1)))
4885 (forward-char -1)
4886 (setq count (1- count))))))
4887 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4888 ((eq backward-delete-char-untabify-method 'all)
4889 " \t\n\r")))
4890 (n (if skip
4891 (let* ((oldpt (point))
4892 (wh (- oldpt (save-excursion
4893 (skip-chars-backward skip)
4894 (constrain-to-field nil oldpt)))))
4895 (+ arg (if (zerop wh) 0 (1- wh))))
4896 arg)))
4897 ;; Avoid warning about delete-backward-char
4898 (with-no-warnings (delete-backward-char n killp))))
4900 (defun zap-to-char (arg char)
4901 "Kill up to and including ARGth occurrence of CHAR.
4902 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4903 Goes backward if ARG is negative; error if CHAR not found."
4904 (interactive (list (prefix-numeric-value current-prefix-arg)
4905 (read-char "Zap to char: " t)))
4906 ;; Avoid "obsolete" warnings for translation-table-for-input.
4907 (with-no-warnings
4908 (if (char-table-p translation-table-for-input)
4909 (setq char (or (aref translation-table-for-input char) char))))
4910 (kill-region (point) (progn
4911 (search-forward (char-to-string char) nil nil arg)
4912 (point))))
4914 ;; kill-line and its subroutines.
4916 (defcustom kill-whole-line nil
4917 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4918 :type 'boolean
4919 :group 'killing)
4921 (defun kill-line (&optional arg)
4922 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4923 With prefix argument ARG, kill that many lines from point.
4924 Negative arguments kill lines backward.
4925 With zero argument, kills the text before point on the current line.
4927 When calling from a program, nil means \"no arg\",
4928 a number counts as a prefix arg.
4930 To kill a whole line, when point is not at the beginning, type \
4931 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4933 If `show-trailing-whitespace' is non-nil, this command will just
4934 kill the rest of the current line, even if there are only
4935 nonblanks there.
4937 If option `kill-whole-line' is non-nil, then this command kills the whole line
4938 including its terminating newline, when used at the beginning of a line
4939 with no argument. As a consequence, you can always kill a whole line
4940 by typing \\[move-beginning-of-line] \\[kill-line].
4942 If you want to append the killed line to the last killed text,
4943 use \\[append-next-kill] before \\[kill-line].
4945 If the buffer is read-only, Emacs will beep and refrain from deleting
4946 the line, but put the line in the kill ring anyway. This means that
4947 you can use this command to copy text from a read-only buffer.
4948 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4949 even beep.)"
4950 (interactive "P")
4951 (kill-region (point)
4952 ;; It is better to move point to the other end of the kill
4953 ;; before killing. That way, in a read-only buffer, point
4954 ;; moves across the text that is copied to the kill ring.
4955 ;; The choice has no effect on undo now that undo records
4956 ;; the value of point from before the command was run.
4957 (progn
4958 (if arg
4959 (forward-visible-line (prefix-numeric-value arg))
4960 (if (eobp)
4961 (signal 'end-of-buffer nil))
4962 (let ((end
4963 (save-excursion
4964 (end-of-visible-line) (point))))
4965 (if (or (save-excursion
4966 ;; If trailing whitespace is visible,
4967 ;; don't treat it as nothing.
4968 (unless show-trailing-whitespace
4969 (skip-chars-forward " \t" end))
4970 (= (point) end))
4971 (and kill-whole-line (bolp)))
4972 (forward-visible-line 1)
4973 (goto-char end))))
4974 (point))))
4976 (defun kill-whole-line (&optional arg)
4977 "Kill current line.
4978 With prefix ARG, kill that many lines starting from the current line.
4979 If ARG is negative, kill backward. Also kill the preceding newline.
4980 \(This is meant to make \\[repeat] work well with negative arguments.)
4981 If ARG is zero, kill current line but exclude the trailing newline."
4982 (interactive "p")
4983 (or arg (setq arg 1))
4984 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4985 (signal 'end-of-buffer nil))
4986 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4987 (signal 'beginning-of-buffer nil))
4988 (unless (eq last-command 'kill-region)
4989 (kill-new "")
4990 (setq last-command 'kill-region))
4991 (cond ((zerop arg)
4992 ;; We need to kill in two steps, because the previous command
4993 ;; could have been a kill command, in which case the text
4994 ;; before point needs to be prepended to the current kill
4995 ;; ring entry and the text after point appended. Also, we
4996 ;; need to use save-excursion to avoid copying the same text
4997 ;; twice to the kill ring in read-only buffers.
4998 (save-excursion
4999 (kill-region (point) (progn (forward-visible-line 0) (point))))
5000 (kill-region (point) (progn (end-of-visible-line) (point))))
5001 ((< arg 0)
5002 (save-excursion
5003 (kill-region (point) (progn (end-of-visible-line) (point))))
5004 (kill-region (point)
5005 (progn (forward-visible-line (1+ arg))
5006 (unless (bobp) (backward-char))
5007 (point))))
5009 (save-excursion
5010 (kill-region (point) (progn (forward-visible-line 0) (point))))
5011 (kill-region (point)
5012 (progn (forward-visible-line arg) (point))))))
5014 (defun forward-visible-line (arg)
5015 "Move forward by ARG lines, ignoring currently invisible newlines only.
5016 If ARG is negative, move backward -ARG lines.
5017 If ARG is zero, move to the beginning of the current line."
5018 (condition-case nil
5019 (if (> arg 0)
5020 (progn
5021 (while (> arg 0)
5022 (or (zerop (forward-line 1))
5023 (signal 'end-of-buffer nil))
5024 ;; If the newline we just skipped is invisible,
5025 ;; don't count it.
5026 (let ((prop
5027 (get-char-property (1- (point)) 'invisible)))
5028 (if (if (eq buffer-invisibility-spec t)
5029 prop
5030 (or (memq prop buffer-invisibility-spec)
5031 (assq prop buffer-invisibility-spec)))
5032 (setq arg (1+ arg))))
5033 (setq arg (1- arg)))
5034 ;; If invisible text follows, and it is a number of complete lines,
5035 ;; skip it.
5036 (let ((opoint (point)))
5037 (while (and (not (eobp))
5038 (let ((prop
5039 (get-char-property (point) 'invisible)))
5040 (if (eq buffer-invisibility-spec t)
5041 prop
5042 (or (memq prop buffer-invisibility-spec)
5043 (assq prop buffer-invisibility-spec)))))
5044 (goto-char
5045 (if (get-text-property (point) 'invisible)
5046 (or (next-single-property-change (point) 'invisible)
5047 (point-max))
5048 (next-overlay-change (point)))))
5049 (unless (bolp)
5050 (goto-char opoint))))
5051 (let ((first t))
5052 (while (or first (<= arg 0))
5053 (if first
5054 (beginning-of-line)
5055 (or (zerop (forward-line -1))
5056 (signal 'beginning-of-buffer nil)))
5057 ;; If the newline we just moved to is invisible,
5058 ;; don't count it.
5059 (unless (bobp)
5060 (let ((prop
5061 (get-char-property (1- (point)) 'invisible)))
5062 (unless (if (eq buffer-invisibility-spec t)
5063 prop
5064 (or (memq prop buffer-invisibility-spec)
5065 (assq prop buffer-invisibility-spec)))
5066 (setq arg (1+ arg)))))
5067 (setq first nil))
5068 ;; If invisible text follows, and it is a number of complete lines,
5069 ;; skip it.
5070 (let ((opoint (point)))
5071 (while (and (not (bobp))
5072 (let ((prop
5073 (get-char-property (1- (point)) 'invisible)))
5074 (if (eq buffer-invisibility-spec t)
5075 prop
5076 (or (memq prop buffer-invisibility-spec)
5077 (assq prop buffer-invisibility-spec)))))
5078 (goto-char
5079 (if (get-text-property (1- (point)) 'invisible)
5080 (or (previous-single-property-change (point) 'invisible)
5081 (point-min))
5082 (previous-overlay-change (point)))))
5083 (unless (bolp)
5084 (goto-char opoint)))))
5085 ((beginning-of-buffer end-of-buffer)
5086 nil)))
5088 (defun end-of-visible-line ()
5089 "Move to end of current visible line."
5090 (end-of-line)
5091 ;; If the following character is currently invisible,
5092 ;; skip all characters with that same `invisible' property value,
5093 ;; then find the next newline.
5094 (while (and (not (eobp))
5095 (save-excursion
5096 (skip-chars-forward "^\n")
5097 (let ((prop
5098 (get-char-property (point) 'invisible)))
5099 (if (eq buffer-invisibility-spec t)
5100 prop
5101 (or (memq prop buffer-invisibility-spec)
5102 (assq prop buffer-invisibility-spec))))))
5103 (skip-chars-forward "^\n")
5104 (if (get-text-property (point) 'invisible)
5105 (goto-char (or (next-single-property-change (point) 'invisible)
5106 (point-max)))
5107 (goto-char (next-overlay-change (point))))
5108 (end-of-line)))
5110 (defun insert-buffer (buffer)
5111 "Insert after point the contents of BUFFER.
5112 Puts mark after the inserted text.
5113 BUFFER may be a buffer or a buffer name."
5114 (declare (interactive-only insert-buffer-substring))
5115 (interactive
5116 (list
5117 (progn
5118 (barf-if-buffer-read-only)
5119 (read-buffer "Insert buffer: "
5120 (if (eq (selected-window) (next-window))
5121 (other-buffer (current-buffer))
5122 (window-buffer (next-window)))
5123 t))))
5124 (push-mark
5125 (save-excursion
5126 (insert-buffer-substring (get-buffer buffer))
5127 (point)))
5128 nil)
5130 (defun append-to-buffer (buffer start end)
5131 "Append to specified buffer the text of the region.
5132 It is inserted into that buffer before its point.
5134 When calling from a program, give three arguments:
5135 BUFFER (or buffer name), START and END.
5136 START and END specify the portion of the current buffer to be copied."
5137 (interactive
5138 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5139 (region-beginning) (region-end)))
5140 (let* ((oldbuf (current-buffer))
5141 (append-to (get-buffer-create buffer))
5142 (windows (get-buffer-window-list append-to t t))
5143 point)
5144 (save-excursion
5145 (with-current-buffer append-to
5146 (setq point (point))
5147 (barf-if-buffer-read-only)
5148 (insert-buffer-substring oldbuf start end)
5149 (dolist (window windows)
5150 (when (= (window-point window) point)
5151 (set-window-point window (point))))))))
5153 (defun prepend-to-buffer (buffer start end)
5154 "Prepend to specified buffer the text of the region.
5155 It is inserted into that buffer after its point.
5157 When calling from a program, give three arguments:
5158 BUFFER (or buffer name), START and END.
5159 START and END specify the portion of the current buffer to be copied."
5160 (interactive "BPrepend to buffer: \nr")
5161 (let ((oldbuf (current-buffer)))
5162 (with-current-buffer (get-buffer-create buffer)
5163 (barf-if-buffer-read-only)
5164 (save-excursion
5165 (insert-buffer-substring oldbuf start end)))))
5167 (defun copy-to-buffer (buffer start end)
5168 "Copy to specified buffer the text of the region.
5169 It is inserted into that buffer, replacing existing text there.
5171 When calling from a program, give three arguments:
5172 BUFFER (or buffer name), START and END.
5173 START and END specify the portion of the current buffer to be copied."
5174 (interactive "BCopy to buffer: \nr")
5175 (let ((oldbuf (current-buffer)))
5176 (with-current-buffer (get-buffer-create buffer)
5177 (barf-if-buffer-read-only)
5178 (erase-buffer)
5179 (save-excursion
5180 (insert-buffer-substring oldbuf start end)))))
5182 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5184 (defvar activate-mark-hook nil
5185 "Hook run when the mark becomes active.
5186 It is also run at the end of a command, if the mark is active and
5187 it is possible that the region may have changed.")
5189 (defvar deactivate-mark-hook nil
5190 "Hook run when the mark becomes inactive.")
5192 (defun mark (&optional force)
5193 "Return this buffer's mark value as integer, or nil if never set.
5195 In Transient Mark mode, this function signals an error if
5196 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5197 or the argument FORCE is non-nil, it disregards whether the mark
5198 is active, and returns an integer or nil in the usual way.
5200 If you are using this in an editing command, you are most likely making
5201 a mistake; see the documentation of `set-mark'."
5202 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5203 (marker-position (mark-marker))
5204 (signal 'mark-inactive nil)))
5206 ;; Behind display-selections-p.
5208 (defun deactivate-mark (&optional force)
5209 "Deactivate the mark.
5210 If Transient Mark mode is disabled, this function normally does
5211 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5213 Deactivating the mark sets `mark-active' to nil, updates the
5214 primary selection according to `select-active-regions', and runs
5215 `deactivate-mark-hook'.
5217 If Transient Mark mode was temporarily enabled, reset the value
5218 of the variable `transient-mark-mode'; if this causes Transient
5219 Mark mode to be disabled, don't change `mark-active' to nil or
5220 run `deactivate-mark-hook'."
5221 (when (or (region-active-p) force)
5222 (when (and (if (eq select-active-regions 'only)
5223 (eq (car-safe transient-mark-mode) 'only)
5224 select-active-regions)
5225 (region-active-p)
5226 (display-selections-p))
5227 ;; The var `saved-region-selection', if non-nil, is the text in
5228 ;; the region prior to the last command modifying the buffer.
5229 ;; Set the selection to that, or to the current region.
5230 (cond (saved-region-selection
5231 (if (gui-backend-selection-owner-p 'PRIMARY)
5232 (gui-set-selection 'PRIMARY saved-region-selection))
5233 (setq saved-region-selection nil))
5234 ;; If another program has acquired the selection, region
5235 ;; deactivation should not clobber it (Bug#11772).
5236 ((and (/= (region-beginning) (region-end))
5237 (or (gui-backend-selection-owner-p 'PRIMARY)
5238 (null (gui-backend-selection-exists-p 'PRIMARY))))
5239 (gui-set-selection 'PRIMARY
5240 (funcall region-extract-function nil)))))
5241 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5242 (cond
5243 ((eq (car-safe transient-mark-mode) 'only)
5244 (setq transient-mark-mode (cdr transient-mark-mode))
5245 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5246 (kill-local-variable 'transient-mark-mode)))
5247 ((eq transient-mark-mode 'lambda)
5248 (kill-local-variable 'transient-mark-mode)))
5249 (setq mark-active nil)
5250 (run-hooks 'deactivate-mark-hook)
5251 (redisplay--update-region-highlight (selected-window))))
5253 (defun activate-mark (&optional no-tmm)
5254 "Activate the mark.
5255 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5256 (when (mark t)
5257 (unless (region-active-p)
5258 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5259 (setq mark-active t)
5260 (unless (or transient-mark-mode no-tmm)
5261 (setq-local transient-mark-mode 'lambda))
5262 (run-hooks 'activate-mark-hook))))
5264 (defun set-mark (pos)
5265 "Set this buffer's mark to POS. Don't use this function!
5266 That is to say, don't use this function unless you want
5267 the user to see that the mark has moved, and you want the previous
5268 mark position to be lost.
5270 Normally, when a new mark is set, the old one should go on the stack.
5271 This is why most applications should use `push-mark', not `set-mark'.
5273 Novice Emacs Lisp programmers often try to use the mark for the wrong
5274 purposes. The mark saves a location for the user's convenience.
5275 Most editing commands should not alter the mark.
5276 To remember a location for internal use in the Lisp program,
5277 store it in a Lisp variable. Example:
5279 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5280 (if pos
5281 (progn
5282 (set-marker (mark-marker) pos (current-buffer))
5283 (activate-mark 'no-tmm))
5284 ;; Normally we never clear mark-active except in Transient Mark mode.
5285 ;; But when we actually clear out the mark value too, we must
5286 ;; clear mark-active in any mode.
5287 (deactivate-mark t)
5288 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5289 ;; it should never be nil if the mark is nil.
5290 (setq mark-active nil)
5291 (set-marker (mark-marker) nil)))
5293 (defun save-mark-and-excursion--save ()
5294 (cons
5295 (let ((mark (mark-marker)))
5296 (and (marker-position mark) (copy-marker mark)))
5297 mark-active))
5299 (defun save-mark-and-excursion--restore (saved-mark-info)
5300 (let ((saved-mark (car saved-mark-info))
5301 (omark (marker-position (mark-marker)))
5302 (nmark nil)
5303 (saved-mark-active (cdr saved-mark-info)))
5304 ;; Mark marker
5305 (if (null saved-mark)
5306 (set-marker (mark-marker) nil)
5307 (setf nmark (marker-position saved-mark))
5308 (set-marker (mark-marker) nmark)
5309 (set-marker saved-mark nil))
5310 ;; Mark active
5311 (let ((cur-mark-active mark-active))
5312 (setq mark-active saved-mark-active)
5313 ;; If mark is active now, and either was not active or was at a
5314 ;; different place, run the activate hook.
5315 (if saved-mark-active
5316 (when (or (not cur-mark-active)
5317 (not (eq omark nmark)))
5318 (run-hooks 'activate-mark-hook))
5319 ;; If mark has ceased to be active, run deactivate hook.
5320 (when cur-mark-active
5321 (run-hooks 'deactivate-mark-hook))))))
5323 (defmacro save-mark-and-excursion (&rest body)
5324 "Like `save-excursion', but also save and restore the mark state.
5325 This macro does what `save-excursion' did before Emacs 25.1."
5326 (declare (indent 0) (debug t))
5327 (let ((saved-marker-sym (make-symbol "saved-marker")))
5328 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5329 (unwind-protect
5330 (save-excursion ,@body)
5331 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5333 (defcustom use-empty-active-region nil
5334 "Whether \"region-aware\" commands should act on empty regions.
5335 If nil, region-aware commands treat the empty region as inactive.
5336 If non-nil, region-aware commands treat the region as active as
5337 long as the mark is active, even if the region is empty.
5339 Region-aware commands are those that act on the region if it is
5340 active and Transient Mark mode is enabled, and on the text near
5341 point otherwise."
5342 :type 'boolean
5343 :version "23.1"
5344 :group 'editing-basics)
5346 (defun use-region-p ()
5347 "Return t if the region is active and it is appropriate to act on it.
5348 This is used by commands that act specially on the region under
5349 Transient Mark mode.
5351 The return value is t if Transient Mark mode is enabled and the
5352 mark is active; furthermore, if `use-empty-active-region' is nil,
5353 the region must not be empty. Otherwise, the return value is nil.
5355 For some commands, it may be appropriate to ignore the value of
5356 `use-empty-active-region'; in that case, use `region-active-p'."
5357 (and (region-active-p)
5358 (or use-empty-active-region (> (region-end) (region-beginning)))))
5360 (defun region-active-p ()
5361 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5363 Some commands act specially on the region when Transient Mark
5364 mode is enabled. Usually, such commands should use
5365 `use-region-p' instead of this function, because `use-region-p'
5366 also checks the value of `use-empty-active-region'."
5367 (and transient-mark-mode mark-active
5368 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5369 ;; without the mark being set (e.g. bug#17324). We really should fix
5370 ;; that problem, but in the mean time, let's make sure we don't say the
5371 ;; region is active when there's no mark.
5372 (progn (cl-assert (mark)) t)))
5374 (defun region-noncontiguous-p ()
5375 "Return non-nil if the region contains several pieces.
5376 An example is a rectangular region handled as a list of
5377 separate contiguous regions for each line."
5378 (> (length (funcall region-extract-function 'bounds)) 1))
5380 (defvar redisplay-unhighlight-region-function
5381 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5383 (defvar redisplay-highlight-region-function
5384 (lambda (start end window rol)
5385 (if (not (overlayp rol))
5386 (let ((nrol (make-overlay start end)))
5387 (funcall redisplay-unhighlight-region-function rol)
5388 (overlay-put nrol 'window window)
5389 (overlay-put nrol 'face 'region)
5390 ;; Normal priority so that a large region doesn't hide all the
5391 ;; overlays within it, but high secondary priority so that if it
5392 ;; ends/starts in the middle of a small overlay, that small overlay
5393 ;; won't hide the region's boundaries.
5394 (overlay-put nrol 'priority '(nil . 100))
5395 nrol)
5396 (unless (and (eq (overlay-buffer rol) (current-buffer))
5397 (eq (overlay-start rol) start)
5398 (eq (overlay-end rol) end))
5399 (move-overlay rol start end (current-buffer)))
5400 rol)))
5402 (defun redisplay--update-region-highlight (window)
5403 (let ((rol (window-parameter window 'internal-region-overlay)))
5404 (if (not (and (region-active-p)
5405 (or highlight-nonselected-windows
5406 (eq window (selected-window))
5407 (and (window-minibuffer-p)
5408 (eq window (minibuffer-selected-window))))))
5409 (funcall redisplay-unhighlight-region-function rol)
5410 (let* ((pt (window-point window))
5411 (mark (mark))
5412 (start (min pt mark))
5413 (end (max pt mark))
5414 (new
5415 (funcall redisplay-highlight-region-function
5416 start end window rol)))
5417 (unless (equal new rol)
5418 (set-window-parameter window 'internal-region-overlay
5419 new))))))
5421 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5422 "Hook run just before redisplay.
5423 It is called in each window that is to be redisplayed. It takes one argument,
5424 which is the window that will be redisplayed. When run, the `current-buffer'
5425 is set to the buffer displayed in that window.")
5427 (defun redisplay--pre-redisplay-functions (windows)
5428 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5429 (if (null windows)
5430 (with-current-buffer (window-buffer (selected-window))
5431 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5432 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5433 (with-current-buffer (window-buffer win)
5434 (run-hook-with-args 'pre-redisplay-functions win))))))
5436 (add-function :before pre-redisplay-function
5437 #'redisplay--pre-redisplay-functions)
5440 (defvar-local mark-ring nil
5441 "The list of former marks of the current buffer, most recent first.")
5442 (put 'mark-ring 'permanent-local t)
5444 (defcustom mark-ring-max 16
5445 "Maximum size of mark ring. Start discarding off end if gets this big."
5446 :type 'integer
5447 :group 'editing-basics)
5449 (defvar global-mark-ring nil
5450 "The list of saved global marks, most recent first.")
5452 (defcustom global-mark-ring-max 16
5453 "Maximum size of global mark ring. \
5454 Start discarding off end if gets this big."
5455 :type 'integer
5456 :group 'editing-basics)
5458 (defun pop-to-mark-command ()
5459 "Jump to mark, and pop a new position for mark off the ring.
5460 \(Does not affect global mark ring)."
5461 (interactive)
5462 (if (null (mark t))
5463 (user-error "No mark set in this buffer")
5464 (if (= (point) (mark t))
5465 (message "Mark popped"))
5466 (goto-char (mark t))
5467 (pop-mark)))
5469 (defun push-mark-command (arg &optional nomsg)
5470 "Set mark at where point is.
5471 If no prefix ARG and mark is already set there, just activate it.
5472 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5473 (interactive "P")
5474 (let ((mark (mark t)))
5475 (if (or arg (null mark) (/= mark (point)))
5476 (push-mark nil nomsg t)
5477 (activate-mark 'no-tmm)
5478 (unless nomsg
5479 (message "Mark activated")))))
5481 (defcustom set-mark-command-repeat-pop nil
5482 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5483 That means that C-u \\[set-mark-command] \\[set-mark-command]
5484 will pop the mark twice, and
5485 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5486 will pop the mark three times.
5488 A value of nil means \\[set-mark-command]'s behavior does not change
5489 after C-u \\[set-mark-command]."
5490 :type 'boolean
5491 :group 'editing-basics)
5493 (defun set-mark-command (arg)
5494 "Set the mark where point is, or jump to the mark.
5495 Setting the mark also alters the region, which is the text
5496 between point and mark; this is the closest equivalent in
5497 Emacs to what some editors call the \"selection\".
5499 With no prefix argument, set the mark at point, and push the
5500 old mark position on local mark ring. Also push the old mark on
5501 global mark ring, if the previous mark was set in another buffer.
5503 When Transient Mark Mode is off, immediately repeating this
5504 command activates `transient-mark-mode' temporarily.
5506 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5507 jump to the mark, and set the mark from
5508 position popped off the local mark ring (this does not affect the global
5509 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5510 mark ring (see `pop-global-mark').
5512 If `set-mark-command-repeat-pop' is non-nil, repeating
5513 the \\[set-mark-command] command with no prefix argument pops the next position
5514 off the local (or global) mark ring and jumps there.
5516 With \\[universal-argument] \\[universal-argument] as prefix
5517 argument, unconditionally set mark where point is, even if
5518 `set-mark-command-repeat-pop' is non-nil.
5520 Novice Emacs Lisp programmers often try to use the mark for the wrong
5521 purposes. See the documentation of `set-mark' for more information."
5522 (interactive "P")
5523 (cond ((eq transient-mark-mode 'lambda)
5524 (kill-local-variable 'transient-mark-mode))
5525 ((eq (car-safe transient-mark-mode) 'only)
5526 (deactivate-mark)))
5527 (cond
5528 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5529 (push-mark-command nil))
5530 ((not (eq this-command 'set-mark-command))
5531 (if arg
5532 (pop-to-mark-command)
5533 (push-mark-command t)))
5534 ((and set-mark-command-repeat-pop
5535 (eq last-command 'pop-global-mark)
5536 (not arg))
5537 (setq this-command 'pop-global-mark)
5538 (pop-global-mark))
5539 ((or (and set-mark-command-repeat-pop
5540 (eq last-command 'pop-to-mark-command))
5541 arg)
5542 (setq this-command 'pop-to-mark-command)
5543 (pop-to-mark-command))
5544 ((eq last-command 'set-mark-command)
5545 (if (region-active-p)
5546 (progn
5547 (deactivate-mark)
5548 (message "Mark deactivated"))
5549 (activate-mark)
5550 (message "Mark activated")))
5552 (push-mark-command nil))))
5554 (defun push-mark (&optional location nomsg activate)
5555 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5556 If the last global mark pushed was not in the current buffer,
5557 also push LOCATION on the global mark ring.
5558 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5560 Novice Emacs Lisp programmers often try to use the mark for the wrong
5561 purposes. See the documentation of `set-mark' for more information.
5563 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5564 (unless (null (mark t))
5565 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5566 (when (> (length mark-ring) mark-ring-max)
5567 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5568 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5569 (set-marker (mark-marker) (or location (point)) (current-buffer))
5570 ;; Now push the mark on the global mark ring.
5571 (if (and global-mark-ring
5572 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5573 ;; The last global mark pushed was in this same buffer.
5574 ;; Don't push another one.
5576 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5577 (when (> (length global-mark-ring) global-mark-ring-max)
5578 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5579 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5580 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5581 (message "Mark set"))
5582 (if (or activate (not transient-mark-mode))
5583 (set-mark (mark t)))
5584 nil)
5586 (defun pop-mark ()
5587 "Pop off mark ring into the buffer's actual mark.
5588 Does not set point. Does nothing if mark ring is empty."
5589 (when mark-ring
5590 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5591 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5592 (move-marker (car mark-ring) nil)
5593 (if (null (mark t)) (ding))
5594 (setq mark-ring (cdr mark-ring)))
5595 (deactivate-mark))
5597 (define-obsolete-function-alias
5598 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5599 (defun exchange-point-and-mark (&optional arg)
5600 "Put the mark where point is now, and point where the mark is now.
5601 This command works even when the mark is not active,
5602 and it reactivates the mark.
5604 If Transient Mark mode is on, a prefix ARG deactivates the mark
5605 if it is active, and otherwise avoids reactivating it. If
5606 Transient Mark mode is off, a prefix ARG enables Transient Mark
5607 mode temporarily."
5608 (interactive "P")
5609 (let ((omark (mark t))
5610 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5611 (if (null omark)
5612 (user-error "No mark set in this buffer"))
5613 (set-mark (point))
5614 (goto-char omark)
5615 (cond (temp-highlight
5616 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5617 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5618 (not (or arg (region-active-p))))
5619 (deactivate-mark))
5620 (t (activate-mark)))
5621 nil))
5623 (defcustom shift-select-mode t
5624 "When non-nil, shifted motion keys activate the mark momentarily.
5626 While the mark is activated in this way, any shift-translated point
5627 motion key extends the region, and if Transient Mark mode was off, it
5628 is temporarily turned on. Furthermore, the mark will be deactivated
5629 by any subsequent point motion key that was not shift-translated, or
5630 by any action that normally deactivates the mark in Transient Mark mode.
5632 See `this-command-keys-shift-translated' for the meaning of
5633 shift-translation."
5634 :type 'boolean
5635 :group 'editing-basics)
5637 (defun handle-shift-selection ()
5638 "Activate/deactivate mark depending on invocation thru shift translation.
5639 This function is called by `call-interactively' when a command
5640 with a `^' character in its `interactive' spec is invoked, before
5641 running the command itself.
5643 If `shift-select-mode' is enabled and the command was invoked
5644 through shift translation, set the mark and activate the region
5645 temporarily, unless it was already set in this way. See
5646 `this-command-keys-shift-translated' for the meaning of shift
5647 translation.
5649 Otherwise, if the region has been activated temporarily,
5650 deactivate it, and restore the variable `transient-mark-mode' to
5651 its earlier value."
5652 (cond ((and shift-select-mode this-command-keys-shift-translated)
5653 (unless (and mark-active
5654 (eq (car-safe transient-mark-mode) 'only))
5655 (setq-local transient-mark-mode
5656 (cons 'only
5657 (unless (eq transient-mark-mode 'lambda)
5658 transient-mark-mode)))
5659 (push-mark nil nil t)))
5660 ((eq (car-safe transient-mark-mode) 'only)
5661 (setq transient-mark-mode (cdr transient-mark-mode))
5662 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5663 (kill-local-variable 'transient-mark-mode))
5664 (deactivate-mark))))
5666 (define-minor-mode transient-mark-mode
5667 "Toggle Transient Mark mode.
5668 With a prefix argument ARG, enable Transient Mark mode if ARG is
5669 positive, and disable it otherwise. If called from Lisp, enable
5670 Transient Mark mode if ARG is omitted or nil.
5672 Transient Mark mode is a global minor mode. When enabled, the
5673 region is highlighted with the `region' face whenever the mark
5674 is active. The mark is \"deactivated\" by changing the buffer,
5675 and after certain other operations that set the mark but whose
5676 main purpose is something else--for example, incremental search,
5677 \\[beginning-of-buffer], and \\[end-of-buffer].
5679 You can also deactivate the mark by typing \\[keyboard-quit] or
5680 \\[keyboard-escape-quit].
5682 Many commands change their behavior when Transient Mark mode is
5683 in effect and the mark is active, by acting on the region instead
5684 of their usual default part of the buffer's text. Examples of
5685 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5686 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5687 To see the documentation of commands which are sensitive to the
5688 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5689 or \"mark.*active\" at the prompt."
5690 :global t
5691 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5692 :variable (default-value 'transient-mark-mode))
5694 (defvar widen-automatically t
5695 "Non-nil means it is ok for commands to call `widen' when they want to.
5696 Some commands will do this in order to go to positions outside
5697 the current accessible part of the buffer.
5699 If `widen-automatically' is nil, these commands will do something else
5700 as a fallback, and won't change the buffer bounds.")
5702 (defvar non-essential nil
5703 "Whether the currently executing code is performing an essential task.
5704 This variable should be non-nil only when running code which should not
5705 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5706 user for a password when we are simply scanning a set of files in the
5707 background or displaying possible completions before the user even asked
5708 for it.")
5710 (defun pop-global-mark ()
5711 "Pop off global mark ring and jump to the top location."
5712 (interactive)
5713 ;; Pop entries which refer to non-existent buffers.
5714 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5715 (setq global-mark-ring (cdr global-mark-ring)))
5716 (or global-mark-ring
5717 (error "No global mark set"))
5718 (let* ((marker (car global-mark-ring))
5719 (buffer (marker-buffer marker))
5720 (position (marker-position marker)))
5721 (setq global-mark-ring (nconc (cdr global-mark-ring)
5722 (list (car global-mark-ring))))
5723 (set-buffer buffer)
5724 (or (and (>= position (point-min))
5725 (<= position (point-max)))
5726 (if widen-automatically
5727 (widen)
5728 (error "Global mark position is outside accessible part of buffer")))
5729 (goto-char position)
5730 (switch-to-buffer buffer)))
5732 (defcustom next-line-add-newlines nil
5733 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5734 :type 'boolean
5735 :version "21.1"
5736 :group 'editing-basics)
5738 (defun next-line (&optional arg try-vscroll)
5739 "Move cursor vertically down ARG lines.
5740 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5741 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5742 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5743 function will not vscroll.
5745 ARG defaults to 1.
5747 If there is no character in the target line exactly under the current column,
5748 the cursor is positioned after the character in that line which spans this
5749 column, or at the end of the line if it is not long enough.
5750 If there is no line in the buffer after this one, behavior depends on the
5751 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5752 to create a line, and moves the cursor to that line. Otherwise it moves the
5753 cursor to the end of the buffer.
5755 If the variable `line-move-visual' is non-nil, this command moves
5756 by display lines. Otherwise, it moves by buffer lines, without
5757 taking variable-width characters or continued lines into account.
5759 The command \\[set-goal-column] can be used to create
5760 a semipermanent goal column for this command.
5761 Then instead of trying to move exactly vertically (or as close as possible),
5762 this command moves to the specified goal column (or as close as possible).
5763 The goal column is stored in the variable `goal-column', which is nil
5764 when there is no goal column. Note that setting `goal-column'
5765 overrides `line-move-visual' and causes this command to move by buffer
5766 lines rather than by display lines."
5767 (declare (interactive-only forward-line))
5768 (interactive "^p\np")
5769 (or arg (setq arg 1))
5770 (if (and next-line-add-newlines (= arg 1))
5771 (if (save-excursion (end-of-line) (eobp))
5772 ;; When adding a newline, don't expand an abbrev.
5773 (let ((abbrev-mode nil))
5774 (end-of-line)
5775 (insert (if use-hard-newlines hard-newline "\n")))
5776 (line-move arg nil nil try-vscroll))
5777 (if (called-interactively-p 'interactive)
5778 (condition-case err
5779 (line-move arg nil nil try-vscroll)
5780 ((beginning-of-buffer end-of-buffer)
5781 (signal (car err) (cdr err))))
5782 (line-move arg nil nil try-vscroll)))
5783 nil)
5785 (defun previous-line (&optional arg try-vscroll)
5786 "Move cursor vertically up ARG lines.
5787 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5788 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5789 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5790 function will not vscroll.
5792 ARG defaults to 1.
5794 If there is no character in the target line exactly over the current column,
5795 the cursor is positioned after the character in that line which spans this
5796 column, or at the end of the line if it is not long enough.
5798 If the variable `line-move-visual' is non-nil, this command moves
5799 by display lines. Otherwise, it moves by buffer lines, without
5800 taking variable-width characters or continued lines into account.
5802 The command \\[set-goal-column] can be used to create
5803 a semipermanent goal column for this command.
5804 Then instead of trying to move exactly vertically (or as close as possible),
5805 this command moves to the specified goal column (or as close as possible).
5806 The goal column is stored in the variable `goal-column', which is nil
5807 when there is no goal column. Note that setting `goal-column'
5808 overrides `line-move-visual' and causes this command to move by buffer
5809 lines rather than by display lines."
5810 (declare (interactive-only
5811 "use `forward-line' with negative argument instead."))
5812 (interactive "^p\np")
5813 (or arg (setq arg 1))
5814 (if (called-interactively-p 'interactive)
5815 (condition-case err
5816 (line-move (- arg) nil nil try-vscroll)
5817 ((beginning-of-buffer end-of-buffer)
5818 (signal (car err) (cdr err))))
5819 (line-move (- arg) nil nil try-vscroll))
5820 nil)
5822 (defcustom track-eol nil
5823 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5824 This means moving to the end of each line moved onto.
5825 The beginning of a blank line does not count as the end of a line.
5826 This has no effect when the variable `line-move-visual' is non-nil."
5827 :type 'boolean
5828 :group 'editing-basics)
5830 (defcustom goal-column nil
5831 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5832 A non-nil setting overrides the variable `line-move-visual', which see."
5833 :type '(choice integer
5834 (const :tag "None" nil))
5835 :group 'editing-basics)
5836 (make-variable-buffer-local 'goal-column)
5838 (defvar temporary-goal-column 0
5839 "Current goal column for vertical motion.
5840 It is the column where point was at the start of the current run
5841 of vertical motion commands.
5843 When moving by visual lines via the function `line-move-visual', it is a cons
5844 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5845 divided by the default column width, and HSCROLL is the number of
5846 columns by which window is scrolled from left margin.
5848 When the `track-eol' feature is doing its job, the value is
5849 `most-positive-fixnum'.")
5851 (defcustom line-move-ignore-invisible t
5852 "Non-nil means commands that move by lines ignore invisible newlines.
5853 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5854 as if newlines that are invisible didn't exist, and count
5855 only visible newlines. Thus, moving across across 2 newlines
5856 one of which is invisible will be counted as a one-line move.
5857 Also, a non-nil value causes invisible text to be ignored when
5858 counting columns for the purposes of keeping point in the same
5859 column by \\[next-line] and \\[previous-line].
5861 Outline mode sets this."
5862 :type 'boolean
5863 :group 'editing-basics)
5865 (defcustom line-move-visual t
5866 "When non-nil, `line-move' moves point by visual lines.
5867 This movement is based on where the cursor is displayed on the
5868 screen, instead of relying on buffer contents alone. It takes
5869 into account variable-width characters and line continuation.
5870 If nil, `line-move' moves point by logical lines.
5871 A non-nil setting of `goal-column' overrides the value of this variable
5872 and forces movement by logical lines.
5873 A window that is horizontally scrolled also forces movement by logical
5874 lines."
5875 :type 'boolean
5876 :group 'editing-basics
5877 :version "23.1")
5879 ;; Only used if display-graphic-p.
5880 (declare-function font-info "font.c" (name &optional frame))
5882 (defun default-font-height ()
5883 "Return the height in pixels of the current buffer's default face font.
5885 If the default font is remapped (see `face-remapping-alist'), the
5886 function returns the height of the remapped face."
5887 (let ((default-font (face-font 'default)))
5888 (cond
5889 ((and (display-multi-font-p)
5890 ;; Avoid calling font-info if the frame's default font was
5891 ;; not changed since the frame was created. That's because
5892 ;; font-info is expensive for some fonts, see bug #14838.
5893 (not (string= (frame-parameter nil 'font) default-font)))
5894 (aref (font-info default-font) 3))
5895 (t (frame-char-height)))))
5897 (defun default-font-width ()
5898 "Return the width in pixels of the current buffer's default face font.
5900 If the default font is remapped (see `face-remapping-alist'), the
5901 function returns the width of the remapped face."
5902 (let ((default-font (face-font 'default)))
5903 (cond
5904 ((and (display-multi-font-p)
5905 ;; Avoid calling font-info if the frame's default font was
5906 ;; not changed since the frame was created. That's because
5907 ;; font-info is expensive for some fonts, see bug #14838.
5908 (not (string= (frame-parameter nil 'font) default-font)))
5909 (let* ((info (font-info (face-font 'default)))
5910 (width (aref info 11)))
5911 (if (> width 0)
5912 width
5913 (aref info 10))))
5914 (t (frame-char-width)))))
5916 (defun default-line-height ()
5917 "Return the pixel height of current buffer's default-face text line.
5919 The value includes `line-spacing', if any, defined for the buffer
5920 or the frame."
5921 (let ((dfh (default-font-height))
5922 (lsp (if (display-graphic-p)
5923 (or line-spacing
5924 (default-value 'line-spacing)
5925 (frame-parameter nil 'line-spacing)
5927 0)))
5928 (if (floatp lsp)
5929 (setq lsp (truncate (* (frame-char-height) lsp))))
5930 (+ dfh lsp)))
5932 (defun window-screen-lines ()
5933 "Return the number of screen lines in the text area of the selected window.
5935 This is different from `window-text-height' in that this function counts
5936 lines in units of the height of the font used by the default face displayed
5937 in the window, not in units of the frame's default font, and also accounts
5938 for `line-spacing', if any, defined for the window's buffer or frame.
5940 The value is a floating-point number."
5941 (let ((edges (window-inside-pixel-edges))
5942 (dlh (default-line-height)))
5943 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5945 ;; Returns non-nil if partial move was done.
5946 (defun line-move-partial (arg noerror &optional _to-end)
5947 (if (< arg 0)
5948 ;; Move backward (up).
5949 ;; If already vscrolled, reduce vscroll
5950 (let ((vs (window-vscroll nil t))
5951 (dlh (default-line-height)))
5952 (when (> vs dlh)
5953 (set-window-vscroll nil (- vs dlh) t)))
5955 ;; Move forward (down).
5956 (let* ((lh (window-line-height -1))
5957 (rowh (car lh))
5958 (vpos (nth 1 lh))
5959 (ypos (nth 2 lh))
5960 (rbot (nth 3 lh))
5961 (this-lh (window-line-height))
5962 (this-height (car this-lh))
5963 (this-ypos (nth 2 this-lh))
5964 (dlh (default-line-height))
5965 (wslines (window-screen-lines))
5966 (edges (window-inside-pixel-edges))
5967 (winh (- (nth 3 edges) (nth 1 edges) 1))
5968 py vs last-line)
5969 (if (> (mod wslines 1.0) 0.0)
5970 (setq wslines (round (+ wslines 0.5))))
5971 (when (or (null lh)
5972 (>= rbot dlh)
5973 (<= ypos (- dlh))
5974 (null this-lh)
5975 (<= this-ypos (- dlh)))
5976 (unless lh
5977 (let ((wend (pos-visible-in-window-p t nil t)))
5978 (setq rbot (nth 3 wend)
5979 rowh (nth 4 wend)
5980 vpos (nth 5 wend))))
5981 (unless this-lh
5982 (let ((wstart (pos-visible-in-window-p nil nil t)))
5983 (setq this-ypos (nth 2 wstart)
5984 this-height (nth 4 wstart))))
5985 (setq py
5986 (or (nth 1 this-lh)
5987 (let ((ppos (posn-at-point))
5988 col-row)
5989 (setq col-row (posn-actual-col-row ppos))
5990 (if col-row
5991 (- (cdr col-row) (window-vscroll))
5992 (cdr (posn-col-row ppos))))))
5993 ;; VPOS > 0 means the last line is only partially visible.
5994 ;; But if the part that is visible is at least as tall as the
5995 ;; default font, that means the line is actually fully
5996 ;; readable, and something like line-spacing is hidden. So in
5997 ;; that case we accept the last line in the window as still
5998 ;; visible, and consider the margin as starting one line
5999 ;; later.
6000 (if (and vpos (> vpos 0))
6001 (if (and rowh
6002 (>= rowh (default-font-height))
6003 (< rowh dlh))
6004 (setq last-line (min (- wslines scroll-margin) vpos))
6005 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6006 (cond
6007 ;; If last line of window is fully visible, and vscrolling
6008 ;; more would make this line invisible, move forward.
6009 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6010 (null this-height)
6011 (<= this-height dlh))
6012 (or (null rbot) (= rbot 0)))
6013 nil)
6014 ;; If cursor is not in the bottom scroll margin, and the
6015 ;; current line is is not too tall, move forward.
6016 ((and (or (null this-height) (<= this-height winh))
6017 vpos
6018 (> vpos 0)
6019 (< py last-line))
6020 nil)
6021 ;; When already vscrolled, we vscroll some more if we can,
6022 ;; or clear vscroll and move forward at end of tall image.
6023 ((> vs 0)
6024 (when (or (and rbot (> rbot 0))
6025 (and this-height (> this-height dlh)))
6026 (set-window-vscroll nil (+ vs dlh) t)))
6027 ;; If cursor just entered the bottom scroll margin, move forward,
6028 ;; but also optionally vscroll one line so redisplay won't recenter.
6029 ((and vpos
6030 (> vpos 0)
6031 (= py last-line))
6032 ;; Don't vscroll if the partially-visible line at window
6033 ;; bottom is not too tall (a.k.a. "just one more text
6034 ;; line"): in that case, we do want redisplay to behave
6035 ;; normally, i.e. recenter or whatever.
6037 ;; Note: ROWH + RBOT from the value returned by
6038 ;; pos-visible-in-window-p give the total height of the
6039 ;; partially-visible glyph row at the end of the window. As
6040 ;; we are dealing with floats, we disregard sub-pixel
6041 ;; discrepancies between that and DLH.
6042 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6043 (set-window-vscroll nil dlh t))
6044 (line-move-1 arg noerror)
6046 ;; If there are lines above the last line, scroll-up one line.
6047 ((and vpos (> vpos 0))
6048 (scroll-up 1)
6050 ;; Finally, start vscroll.
6052 (set-window-vscroll nil dlh t)))))))
6055 ;; This is like line-move-1 except that it also performs
6056 ;; vertical scrolling of tall images if appropriate.
6057 ;; That is not really a clean thing to do, since it mixes
6058 ;; scrolling with cursor motion. But so far we don't have
6059 ;; a cleaner solution to the problem of making C-n do something
6060 ;; useful given a tall image.
6061 (defun line-move (arg &optional noerror _to-end try-vscroll)
6062 "Move forward ARG lines.
6063 If NOERROR, don't signal an error if we can't move ARG lines.
6064 TO-END is unused.
6065 TRY-VSCROLL controls whether to vscroll tall lines: if either
6066 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6067 not vscroll."
6068 (if noninteractive
6069 (line-move-1 arg noerror)
6070 (unless (and auto-window-vscroll try-vscroll
6071 ;; Only vscroll for single line moves
6072 (= (abs arg) 1)
6073 ;; Under scroll-conservatively, the display engine
6074 ;; does this better.
6075 (zerop scroll-conservatively)
6076 ;; But don't vscroll in a keyboard macro.
6077 (not defining-kbd-macro)
6078 (not executing-kbd-macro)
6079 (line-move-partial arg noerror))
6080 (set-window-vscroll nil 0 t)
6081 (if (and line-move-visual
6082 ;; Display-based column are incompatible with goal-column.
6083 (not goal-column)
6084 ;; When the text in the window is scrolled to the left,
6085 ;; display-based motion doesn't make sense (because each
6086 ;; logical line occupies exactly one screen line).
6087 (not (> (window-hscroll) 0))
6088 ;; Likewise when the text _was_ scrolled to the left
6089 ;; when the current run of vertical motion commands
6090 ;; started.
6091 (not (and (memq last-command
6092 `(next-line previous-line ,this-command))
6093 auto-hscroll-mode
6094 (numberp temporary-goal-column)
6095 (>= temporary-goal-column
6096 (- (window-width) hscroll-margin)))))
6097 (prog1 (line-move-visual arg noerror)
6098 ;; If we moved into a tall line, set vscroll to make
6099 ;; scrolling through tall images more smooth.
6100 (let ((lh (line-pixel-height))
6101 (edges (window-inside-pixel-edges))
6102 (dlh (default-line-height))
6103 winh)
6104 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6105 (if (and (< arg 0)
6106 (< (point) (window-start))
6107 (> lh winh))
6108 (set-window-vscroll
6110 (- lh dlh) t))))
6111 (line-move-1 arg noerror)))))
6113 ;; Display-based alternative to line-move-1.
6114 ;; Arg says how many lines to move. The value is t if we can move the
6115 ;; specified number of lines.
6116 (defun line-move-visual (arg &optional noerror)
6117 "Move ARG lines forward.
6118 If NOERROR, don't signal an error if we can't move that many lines."
6119 (let ((opoint (point))
6120 (hscroll (window-hscroll))
6121 target-hscroll)
6122 ;; Check if the previous command was a line-motion command, or if
6123 ;; we were called from some other command.
6124 (if (and (consp temporary-goal-column)
6125 (memq last-command `(next-line previous-line ,this-command)))
6126 ;; If so, there's no need to reset `temporary-goal-column',
6127 ;; but we may need to hscroll.
6128 (if (or (/= (cdr temporary-goal-column) hscroll)
6129 (> (cdr temporary-goal-column) 0))
6130 (setq target-hscroll (cdr temporary-goal-column)))
6131 ;; Otherwise, we should reset `temporary-goal-column'.
6132 (let ((posn (posn-at-point))
6133 x-pos)
6134 (cond
6135 ;; Handle the `overflow-newline-into-fringe' case:
6136 ((eq (nth 1 posn) 'right-fringe)
6137 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6138 ((car (posn-x-y posn))
6139 (setq x-pos (car (posn-x-y posn)))
6140 ;; In R2L lines, the X pixel coordinate is measured from the
6141 ;; left edge of the window, but columns are still counted
6142 ;; from the logical-order beginning of the line, i.e. from
6143 ;; the right edge in this case. We need to adjust for that.
6144 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6145 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6146 (setq temporary-goal-column
6147 (cons (/ (float x-pos)
6148 (frame-char-width))
6149 hscroll)))
6150 (executing-kbd-macro
6151 ;; When we move beyond the first/last character visible in
6152 ;; the window, posn-at-point will return nil, so we need to
6153 ;; approximate the goal column as below.
6154 (setq temporary-goal-column
6155 (mod (current-column) (window-text-width)))))))
6156 (if target-hscroll
6157 (set-window-hscroll (selected-window) target-hscroll))
6158 ;; vertical-motion can move more than it was asked to if it moves
6159 ;; across display strings with newlines. We don't want to ring
6160 ;; the bell and announce beginning/end of buffer in that case.
6161 (or (and (or (and (>= arg 0)
6162 (>= (vertical-motion
6163 (cons (or goal-column
6164 (if (consp temporary-goal-column)
6165 (car temporary-goal-column)
6166 temporary-goal-column))
6167 arg))
6168 arg))
6169 (and (< arg 0)
6170 (<= (vertical-motion
6171 (cons (or goal-column
6172 (if (consp temporary-goal-column)
6173 (car temporary-goal-column)
6174 temporary-goal-column))
6175 arg))
6176 arg)))
6177 (or (>= arg 0)
6178 (/= (point) opoint)
6179 ;; If the goal column lies on a display string,
6180 ;; `vertical-motion' advances the cursor to the end
6181 ;; of the string. For arg < 0, this can cause the
6182 ;; cursor to get stuck. (Bug#3020).
6183 (= (vertical-motion arg) arg)))
6184 (unless noerror
6185 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6186 nil)))))
6188 ;; This is the guts of next-line and previous-line.
6189 ;; Arg says how many lines to move.
6190 ;; The value is t if we can move the specified number of lines.
6191 (defun line-move-1 (arg &optional noerror _to-end)
6192 ;; Don't run any point-motion hooks, and disregard intangibility,
6193 ;; for intermediate positions.
6194 (let ((inhibit-point-motion-hooks t)
6195 (opoint (point))
6196 (orig-arg arg))
6197 (if (consp temporary-goal-column)
6198 (setq temporary-goal-column (+ (car temporary-goal-column)
6199 (cdr temporary-goal-column))))
6200 (unwind-protect
6201 (progn
6202 (if (not (memq last-command '(next-line previous-line)))
6203 (setq temporary-goal-column
6204 (if (and track-eol (eolp)
6205 ;; Don't count beg of empty line as end of line
6206 ;; unless we just did explicit end-of-line.
6207 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6208 most-positive-fixnum
6209 (current-column))))
6211 (if (not (or (integerp selective-display)
6212 line-move-ignore-invisible))
6213 ;; Use just newline characters.
6214 ;; Set ARG to 0 if we move as many lines as requested.
6215 (or (if (> arg 0)
6216 (progn (if (> arg 1) (forward-line (1- arg)))
6217 ;; This way of moving forward ARG lines
6218 ;; verifies that we have a newline after the last one.
6219 ;; It doesn't get confused by intangible text.
6220 (end-of-line)
6221 (if (zerop (forward-line 1))
6222 (setq arg 0)))
6223 (and (zerop (forward-line arg))
6224 (bolp)
6225 (setq arg 0)))
6226 (unless noerror
6227 (signal (if (< arg 0)
6228 'beginning-of-buffer
6229 'end-of-buffer)
6230 nil)))
6231 ;; Move by arg lines, but ignore invisible ones.
6232 (let (done)
6233 (while (and (> arg 0) (not done))
6234 ;; If the following character is currently invisible,
6235 ;; skip all characters with that same `invisible' property value.
6236 (while (and (not (eobp)) (invisible-p (point)))
6237 (goto-char (next-char-property-change (point))))
6238 ;; Move a line.
6239 ;; We don't use `end-of-line', since we want to escape
6240 ;; from field boundaries occurring exactly at point.
6241 (goto-char (constrain-to-field
6242 (let ((inhibit-field-text-motion t))
6243 (line-end-position))
6244 (point) t t
6245 'inhibit-line-move-field-capture))
6246 ;; If there's no invisibility here, move over the newline.
6247 (cond
6248 ((eobp)
6249 (if (not noerror)
6250 (signal 'end-of-buffer nil)
6251 (setq done t)))
6252 ((and (> arg 1) ;; Use vertical-motion for last move
6253 (not (integerp selective-display))
6254 (not (invisible-p (point))))
6255 ;; We avoid vertical-motion when possible
6256 ;; because that has to fontify.
6257 (forward-line 1))
6258 ;; Otherwise move a more sophisticated way.
6259 ((zerop (vertical-motion 1))
6260 (if (not noerror)
6261 (signal 'end-of-buffer nil)
6262 (setq done t))))
6263 (unless done
6264 (setq arg (1- arg))))
6265 ;; The logic of this is the same as the loop above,
6266 ;; it just goes in the other direction.
6267 (while (and (< arg 0) (not done))
6268 ;; For completely consistency with the forward-motion
6269 ;; case, we should call beginning-of-line here.
6270 ;; However, if point is inside a field and on a
6271 ;; continued line, the call to (vertical-motion -1)
6272 ;; below won't move us back far enough; then we return
6273 ;; to the same column in line-move-finish, and point
6274 ;; gets stuck -- cyd
6275 (forward-line 0)
6276 (cond
6277 ((bobp)
6278 (if (not noerror)
6279 (signal 'beginning-of-buffer nil)
6280 (setq done t)))
6281 ((and (< arg -1) ;; Use vertical-motion for last move
6282 (not (integerp selective-display))
6283 (not (invisible-p (1- (point)))))
6284 (forward-line -1))
6285 ((zerop (vertical-motion -1))
6286 (if (not noerror)
6287 (signal 'beginning-of-buffer nil)
6288 (setq done t))))
6289 (unless done
6290 (setq arg (1+ arg))
6291 (while (and ;; Don't move over previous invis lines
6292 ;; if our target is the middle of this line.
6293 (or (zerop (or goal-column temporary-goal-column))
6294 (< arg 0))
6295 (not (bobp)) (invisible-p (1- (point))))
6296 (goto-char (previous-char-property-change (point))))))))
6297 ;; This is the value the function returns.
6298 (= arg 0))
6300 (cond ((> arg 0)
6301 ;; If we did not move down as far as desired, at least go
6302 ;; to end of line. Be sure to call point-entered and
6303 ;; point-left-hooks.
6304 (let* ((npoint (prog1 (line-end-position)
6305 (goto-char opoint)))
6306 (inhibit-point-motion-hooks nil))
6307 (goto-char npoint)))
6308 ((< arg 0)
6309 ;; If we did not move up as far as desired,
6310 ;; at least go to beginning of line.
6311 (let* ((npoint (prog1 (line-beginning-position)
6312 (goto-char opoint)))
6313 (inhibit-point-motion-hooks nil))
6314 (goto-char npoint)))
6316 (line-move-finish (or goal-column temporary-goal-column)
6317 opoint (> orig-arg 0)))))))
6319 (defun line-move-finish (column opoint forward)
6320 (let ((repeat t))
6321 (while repeat
6322 ;; Set REPEAT to t to repeat the whole thing.
6323 (setq repeat nil)
6325 (let (new
6326 (old (point))
6327 (line-beg (line-beginning-position))
6328 (line-end
6329 ;; Compute the end of the line
6330 ;; ignoring effectively invisible newlines.
6331 (save-excursion
6332 ;; Like end-of-line but ignores fields.
6333 (skip-chars-forward "^\n")
6334 (while (and (not (eobp)) (invisible-p (point)))
6335 (goto-char (next-char-property-change (point)))
6336 (skip-chars-forward "^\n"))
6337 (point))))
6339 ;; Move to the desired column.
6340 (line-move-to-column (truncate column))
6342 ;; Corner case: suppose we start out in a field boundary in
6343 ;; the middle of a continued line. When we get to
6344 ;; line-move-finish, point is at the start of a new *screen*
6345 ;; line but the same text line; then line-move-to-column would
6346 ;; move us backwards. Test using C-n with point on the "x" in
6347 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6348 (and forward
6349 (< (point) old)
6350 (goto-char old))
6352 (setq new (point))
6354 ;; Process intangibility within a line.
6355 ;; With inhibit-point-motion-hooks bound to nil, a call to
6356 ;; goto-char moves point past intangible text.
6358 ;; However, inhibit-point-motion-hooks controls both the
6359 ;; intangibility and the point-entered/point-left hooks. The
6360 ;; following hack avoids calling the point-* hooks
6361 ;; unnecessarily. Note that we move *forward* past intangible
6362 ;; text when the initial and final points are the same.
6363 (goto-char new)
6364 (let ((inhibit-point-motion-hooks nil))
6365 (goto-char new)
6367 ;; If intangibility moves us to a different (later) place
6368 ;; in the same line, use that as the destination.
6369 (if (<= (point) line-end)
6370 (setq new (point))
6371 ;; If that position is "too late",
6372 ;; try the previous allowable position.
6373 ;; See if it is ok.
6374 (backward-char)
6375 (if (if forward
6376 ;; If going forward, don't accept the previous
6377 ;; allowable position if it is before the target line.
6378 (< line-beg (point))
6379 ;; If going backward, don't accept the previous
6380 ;; allowable position if it is still after the target line.
6381 (<= (point) line-end))
6382 (setq new (point))
6383 ;; As a last resort, use the end of the line.
6384 (setq new line-end))))
6386 ;; Now move to the updated destination, processing fields
6387 ;; as well as intangibility.
6388 (goto-char opoint)
6389 (let ((inhibit-point-motion-hooks nil))
6390 (goto-char
6391 ;; Ignore field boundaries if the initial and final
6392 ;; positions have the same `field' property, even if the
6393 ;; fields are non-contiguous. This seems to be "nicer"
6394 ;; behavior in many situations.
6395 (if (eq (get-char-property new 'field)
6396 (get-char-property opoint 'field))
6398 (constrain-to-field new opoint t t
6399 'inhibit-line-move-field-capture))))
6401 ;; If all this moved us to a different line,
6402 ;; retry everything within that new line.
6403 (when (or (< (point) line-beg) (> (point) line-end))
6404 ;; Repeat the intangibility and field processing.
6405 (setq repeat t))))))
6407 (defun line-move-to-column (col)
6408 "Try to find column COL, considering invisibility.
6409 This function works only in certain cases,
6410 because what we really need is for `move-to-column'
6411 and `current-column' to be able to ignore invisible text."
6412 (if (zerop col)
6413 (beginning-of-line)
6414 (move-to-column col))
6416 (when (and line-move-ignore-invisible
6417 (not (bolp)) (invisible-p (1- (point))))
6418 (let ((normal-location (point))
6419 (normal-column (current-column)))
6420 ;; If the following character is currently invisible,
6421 ;; skip all characters with that same `invisible' property value.
6422 (while (and (not (eobp))
6423 (invisible-p (point)))
6424 (goto-char (next-char-property-change (point))))
6425 ;; Have we advanced to a larger column position?
6426 (if (> (current-column) normal-column)
6427 ;; We have made some progress towards the desired column.
6428 ;; See if we can make any further progress.
6429 (line-move-to-column (+ (current-column) (- col normal-column)))
6430 ;; Otherwise, go to the place we originally found
6431 ;; and move back over invisible text.
6432 ;; that will get us to the same place on the screen
6433 ;; but with a more reasonable buffer position.
6434 (goto-char normal-location)
6435 (let ((line-beg
6436 ;; We want the real line beginning, so it's consistent
6437 ;; with bolp below, otherwise we might infloop.
6438 (let ((inhibit-field-text-motion t))
6439 (line-beginning-position))))
6440 (while (and (not (bolp)) (invisible-p (1- (point))))
6441 (goto-char (previous-char-property-change (point) line-beg))))))))
6443 (defun move-end-of-line (arg)
6444 "Move point to end of current line as displayed.
6445 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6446 If point reaches the beginning or end of buffer, it stops there.
6448 To ignore the effects of the `intangible' text or overlay
6449 property, bind `inhibit-point-motion-hooks' to t.
6450 If there is an image in the current line, this function
6451 disregards newlines that are part of the text on which the image
6452 rests."
6453 (interactive "^p")
6454 (or arg (setq arg 1))
6455 (let (done)
6456 (while (not done)
6457 (let ((newpos
6458 (save-excursion
6459 (let ((goal-column 0)
6460 (line-move-visual nil))
6461 (and (line-move arg t)
6462 ;; With bidi reordering, we may not be at bol,
6463 ;; so make sure we are.
6464 (skip-chars-backward "^\n")
6465 (not (bobp))
6466 (progn
6467 (while (and (not (bobp)) (invisible-p (1- (point))))
6468 (goto-char (previous-single-char-property-change
6469 (point) 'invisible)))
6470 (backward-char 1)))
6471 (point)))))
6472 (goto-char newpos)
6473 (if (and (> (point) newpos)
6474 (eq (preceding-char) ?\n))
6475 (backward-char 1)
6476 (if (and (> (point) newpos) (not (eobp))
6477 (not (eq (following-char) ?\n)))
6478 ;; If we skipped something intangible and now we're not
6479 ;; really at eol, keep going.
6480 (setq arg 1)
6481 (setq done t)))))))
6483 (defun move-beginning-of-line (arg)
6484 "Move point to beginning of current line as displayed.
6485 \(If there's an image in the line, this disregards newlines
6486 which are part of the text that the image rests on.)
6488 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6489 If point reaches the beginning or end of buffer, it stops there.
6490 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6491 (interactive "^p")
6492 (or arg (setq arg 1))
6494 (let ((orig (point))
6495 first-vis first-vis-field-value)
6497 ;; Move by lines, if ARG is not 1 (the default).
6498 (if (/= arg 1)
6499 (let ((line-move-visual nil))
6500 (line-move (1- arg) t)))
6502 ;; Move to beginning-of-line, ignoring fields and invisible text.
6503 (skip-chars-backward "^\n")
6504 (while (and (not (bobp)) (invisible-p (1- (point))))
6505 (goto-char (previous-char-property-change (point)))
6506 (skip-chars-backward "^\n"))
6508 ;; Now find first visible char in the line.
6509 (while (and (< (point) orig) (invisible-p (point)))
6510 (goto-char (next-char-property-change (point) orig)))
6511 (setq first-vis (point))
6513 ;; See if fields would stop us from reaching FIRST-VIS.
6514 (setq first-vis-field-value
6515 (constrain-to-field first-vis orig (/= arg 1) t nil))
6517 (goto-char (if (/= first-vis-field-value first-vis)
6518 ;; If yes, obey them.
6519 first-vis-field-value
6520 ;; Otherwise, move to START with attention to fields.
6521 ;; (It is possible that fields never matter in this case.)
6522 (constrain-to-field (point) orig
6523 (/= arg 1) t nil)))))
6526 ;; Many people have said they rarely use this feature, and often type
6527 ;; it by accident. Maybe it shouldn't even be on a key.
6528 (put 'set-goal-column 'disabled t)
6530 (defun set-goal-column (arg)
6531 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6532 Those commands will move to this position in the line moved to
6533 rather than trying to keep the same horizontal position.
6534 With a non-nil argument ARG, clears out the goal column
6535 so that \\[next-line] and \\[previous-line] resume vertical motion.
6536 The goal column is stored in the variable `goal-column'.
6537 This is a buffer-local setting."
6538 (interactive "P")
6539 (if arg
6540 (progn
6541 (setq goal-column nil)
6542 (message "No goal column"))
6543 (setq goal-column (current-column))
6544 ;; The older method below can be erroneous if `set-goal-column' is bound
6545 ;; to a sequence containing %
6546 ;;(message (substitute-command-keys
6547 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6548 ;;goal-column)
6549 (message "%s"
6550 (concat
6551 (format "Goal column %d " goal-column)
6552 (substitute-command-keys
6553 "(use \\[set-goal-column] with an arg to unset it)")))
6556 nil)
6558 ;;; Editing based on visual lines, as opposed to logical lines.
6560 (defun end-of-visual-line (&optional n)
6561 "Move point to end of current visual line.
6562 With argument N not nil or 1, move forward N - 1 visual lines first.
6563 If point reaches the beginning or end of buffer, it stops there.
6564 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6565 (interactive "^p")
6566 (or n (setq n 1))
6567 (if (/= n 1)
6568 (let ((line-move-visual t))
6569 (line-move (1- n) t)))
6570 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6571 ;; constrain to field boundaries, so we don't either.
6572 (vertical-motion (cons (window-width) 0)))
6574 (defun beginning-of-visual-line (&optional n)
6575 "Move point to beginning of current visual line.
6576 With argument N not nil or 1, move forward N - 1 visual lines first.
6577 If point reaches the beginning or end of buffer, it stops there.
6578 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6579 (interactive "^p")
6580 (or n (setq n 1))
6581 (let ((opoint (point)))
6582 (if (/= n 1)
6583 (let ((line-move-visual t))
6584 (line-move (1- n) t)))
6585 (vertical-motion 0)
6586 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6587 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6589 (defun kill-visual-line (&optional arg)
6590 "Kill the rest of the visual line.
6591 With prefix argument ARG, kill that many visual lines from point.
6592 If ARG is negative, kill visual lines backward.
6593 If ARG is zero, kill the text before point on the current visual
6594 line.
6596 If you want to append the killed line to the last killed text,
6597 use \\[append-next-kill] before \\[kill-line].
6599 If the buffer is read-only, Emacs will beep and refrain from deleting
6600 the line, but put the line in the kill ring anyway. This means that
6601 you can use this command to copy text from a read-only buffer.
6602 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6603 even beep.)"
6604 (interactive "P")
6605 ;; Like in `kill-line', it's better to move point to the other end
6606 ;; of the kill before killing.
6607 (let ((opoint (point))
6608 (kill-whole-line (and kill-whole-line (bolp))))
6609 (if arg
6610 (vertical-motion (prefix-numeric-value arg))
6611 (end-of-visual-line 1)
6612 (if (= (point) opoint)
6613 (vertical-motion 1)
6614 ;; Skip any trailing whitespace at the end of the visual line.
6615 ;; We used to do this only if `show-trailing-whitespace' is
6616 ;; nil, but that's wrong; the correct thing would be to check
6617 ;; whether the trailing whitespace is highlighted. But, it's
6618 ;; OK to just do this unconditionally.
6619 (skip-chars-forward " \t")))
6620 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6621 (1+ (point))
6622 (point)))))
6624 (defun next-logical-line (&optional arg try-vscroll)
6625 "Move cursor vertically down ARG lines.
6626 This is identical to `next-line', except that it always moves
6627 by logical lines instead of visual lines, ignoring the value of
6628 the variable `line-move-visual'."
6629 (interactive "^p\np")
6630 (let ((line-move-visual nil))
6631 (with-no-warnings
6632 (next-line arg try-vscroll))))
6634 (defun previous-logical-line (&optional arg try-vscroll)
6635 "Move cursor vertically up ARG lines.
6636 This is identical to `previous-line', except that it always moves
6637 by logical lines instead of visual lines, ignoring the value of
6638 the variable `line-move-visual'."
6639 (interactive "^p\np")
6640 (let ((line-move-visual nil))
6641 (with-no-warnings
6642 (previous-line arg try-vscroll))))
6644 (defgroup visual-line nil
6645 "Editing based on visual lines."
6646 :group 'convenience
6647 :version "23.1")
6649 (defvar visual-line-mode-map
6650 (let ((map (make-sparse-keymap)))
6651 (define-key map [remap kill-line] 'kill-visual-line)
6652 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6653 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6654 ;; These keybindings interfere with xterm function keys. Are
6655 ;; there any other suitable bindings?
6656 ;; (define-key map "\M-[" 'previous-logical-line)
6657 ;; (define-key map "\M-]" 'next-logical-line)
6658 map))
6660 (defcustom visual-line-fringe-indicators '(nil nil)
6661 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6662 The value should be a list of the form (LEFT RIGHT), where LEFT
6663 and RIGHT are symbols representing the bitmaps to display, to
6664 indicate wrapped lines, in the left and right fringes respectively.
6665 See also `fringe-indicator-alist'.
6666 The default is not to display fringe indicators for wrapped lines.
6667 This variable does not affect fringe indicators displayed for
6668 other purposes."
6669 :type '(list (choice (const :tag "Hide left indicator" nil)
6670 (const :tag "Left curly arrow" left-curly-arrow)
6671 (symbol :tag "Other bitmap"))
6672 (choice (const :tag "Hide right indicator" nil)
6673 (const :tag "Right curly arrow" right-curly-arrow)
6674 (symbol :tag "Other bitmap")))
6675 :set (lambda (symbol value)
6676 (dolist (buf (buffer-list))
6677 (with-current-buffer buf
6678 (when (and (boundp 'visual-line-mode)
6679 (symbol-value 'visual-line-mode))
6680 (setq fringe-indicator-alist
6681 (cons (cons 'continuation value)
6682 (assq-delete-all
6683 'continuation
6684 (copy-tree fringe-indicator-alist)))))))
6685 (set-default symbol value)))
6687 (defvar visual-line--saved-state nil)
6689 (define-minor-mode visual-line-mode
6690 "Toggle visual line based editing (Visual Line mode).
6691 With a prefix argument ARG, enable Visual Line mode if ARG is
6692 positive, and disable it otherwise. If called from Lisp, enable
6693 the mode if ARG is omitted or nil.
6695 When Visual Line mode is enabled, `word-wrap' is turned on in
6696 this buffer, and simple editing commands are redefined to act on
6697 visual lines, not logical lines. See Info node `Visual Line
6698 Mode' for details."
6699 :keymap visual-line-mode-map
6700 :group 'visual-line
6701 :lighter " Wrap"
6702 (if visual-line-mode
6703 (progn
6704 (set (make-local-variable 'visual-line--saved-state) nil)
6705 ;; Save the local values of some variables, to be restored if
6706 ;; visual-line-mode is turned off.
6707 (dolist (var '(line-move-visual truncate-lines
6708 truncate-partial-width-windows
6709 word-wrap fringe-indicator-alist))
6710 (if (local-variable-p var)
6711 (push (cons var (symbol-value var))
6712 visual-line--saved-state)))
6713 (set (make-local-variable 'line-move-visual) t)
6714 (set (make-local-variable 'truncate-partial-width-windows) nil)
6715 (setq truncate-lines nil
6716 word-wrap t
6717 fringe-indicator-alist
6718 (cons (cons 'continuation visual-line-fringe-indicators)
6719 fringe-indicator-alist)))
6720 (kill-local-variable 'line-move-visual)
6721 (kill-local-variable 'word-wrap)
6722 (kill-local-variable 'truncate-lines)
6723 (kill-local-variable 'truncate-partial-width-windows)
6724 (kill-local-variable 'fringe-indicator-alist)
6725 (dolist (saved visual-line--saved-state)
6726 (set (make-local-variable (car saved)) (cdr saved)))
6727 (kill-local-variable 'visual-line--saved-state)))
6729 (defun turn-on-visual-line-mode ()
6730 (visual-line-mode 1))
6732 (define-globalized-minor-mode global-visual-line-mode
6733 visual-line-mode turn-on-visual-line-mode)
6736 (defun transpose-chars (arg)
6737 "Interchange characters around point, moving forward one character.
6738 With prefix arg ARG, effect is to take character before point
6739 and drag it forward past ARG other characters (backward if ARG negative).
6740 If no argument and at end of line, the previous two chars are exchanged."
6741 (interactive "*P")
6742 (when (and (null arg) (eolp) (not (bobp))
6743 (not (get-text-property (1- (point)) 'read-only)))
6744 (forward-char -1))
6745 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6747 (defun transpose-words (arg)
6748 "Interchange words around point, leaving point at end of them.
6749 With prefix arg ARG, effect is to take word before or around point
6750 and drag it forward past ARG other words (backward if ARG negative).
6751 If ARG is zero, the words around or after point and around or after mark
6752 are interchanged."
6753 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6754 (interactive "*p")
6755 (transpose-subr 'forward-word arg))
6757 (defun transpose-sexps (arg)
6758 "Like \\[transpose-words] but applies to sexps.
6759 Does not work on a sexp that point is in the middle of
6760 if it is a list or string."
6761 (interactive "*p")
6762 (transpose-subr
6763 (lambda (arg)
6764 ;; Here we should try to simulate the behavior of
6765 ;; (cons (progn (forward-sexp x) (point))
6766 ;; (progn (forward-sexp (- x)) (point)))
6767 ;; Except that we don't want to rely on the second forward-sexp
6768 ;; putting us back to where we want to be, since forward-sexp-function
6769 ;; might do funny things like infix-precedence.
6770 (if (if (> arg 0)
6771 (looking-at "\\sw\\|\\s_")
6772 (and (not (bobp))
6773 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6774 ;; Jumping over a symbol. We might be inside it, mind you.
6775 (progn (funcall (if (> arg 0)
6776 'skip-syntax-backward 'skip-syntax-forward)
6777 "w_")
6778 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6779 ;; Otherwise, we're between sexps. Take a step back before jumping
6780 ;; to make sure we'll obey the same precedence no matter which direction
6781 ;; we're going.
6782 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6783 (cons (save-excursion (forward-sexp arg) (point))
6784 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6785 (not (zerop (funcall (if (> arg 0)
6786 'skip-syntax-forward
6787 'skip-syntax-backward)
6788 ".")))))
6789 (point)))))
6790 arg 'special))
6792 (defun transpose-lines (arg)
6793 "Exchange current line and previous line, leaving point after both.
6794 With argument ARG, takes previous line and moves it past ARG lines.
6795 With argument 0, interchanges line point is in with line mark is in."
6796 (interactive "*p")
6797 (transpose-subr (function
6798 (lambda (arg)
6799 (if (> arg 0)
6800 (progn
6801 ;; Move forward over ARG lines,
6802 ;; but create newlines if necessary.
6803 (setq arg (forward-line arg))
6804 (if (/= (preceding-char) ?\n)
6805 (setq arg (1+ arg)))
6806 (if (> arg 0)
6807 (newline arg)))
6808 (forward-line arg))))
6809 arg))
6811 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6812 ;; which seems inconsistent with the ARG /= 0 case.
6813 ;; FIXME document SPECIAL.
6814 (defun transpose-subr (mover arg &optional special)
6815 "Subroutine to do the work of transposing objects.
6816 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6817 moves forward by units of the given object (e.g. forward-sentence,
6818 forward-paragraph). If ARG is zero, exchanges the current object
6819 with the one containing mark. If ARG is an integer, moves the
6820 current object past ARG following (if ARG is positive) or
6821 preceding (if ARG is negative) objects, leaving point after the
6822 current object."
6823 (let ((aux (if special mover
6824 (lambda (x)
6825 (cons (progn (funcall mover x) (point))
6826 (progn (funcall mover (- x)) (point))))))
6827 pos1 pos2)
6828 (cond
6829 ((= arg 0)
6830 (save-excursion
6831 (setq pos1 (funcall aux 1))
6832 (goto-char (or (mark) (error "No mark set in this buffer")))
6833 (setq pos2 (funcall aux 1))
6834 (transpose-subr-1 pos1 pos2))
6835 (exchange-point-and-mark))
6836 ((> arg 0)
6837 (setq pos1 (funcall aux -1))
6838 (setq pos2 (funcall aux arg))
6839 (transpose-subr-1 pos1 pos2)
6840 (goto-char (car pos2)))
6842 (setq pos1 (funcall aux -1))
6843 (goto-char (car pos1))
6844 (setq pos2 (funcall aux arg))
6845 (transpose-subr-1 pos1 pos2)
6846 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6848 (defun transpose-subr-1 (pos1 pos2)
6849 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6850 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6851 (when (> (car pos1) (car pos2))
6852 (let ((swap pos1))
6853 (setq pos1 pos2 pos2 swap)))
6854 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6855 (atomic-change-group
6856 ;; This sequence of insertions attempts to preserve marker
6857 ;; positions at the start and end of the transposed objects.
6858 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6859 (len1 (- (cdr pos1) (car pos1)))
6860 (len2 (length word))
6861 (boundary (make-marker)))
6862 (set-marker boundary (car pos2))
6863 (goto-char (cdr pos1))
6864 (insert-before-markers word)
6865 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6866 (goto-char boundary)
6867 (insert word)
6868 (goto-char (+ boundary len1))
6869 (delete-region (point) (+ (point) len2))
6870 (set-marker boundary nil))))
6872 (defun backward-word (&optional arg)
6873 "Move backward until encountering the beginning of a word.
6874 With argument ARG, do this that many times.
6875 If ARG is omitted or nil, move point backward one word.
6877 The word boundaries are normally determined by the buffer's syntax
6878 table, but `find-word-boundary-function-table', such as set up
6879 by `subword-mode', can change that. If a Lisp program needs to
6880 move by words determined strictly by the syntax table, it should
6881 use `backward-word-strictly' instead."
6882 (interactive "^p")
6883 (forward-word (- (or arg 1))))
6885 (defun mark-word (&optional arg allow-extend)
6886 "Set mark ARG words away from point.
6887 The place mark goes is the same place \\[forward-word] would
6888 move to with the same argument.
6889 Interactively, if this command is repeated
6890 or (in Transient Mark mode) if the mark is active,
6891 it marks the next ARG words after the ones already marked."
6892 (interactive "P\np")
6893 (cond ((and allow-extend
6894 (or (and (eq last-command this-command) (mark t))
6895 (region-active-p)))
6896 (setq arg (if arg (prefix-numeric-value arg)
6897 (if (< (mark) (point)) -1 1)))
6898 (set-mark
6899 (save-excursion
6900 (goto-char (mark))
6901 (forward-word arg)
6902 (point))))
6904 (push-mark
6905 (save-excursion
6906 (forward-word (prefix-numeric-value arg))
6907 (point))
6908 nil t))))
6910 (defun kill-word (arg)
6911 "Kill characters forward until encountering the end of a word.
6912 With argument ARG, do this that many times."
6913 (interactive "p")
6914 (kill-region (point) (progn (forward-word arg) (point))))
6916 (defun backward-kill-word (arg)
6917 "Kill characters backward until encountering the beginning of a word.
6918 With argument ARG, do this that many times."
6919 (interactive "p")
6920 (kill-word (- arg)))
6922 (defun current-word (&optional strict really-word)
6923 "Return the symbol or word that point is on (or a nearby one) as a string.
6924 The return value includes no text properties.
6925 If optional arg STRICT is non-nil, return nil unless point is within
6926 or adjacent to a symbol or word. In all cases the value can be nil
6927 if there is no word nearby.
6928 The function, belying its name, normally finds a symbol.
6929 If optional arg REALLY-WORD is non-nil, it finds just a word."
6930 (save-excursion
6931 (let* ((oldpoint (point)) (start (point)) (end (point))
6932 (syntaxes (if really-word "w" "w_"))
6933 (not-syntaxes (concat "^" syntaxes)))
6934 (skip-syntax-backward syntaxes) (setq start (point))
6935 (goto-char oldpoint)
6936 (skip-syntax-forward syntaxes) (setq end (point))
6937 (when (and (eq start oldpoint) (eq end oldpoint)
6938 ;; Point is neither within nor adjacent to a word.
6939 (not strict))
6940 ;; Look for preceding word in same line.
6941 (skip-syntax-backward not-syntaxes (line-beginning-position))
6942 (if (bolp)
6943 ;; No preceding word in same line.
6944 ;; Look for following word in same line.
6945 (progn
6946 (skip-syntax-forward not-syntaxes (line-end-position))
6947 (setq start (point))
6948 (skip-syntax-forward syntaxes)
6949 (setq end (point)))
6950 (setq end (point))
6951 (skip-syntax-backward syntaxes)
6952 (setq start (point))))
6953 ;; If we found something nonempty, return it as a string.
6954 (unless (= start end)
6955 (buffer-substring-no-properties start end)))))
6957 (defcustom fill-prefix nil
6958 "String for filling to insert at front of new line, or nil for none."
6959 :type '(choice (const :tag "None" nil)
6960 string)
6961 :group 'fill)
6962 (make-variable-buffer-local 'fill-prefix)
6963 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6965 (defcustom auto-fill-inhibit-regexp nil
6966 "Regexp to match lines which should not be auto-filled."
6967 :type '(choice (const :tag "None" nil)
6968 regexp)
6969 :group 'fill)
6971 (defun do-auto-fill ()
6972 "The default value for `normal-auto-fill-function'.
6973 This is the default auto-fill function, some major modes use a different one.
6974 Returns t if it really did any work."
6975 (let (fc justify give-up
6976 (fill-prefix fill-prefix))
6977 (if (or (not (setq justify (current-justification)))
6978 (null (setq fc (current-fill-column)))
6979 (and (eq justify 'left)
6980 (<= (current-column) fc))
6981 (and auto-fill-inhibit-regexp
6982 (save-excursion (beginning-of-line)
6983 (looking-at auto-fill-inhibit-regexp))))
6984 nil ;; Auto-filling not required
6985 (if (memq justify '(full center right))
6986 (save-excursion (unjustify-current-line)))
6988 ;; Choose a fill-prefix automatically.
6989 (when (and adaptive-fill-mode
6990 (or (null fill-prefix) (string= fill-prefix "")))
6991 (let ((prefix
6992 (fill-context-prefix
6993 (save-excursion (fill-forward-paragraph -1) (point))
6994 (save-excursion (fill-forward-paragraph 1) (point)))))
6995 (and prefix (not (equal prefix ""))
6996 ;; Use auto-indentation rather than a guessed empty prefix.
6997 (not (and fill-indent-according-to-mode
6998 (string-match "\\`[ \t]*\\'" prefix)))
6999 (setq fill-prefix prefix))))
7001 (while (and (not give-up) (> (current-column) fc))
7002 ;; Determine where to split the line.
7003 (let* (after-prefix
7004 (fill-point
7005 (save-excursion
7006 (beginning-of-line)
7007 (setq after-prefix (point))
7008 (and fill-prefix
7009 (looking-at (regexp-quote fill-prefix))
7010 (setq after-prefix (match-end 0)))
7011 (move-to-column (1+ fc))
7012 (fill-move-to-break-point after-prefix)
7013 (point))))
7015 ;; See whether the place we found is any good.
7016 (if (save-excursion
7017 (goto-char fill-point)
7018 (or (bolp)
7019 ;; There is no use breaking at end of line.
7020 (save-excursion (skip-chars-forward " ") (eolp))
7021 ;; It is futile to split at the end of the prefix
7022 ;; since we would just insert the prefix again.
7023 (and after-prefix (<= (point) after-prefix))
7024 ;; Don't split right after a comment starter
7025 ;; since we would just make another comment starter.
7026 (and comment-start-skip
7027 (let ((limit (point)))
7028 (beginning-of-line)
7029 (and (re-search-forward comment-start-skip
7030 limit t)
7031 (eq (point) limit))))))
7032 ;; No good place to break => stop trying.
7033 (setq give-up t)
7034 ;; Ok, we have a useful place to break the line. Do it.
7035 (let ((prev-column (current-column)))
7036 ;; If point is at the fill-point, do not `save-excursion'.
7037 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7038 ;; point will end up before it rather than after it.
7039 (if (save-excursion
7040 (skip-chars-backward " \t")
7041 (= (point) fill-point))
7042 (default-indent-new-line t)
7043 (save-excursion
7044 (goto-char fill-point)
7045 (default-indent-new-line t)))
7046 ;; Now do justification, if required
7047 (if (not (eq justify 'left))
7048 (save-excursion
7049 (end-of-line 0)
7050 (justify-current-line justify nil t)))
7051 ;; If making the new line didn't reduce the hpos of
7052 ;; the end of the line, then give up now;
7053 ;; trying again will not help.
7054 (if (>= (current-column) prev-column)
7055 (setq give-up t))))))
7056 ;; Justify last line.
7057 (justify-current-line justify t t)
7058 t)))
7060 (defvar comment-line-break-function 'comment-indent-new-line
7061 "Mode-specific function which line breaks and continues a comment.
7062 This function is called during auto-filling when a comment syntax
7063 is defined.
7064 The function should take a single optional argument, which is a flag
7065 indicating whether it should use soft newlines.")
7067 (defun default-indent-new-line (&optional soft)
7068 "Break line at point and indent.
7069 If a comment syntax is defined, call `comment-indent-new-line'.
7071 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7072 unless optional argument SOFT is non-nil."
7073 (interactive)
7074 (if comment-start
7075 (funcall comment-line-break-function soft)
7076 ;; Insert the newline before removing empty space so that markers
7077 ;; get preserved better.
7078 (if soft (insert-and-inherit ?\n) (newline 1))
7079 (save-excursion (forward-char -1) (delete-horizontal-space))
7080 (delete-horizontal-space)
7082 (if (and fill-prefix (not adaptive-fill-mode))
7083 ;; Blindly trust a non-adaptive fill-prefix.
7084 (progn
7085 (indent-to-left-margin)
7086 (insert-before-markers-and-inherit fill-prefix))
7088 (cond
7089 ;; If there's an adaptive prefix, use it unless we're inside
7090 ;; a comment and the prefix is not a comment starter.
7091 (fill-prefix
7092 (indent-to-left-margin)
7093 (insert-and-inherit fill-prefix))
7094 ;; If we're not inside a comment, just try to indent.
7095 (t (indent-according-to-mode))))))
7097 (defvar normal-auto-fill-function 'do-auto-fill
7098 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7099 Some major modes set this.")
7101 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7102 ;; `functions' and `hooks' are usually unsafe to set, but setting
7103 ;; auto-fill-function to nil in a file-local setting is safe and
7104 ;; can be useful to prevent auto-filling.
7105 (put 'auto-fill-function 'safe-local-variable 'null)
7107 (define-minor-mode auto-fill-mode
7108 "Toggle automatic line breaking (Auto Fill mode).
7109 With a prefix argument ARG, enable Auto Fill mode if ARG is
7110 positive, and disable it otherwise. If called from Lisp, enable
7111 the mode if ARG is omitted or nil.
7113 When Auto Fill mode is enabled, inserting a space at a column
7114 beyond `current-fill-column' automatically breaks the line at a
7115 previous space.
7117 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7118 non-nil.
7120 The value of `normal-auto-fill-function' specifies the function to use
7121 for `auto-fill-function' when turning Auto Fill mode on."
7122 :variable (auto-fill-function
7123 . (lambda (v) (setq auto-fill-function
7124 (if v normal-auto-fill-function)))))
7126 ;; This holds a document string used to document auto-fill-mode.
7127 (defun auto-fill-function ()
7128 "Automatically break line at a previous space, in insertion of text."
7129 nil)
7131 (defun turn-on-auto-fill ()
7132 "Unconditionally turn on Auto Fill mode."
7133 (auto-fill-mode 1))
7135 (defun turn-off-auto-fill ()
7136 "Unconditionally turn off Auto Fill mode."
7137 (auto-fill-mode -1))
7139 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7141 (defun set-fill-column (arg)
7142 "Set `fill-column' to specified argument.
7143 Use \\[universal-argument] followed by a number to specify a column.
7144 Just \\[universal-argument] as argument means to use the current column."
7145 (interactive
7146 (list (or current-prefix-arg
7147 ;; We used to use current-column silently, but C-x f is too easily
7148 ;; typed as a typo for C-x C-f, so we turned it into an error and
7149 ;; now an interactive prompt.
7150 (read-number "Set fill-column to: " (current-column)))))
7151 (if (consp arg)
7152 (setq arg (current-column)))
7153 (if (not (integerp arg))
7154 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7155 (error "set-fill-column requires an explicit argument")
7156 (message "Fill column set to %d (was %d)" arg fill-column)
7157 (setq fill-column arg)))
7159 (defun set-selective-display (arg)
7160 "Set `selective-display' to ARG; clear it if no arg.
7161 When the value of `selective-display' is a number > 0,
7162 lines whose indentation is >= that value are not displayed.
7163 The variable `selective-display' has a separate value for each buffer."
7164 (interactive "P")
7165 (if (eq selective-display t)
7166 (error "selective-display already in use for marked lines"))
7167 (let ((current-vpos
7168 (save-restriction
7169 (narrow-to-region (point-min) (point))
7170 (goto-char (window-start))
7171 (vertical-motion (window-height)))))
7172 (setq selective-display
7173 (and arg (prefix-numeric-value arg)))
7174 (recenter current-vpos))
7175 (set-window-start (selected-window) (window-start))
7176 (princ "selective-display set to " t)
7177 (prin1 selective-display t)
7178 (princ "." t))
7180 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7182 (defun toggle-truncate-lines (&optional arg)
7183 "Toggle truncating of long lines for the current buffer.
7184 When truncating is off, long lines are folded.
7185 With prefix argument ARG, truncate long lines if ARG is positive,
7186 otherwise fold them. Note that in side-by-side windows, this
7187 command has no effect if `truncate-partial-width-windows' is
7188 non-nil."
7189 (interactive "P")
7190 (setq truncate-lines
7191 (if (null arg)
7192 (not truncate-lines)
7193 (> (prefix-numeric-value arg) 0)))
7194 (force-mode-line-update)
7195 (unless truncate-lines
7196 (let ((buffer (current-buffer)))
7197 (walk-windows (lambda (window)
7198 (if (eq buffer (window-buffer window))
7199 (set-window-hscroll window 0)))
7200 nil t)))
7201 (message "Truncate long lines %s"
7202 (if truncate-lines "enabled" "disabled")))
7204 (defun toggle-word-wrap (&optional arg)
7205 "Toggle whether to use word-wrapping for continuation lines.
7206 With prefix argument ARG, wrap continuation lines at word boundaries
7207 if ARG is positive, otherwise wrap them at the right screen edge.
7208 This command toggles the value of `word-wrap'. It has no effect
7209 if long lines are truncated."
7210 (interactive "P")
7211 (setq word-wrap
7212 (if (null arg)
7213 (not word-wrap)
7214 (> (prefix-numeric-value arg) 0)))
7215 (force-mode-line-update)
7216 (message "Word wrapping %s"
7217 (if word-wrap "enabled" "disabled")))
7219 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7220 "The string displayed in the mode line when in overwrite mode.")
7221 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7222 "The string displayed in the mode line when in binary overwrite mode.")
7224 (define-minor-mode overwrite-mode
7225 "Toggle Overwrite mode.
7226 With a prefix argument ARG, enable Overwrite mode if ARG is
7227 positive, and disable it otherwise. If called from Lisp, enable
7228 the mode if ARG is omitted or nil.
7230 When Overwrite mode is enabled, printing characters typed in
7231 replace existing text on a one-for-one basis, rather than pushing
7232 it to the right. At the end of a line, such characters extend
7233 the line. Before a tab, such characters insert until the tab is
7234 filled in. \\[quoted-insert] still inserts characters in
7235 overwrite mode; this is supposed to make it easier to insert
7236 characters when necessary."
7237 :variable (overwrite-mode
7238 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7240 (define-minor-mode binary-overwrite-mode
7241 "Toggle Binary Overwrite mode.
7242 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7243 is positive, and disable it otherwise. If called from Lisp,
7244 enable the mode if ARG is omitted or nil.
7246 When Binary Overwrite mode is enabled, printing characters typed
7247 in replace existing text. Newlines are not treated specially, so
7248 typing at the end of a line joins the line to the next, with the
7249 typed character between them. Typing before a tab character
7250 simply replaces the tab with the character typed.
7251 \\[quoted-insert] replaces the text at the cursor, just as
7252 ordinary typing characters do.
7254 Note that Binary Overwrite mode is not its own minor mode; it is
7255 a specialization of overwrite mode, entered by setting the
7256 `overwrite-mode' variable to `overwrite-mode-binary'."
7257 :variable (overwrite-mode
7258 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7260 (define-minor-mode line-number-mode
7261 "Toggle line number display in the mode line (Line Number mode).
7262 With a prefix argument ARG, enable Line Number mode if ARG is
7263 positive, and disable it otherwise. If called from Lisp, enable
7264 the mode if ARG is omitted or nil.
7266 Line numbers do not appear for very large buffers and buffers
7267 with very long lines; see variables `line-number-display-limit'
7268 and `line-number-display-limit-width'."
7269 :init-value t :global t :group 'mode-line)
7271 (define-minor-mode column-number-mode
7272 "Toggle column number display in the mode line (Column Number mode).
7273 With a prefix argument ARG, enable Column Number mode if ARG is
7274 positive, and disable it otherwise.
7276 If called from Lisp, enable the mode if ARG is omitted or nil."
7277 :global t :group 'mode-line)
7279 (define-minor-mode size-indication-mode
7280 "Toggle buffer size display in the mode line (Size Indication mode).
7281 With a prefix argument ARG, enable Size Indication mode if ARG is
7282 positive, and disable it otherwise.
7284 If called from Lisp, enable the mode if ARG is omitted or nil."
7285 :global t :group 'mode-line)
7287 (define-minor-mode auto-save-mode
7288 "Toggle auto-saving in the current buffer (Auto Save mode).
7289 With a prefix argument ARG, enable Auto Save mode if ARG is
7290 positive, and disable it otherwise.
7292 If called from Lisp, enable the mode if ARG is omitted or nil."
7293 :variable ((and buffer-auto-save-file-name
7294 ;; If auto-save is off because buffer has shrunk,
7295 ;; then toggling should turn it on.
7296 (>= buffer-saved-size 0))
7297 . (lambda (val)
7298 (setq buffer-auto-save-file-name
7299 (cond
7300 ((null val) nil)
7301 ((and buffer-file-name auto-save-visited-file-name
7302 (not buffer-read-only))
7303 buffer-file-name)
7304 (t (make-auto-save-file-name))))))
7305 ;; If -1 was stored here, to temporarily turn off saving,
7306 ;; turn it back on.
7307 (and (< buffer-saved-size 0)
7308 (setq buffer-saved-size 0)))
7310 (defgroup paren-blinking nil
7311 "Blinking matching of parens and expressions."
7312 :prefix "blink-matching-"
7313 :group 'paren-matching)
7315 (defcustom blink-matching-paren t
7316 "Non-nil means show matching open-paren when close-paren is inserted.
7317 If t, highlight the paren. If `jump', briefly move cursor to its
7318 position. If `jump-offscreen', move cursor there even if the
7319 position is off screen. With any other non-nil value, the
7320 off-screen position of the opening paren will be shown in the
7321 echo area."
7322 :type '(choice
7323 (const :tag "Disable" nil)
7324 (const :tag "Highlight" t)
7325 (const :tag "Move cursor" jump)
7326 (const :tag "Move cursor, even if off screen" jump-offscreen))
7327 :group 'paren-blinking)
7329 (defcustom blink-matching-paren-on-screen t
7330 "Non-nil means show matching open-paren when it is on screen.
7331 If nil, don't show it (but the open-paren can still be shown
7332 in the echo area when it is off screen).
7334 This variable has no effect if `blink-matching-paren' is nil.
7335 \(In that case, the open-paren is never shown.)
7336 It is also ignored if `show-paren-mode' is enabled."
7337 :type 'boolean
7338 :group 'paren-blinking)
7340 (defcustom blink-matching-paren-distance (* 100 1024)
7341 "If non-nil, maximum distance to search backwards for matching open-paren.
7342 If nil, search stops at the beginning of the accessible portion of the buffer."
7343 :version "23.2" ; 25->100k
7344 :type '(choice (const nil) integer)
7345 :group 'paren-blinking)
7347 (defcustom blink-matching-delay 1
7348 "Time in seconds to delay after showing a matching paren."
7349 :type 'number
7350 :group 'paren-blinking)
7352 (defcustom blink-matching-paren-dont-ignore-comments nil
7353 "If nil, `blink-matching-paren' ignores comments.
7354 More precisely, when looking for the matching parenthesis,
7355 it skips the contents of comments that end before point."
7356 :type 'boolean
7357 :group 'paren-blinking)
7359 (defun blink-matching-check-mismatch (start end)
7360 "Return whether or not START...END are matching parens.
7361 END is the current point and START is the blink position.
7362 START might be nil if no matching starter was found.
7363 Returns non-nil if we find there is a mismatch."
7364 (let* ((end-syntax (syntax-after (1- end)))
7365 (matching-paren (and (consp end-syntax)
7366 (eq (syntax-class end-syntax) 5)
7367 (cdr end-syntax))))
7368 ;; For self-matched chars like " and $, we can't know when they're
7369 ;; mismatched or unmatched, so we can only do it for parens.
7370 (when matching-paren
7371 (not (and start
7373 (eq (char-after start) matching-paren)
7374 ;; The cdr might hold a new paren-class info rather than
7375 ;; a matching-char info, in which case the two CDRs
7376 ;; should match.
7377 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7379 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7380 "Function to check parentheses mismatches.
7381 The function takes two arguments (START and END) where START is the
7382 position just before the opening token and END is the position right after.
7383 START can be nil, if it was not found.
7384 The function should return non-nil if the two tokens do not match.")
7386 (defvar blink-matching--overlay
7387 (let ((ol (make-overlay (point) (point) nil t)))
7388 (overlay-put ol 'face 'show-paren-match)
7389 (delete-overlay ol)
7391 "Overlay used to highlight the matching paren.")
7393 (defun blink-matching-open ()
7394 "Momentarily highlight the beginning of the sexp before point."
7395 (interactive)
7396 (when (and (not (bobp))
7397 blink-matching-paren)
7398 (let* ((oldpos (point))
7399 (message-log-max nil) ; Don't log messages about paren matching.
7400 (blinkpos
7401 (save-excursion
7402 (save-restriction
7403 (if blink-matching-paren-distance
7404 (narrow-to-region
7405 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7406 (- (point) blink-matching-paren-distance))
7407 oldpos))
7408 (let ((parse-sexp-ignore-comments
7409 (and parse-sexp-ignore-comments
7410 (not blink-matching-paren-dont-ignore-comments))))
7411 (condition-case ()
7412 (progn
7413 (syntax-propertize (point))
7414 (forward-sexp -1)
7415 ;; backward-sexp skips backward over prefix chars,
7416 ;; so move back to the matching paren.
7417 (while (and (< (point) (1- oldpos))
7418 (let ((code (syntax-after (point))))
7419 (or (eq (syntax-class code) 6)
7420 (eq (logand 1048576 (car code))
7421 1048576))))
7422 (forward-char 1))
7423 (point))
7424 (error nil))))))
7425 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7426 (cond
7427 (mismatch
7428 (if blinkpos
7429 (if (minibufferp)
7430 (minibuffer-message "Mismatched parentheses")
7431 (message "Mismatched parentheses"))
7432 (if (minibufferp)
7433 (minibuffer-message "No matching parenthesis found")
7434 (message "No matching parenthesis found"))))
7435 ((not blinkpos) nil)
7436 ((or
7437 (eq blink-matching-paren 'jump-offscreen)
7438 (pos-visible-in-window-p blinkpos))
7439 ;; Matching open within window, temporarily move to or highlight
7440 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7441 ;; is non-nil.
7442 (and blink-matching-paren-on-screen
7443 (not show-paren-mode)
7444 (if (memq blink-matching-paren '(jump jump-offscreen))
7445 (save-excursion
7446 (goto-char blinkpos)
7447 (sit-for blink-matching-delay))
7448 (unwind-protect
7449 (progn
7450 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7451 (current-buffer))
7452 (sit-for blink-matching-delay))
7453 (delete-overlay blink-matching--overlay)))))
7455 (let ((open-paren-line-string
7456 (save-excursion
7457 (goto-char blinkpos)
7458 ;; Show what precedes the open in its line, if anything.
7459 (cond
7460 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7461 (buffer-substring (line-beginning-position)
7462 (1+ blinkpos)))
7463 ;; Show what follows the open in its line, if anything.
7464 ((save-excursion
7465 (forward-char 1)
7466 (skip-chars-forward " \t")
7467 (not (eolp)))
7468 (buffer-substring blinkpos
7469 (line-end-position)))
7470 ;; Otherwise show the previous nonblank line,
7471 ;; if there is one.
7472 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7473 (concat
7474 (buffer-substring (progn
7475 (skip-chars-backward "\n \t")
7476 (line-beginning-position))
7477 (progn (end-of-line)
7478 (skip-chars-backward " \t")
7479 (point)))
7480 ;; Replace the newline and other whitespace with `...'.
7481 "..."
7482 (buffer-substring blinkpos (1+ blinkpos))))
7483 ;; There is nothing to show except the char itself.
7484 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7485 (minibuffer-message
7486 "Matches %s"
7487 (substring-no-properties open-paren-line-string))))))))
7489 (defvar blink-paren-function 'blink-matching-open
7490 "Function called, if non-nil, whenever a close parenthesis is inserted.
7491 More precisely, a char with closeparen syntax is self-inserted.")
7493 (defun blink-paren-post-self-insert-function ()
7494 (when (and (eq (char-before) last-command-event) ; Sanity check.
7495 (memq (char-syntax last-command-event) '(?\) ?\$))
7496 blink-paren-function
7497 (not executing-kbd-macro)
7498 (not noninteractive)
7499 ;; Verify an even number of quoting characters precede the close.
7500 ;; FIXME: Also check if this parenthesis closes a comment as
7501 ;; can happen in Pascal and SML.
7502 (= 1 (logand 1 (- (point)
7503 (save-excursion
7504 (forward-char -1)
7505 (skip-syntax-backward "/\\")
7506 (point))))))
7507 (funcall blink-paren-function)))
7509 (put 'blink-paren-post-self-insert-function 'priority 100)
7511 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7512 ;; Most likely, this hook is nil, so this arg doesn't matter,
7513 ;; but I use it as a reminder that this function usually
7514 ;; likes to be run after others since it does
7515 ;; `sit-for'. That's also the reason it get a `priority' prop
7516 ;; of 100.
7517 'append)
7519 ;; This executes C-g typed while Emacs is waiting for a command.
7520 ;; Quitting out of a program does not go through here;
7521 ;; that happens in the QUIT macro at the C code level.
7522 (defun keyboard-quit ()
7523 "Signal a `quit' condition.
7524 During execution of Lisp code, this character causes a quit directly.
7525 At top-level, as an editor command, this simply beeps."
7526 (interactive)
7527 ;; Avoid adding the region to the window selection.
7528 (setq saved-region-selection nil)
7529 (let (select-active-regions)
7530 (deactivate-mark))
7531 (if (fboundp 'kmacro-keyboard-quit)
7532 (kmacro-keyboard-quit))
7533 (when completion-in-region-mode
7534 (completion-in-region-mode -1))
7535 ;; Force the next redisplay cycle to remove the "Def" indicator from
7536 ;; all the mode lines.
7537 (if defining-kbd-macro
7538 (force-mode-line-update t))
7539 (setq defining-kbd-macro nil)
7540 (let ((debug-on-quit nil))
7541 (signal 'quit nil)))
7543 (defvar buffer-quit-function nil
7544 "Function to call to \"quit\" the current buffer, or nil if none.
7545 \\[keyboard-escape-quit] calls this function when its more local actions
7546 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7548 (defun keyboard-escape-quit ()
7549 "Exit the current \"mode\" (in a generalized sense of the word).
7550 This command can exit an interactive command such as `query-replace',
7551 can clear out a prefix argument or a region,
7552 can get out of the minibuffer or other recursive edit,
7553 cancel the use of the current buffer (for special-purpose buffers),
7554 or go back to just one window (by deleting all but the selected window)."
7555 (interactive)
7556 (cond ((eq last-command 'mode-exited) nil)
7557 ((region-active-p)
7558 (deactivate-mark))
7559 ((> (minibuffer-depth) 0)
7560 (abort-recursive-edit))
7561 (current-prefix-arg
7562 nil)
7563 ((> (recursion-depth) 0)
7564 (exit-recursive-edit))
7565 (buffer-quit-function
7566 (funcall buffer-quit-function))
7567 ((not (one-window-p t))
7568 (delete-other-windows))
7569 ((string-match "^ \\*" (buffer-name (current-buffer)))
7570 (bury-buffer))))
7572 (defun play-sound-file (file &optional volume device)
7573 "Play sound stored in FILE.
7574 VOLUME and DEVICE correspond to the keywords of the sound
7575 specification for `play-sound'."
7576 (interactive "fPlay sound file: ")
7577 (let ((sound (list :file file)))
7578 (if volume
7579 (plist-put sound :volume volume))
7580 (if device
7581 (plist-put sound :device device))
7582 (push 'sound sound)
7583 (play-sound sound)))
7586 (defcustom read-mail-command 'rmail
7587 "Your preference for a mail reading package.
7588 This is used by some keybindings which support reading mail.
7589 See also `mail-user-agent' concerning sending mail."
7590 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7591 (function-item :tag "Gnus" :format "%t\n" gnus)
7592 (function-item :tag "Emacs interface to MH"
7593 :format "%t\n" mh-rmail)
7594 (function :tag "Other"))
7595 :version "21.1"
7596 :group 'mail)
7598 (defcustom mail-user-agent 'message-user-agent
7599 "Your preference for a mail composition package.
7600 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7601 outgoing email message. This variable lets you specify which
7602 mail-sending package you prefer.
7604 Valid values include:
7606 `message-user-agent' -- use the Message package.
7607 See Info node `(message)'.
7608 `sendmail-user-agent' -- use the Mail package.
7609 See Info node `(emacs)Sending Mail'.
7610 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7611 See Info node `(mh-e)'.
7612 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7613 paraphernalia if Gnus is running, particularly
7614 the Gcc: header for archiving.
7616 Additional valid symbols may be available; check with the author of
7617 your package for details. The function should return non-nil if it
7618 succeeds.
7620 See also `read-mail-command' concerning reading mail."
7621 :type '(radio (function-item :tag "Message package"
7622 :format "%t\n"
7623 message-user-agent)
7624 (function-item :tag "Mail package"
7625 :format "%t\n"
7626 sendmail-user-agent)
7627 (function-item :tag "Emacs interface to MH"
7628 :format "%t\n"
7629 mh-e-user-agent)
7630 (function-item :tag "Message with full Gnus features"
7631 :format "%t\n"
7632 gnus-user-agent)
7633 (function :tag "Other"))
7634 :version "23.2" ; sendmail->message
7635 :group 'mail)
7637 (defcustom compose-mail-user-agent-warnings t
7638 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7639 If the value of `mail-user-agent' is the default, and the user
7640 appears to have customizations applying to the old default,
7641 `compose-mail' issues a warning."
7642 :type 'boolean
7643 :version "23.2"
7644 :group 'mail)
7646 (defun rfc822-goto-eoh ()
7647 "If the buffer starts with a mail header, move point to the header's end.
7648 Otherwise, moves to `point-min'.
7649 The end of the header is the start of the next line, if there is one,
7650 else the end of the last line. This function obeys RFC822."
7651 (goto-char (point-min))
7652 (when (re-search-forward
7653 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7654 (goto-char (match-beginning 0))))
7656 ;; Used by Rmail (e.g., rmail-forward).
7657 (defvar mail-encode-mml nil
7658 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7659 the outgoing message before sending it.")
7661 (defun compose-mail (&optional to subject other-headers continue
7662 switch-function yank-action send-actions
7663 return-action)
7664 "Start composing a mail message to send.
7665 This uses the user's chosen mail composition package
7666 as selected with the variable `mail-user-agent'.
7667 The optional arguments TO and SUBJECT specify recipients
7668 and the initial Subject field, respectively.
7670 OTHER-HEADERS is an alist specifying additional
7671 header fields. Elements look like (HEADER . VALUE) where both
7672 HEADER and VALUE are strings.
7674 CONTINUE, if non-nil, says to continue editing a message already
7675 being composed. Interactively, CONTINUE is the prefix argument.
7677 SWITCH-FUNCTION, if non-nil, is a function to use to
7678 switch to and display the buffer used for mail composition.
7680 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7681 to insert the raw text of the message being replied to.
7682 It has the form (FUNCTION . ARGS). The user agent will apply
7683 FUNCTION to ARGS, to insert the raw text of the original message.
7684 \(The user agent will also run `mail-citation-hook', *after* the
7685 original text has been inserted in this way.)
7687 SEND-ACTIONS is a list of actions to call when the message is sent.
7688 Each action has the form (FUNCTION . ARGS).
7690 RETURN-ACTION, if non-nil, is an action for returning to the
7691 caller. It has the form (FUNCTION . ARGS). The function is
7692 called after the mail has been sent or put aside, and the mail
7693 buffer buried."
7694 (interactive
7695 (list nil nil nil current-prefix-arg))
7697 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7698 ;; from sendmail-user-agent to message-user-agent. Some users may
7699 ;; encounter incompatibilities. This hack tries to detect problems
7700 ;; and warn about them.
7701 (and compose-mail-user-agent-warnings
7702 (eq mail-user-agent 'message-user-agent)
7703 (let (warn-vars)
7704 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7705 mail-yank-hooks mail-archive-file-name
7706 mail-default-reply-to mail-mailing-lists
7707 mail-self-blind))
7708 (and (boundp var)
7709 (symbol-value var)
7710 (push var warn-vars)))
7711 (when warn-vars
7712 (display-warning 'mail
7713 (format-message "\
7714 The default mail mode is now Message mode.
7715 You have the following Mail mode variable%s customized:
7716 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7717 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7718 (if (> (length warn-vars) 1) "s" "")
7719 (mapconcat 'symbol-name
7720 warn-vars " "))))))
7722 (let ((function (get mail-user-agent 'composefunc)))
7723 (funcall function to subject other-headers continue switch-function
7724 yank-action send-actions return-action)))
7726 (defun compose-mail-other-window (&optional to subject other-headers continue
7727 yank-action send-actions
7728 return-action)
7729 "Like \\[compose-mail], but edit the outgoing message in another window."
7730 (interactive (list nil nil nil current-prefix-arg))
7731 (compose-mail to subject other-headers continue
7732 'switch-to-buffer-other-window yank-action send-actions
7733 return-action))
7735 (defun compose-mail-other-frame (&optional to subject other-headers continue
7736 yank-action send-actions
7737 return-action)
7738 "Like \\[compose-mail], but edit the outgoing message in another frame."
7739 (interactive (list nil nil nil current-prefix-arg))
7740 (compose-mail to subject other-headers continue
7741 'switch-to-buffer-other-frame yank-action send-actions
7742 return-action))
7745 (defvar set-variable-value-history nil
7746 "History of values entered with `set-variable'.
7748 Maximum length of the history list is determined by the value
7749 of `history-length', which see.")
7751 (defun set-variable (variable value &optional make-local)
7752 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7753 VARIABLE should be a user option variable name, a Lisp variable
7754 meant to be customized by users. You should enter VALUE in Lisp syntax,
7755 so if you want VALUE to be a string, you must surround it with doublequotes.
7756 VALUE is used literally, not evaluated.
7758 If VARIABLE has a `variable-interactive' property, that is used as if
7759 it were the arg to `interactive' (which see) to interactively read VALUE.
7761 If VARIABLE has been defined with `defcustom', then the type information
7762 in the definition is used to check that VALUE is valid.
7764 Note that this function is at heart equivalent to the basic `set' function.
7765 For a variable defined with `defcustom', it does not pay attention to
7766 any :set property that the variable might have (if you want that, use
7767 \\[customize-set-variable] instead).
7769 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7770 (interactive
7771 (let* ((default-var (variable-at-point))
7772 (var (if (custom-variable-p default-var)
7773 (read-variable (format "Set variable (default %s): " default-var)
7774 default-var)
7775 (read-variable "Set variable: ")))
7776 (minibuffer-help-form '(describe-variable var))
7777 (prop (get var 'variable-interactive))
7778 (obsolete (car (get var 'byte-obsolete-variable)))
7779 (prompt (format "Set %s %s to value: " var
7780 (cond ((local-variable-p var)
7781 "(buffer-local)")
7782 ((or current-prefix-arg
7783 (local-variable-if-set-p var))
7784 "buffer-locally")
7785 (t "globally"))))
7786 (val (progn
7787 (when obsolete
7788 (message (concat "`%S' is obsolete; "
7789 (if (symbolp obsolete) "use `%S' instead" "%s"))
7790 var obsolete)
7791 (sit-for 3))
7792 (if prop
7793 ;; Use VAR's `variable-interactive' property
7794 ;; as an interactive spec for prompting.
7795 (call-interactively `(lambda (arg)
7796 (interactive ,prop)
7797 arg))
7798 (read-from-minibuffer prompt nil
7799 read-expression-map t
7800 'set-variable-value-history
7801 (format "%S" (symbol-value var)))))))
7802 (list var val current-prefix-arg)))
7804 (and (custom-variable-p variable)
7805 (not (get variable 'custom-type))
7806 (custom-load-symbol variable))
7807 (let ((type (get variable 'custom-type)))
7808 (when type
7809 ;; Match with custom type.
7810 (require 'cus-edit)
7811 (setq type (widget-convert type))
7812 (unless (widget-apply type :match value)
7813 (user-error "Value `%S' does not match type %S of %S"
7814 value (car type) variable))))
7816 (if make-local
7817 (make-local-variable variable))
7819 (set variable value)
7821 ;; Force a thorough redisplay for the case that the variable
7822 ;; has an effect on the display, like `tab-width' has.
7823 (force-mode-line-update))
7825 ;; Define the major mode for lists of completions.
7827 (defvar completion-list-mode-map
7828 (let ((map (make-sparse-keymap)))
7829 (define-key map [mouse-2] 'choose-completion)
7830 (define-key map [follow-link] 'mouse-face)
7831 (define-key map [down-mouse-2] nil)
7832 (define-key map "\C-m" 'choose-completion)
7833 (define-key map "\e\e\e" 'delete-completion-window)
7834 (define-key map [left] 'previous-completion)
7835 (define-key map [right] 'next-completion)
7836 (define-key map [?\t] 'next-completion)
7837 (define-key map [backtab] 'previous-completion)
7838 (define-key map "q" 'quit-window)
7839 (define-key map "z" 'kill-this-buffer)
7840 map)
7841 "Local map for completion list buffers.")
7843 ;; Completion mode is suitable only for specially formatted data.
7844 (put 'completion-list-mode 'mode-class 'special)
7846 (defvar completion-reference-buffer nil
7847 "Record the buffer that was current when the completion list was requested.
7848 This is a local variable in the completion list buffer.
7849 Initial value is nil to avoid some compiler warnings.")
7851 (defvar completion-no-auto-exit nil
7852 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7853 This also applies to other functions such as `choose-completion'.")
7855 (defvar completion-base-position nil
7856 "Position of the base of the text corresponding to the shown completions.
7857 This variable is used in the *Completions* buffers.
7858 Its value is a list of the form (START END) where START is the place
7859 where the completion should be inserted and END (if non-nil) is the end
7860 of the text to replace. If END is nil, point is used instead.")
7862 (defvar completion-list-insert-choice-function #'completion--replace
7863 "Function to use to insert the text chosen in *Completions*.
7864 Called with three arguments (BEG END TEXT), it should replace the text
7865 between BEG and END with TEXT. Expected to be set buffer-locally
7866 in the *Completions* buffer.")
7868 (defvar completion-base-size nil
7869 "Number of chars before point not involved in completion.
7870 This is a local variable in the completion list buffer.
7871 It refers to the chars in the minibuffer if completing in the
7872 minibuffer, or in `completion-reference-buffer' otherwise.
7873 Only characters in the field at point are included.
7875 If nil, Emacs determines which part of the tail end of the
7876 buffer's text is involved in completion by comparing the text
7877 directly.")
7878 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7880 (defun delete-completion-window ()
7881 "Delete the completion list window.
7882 Go to the window from which completion was requested."
7883 (interactive)
7884 (let ((buf completion-reference-buffer))
7885 (if (one-window-p t)
7886 (if (window-dedicated-p) (delete-frame))
7887 (delete-window (selected-window))
7888 (if (get-buffer-window buf)
7889 (select-window (get-buffer-window buf))))))
7891 (defun previous-completion (n)
7892 "Move to the previous item in the completion list."
7893 (interactive "p")
7894 (next-completion (- n)))
7896 (defun next-completion (n)
7897 "Move to the next item in the completion list.
7898 With prefix argument N, move N items (negative N means move backward)."
7899 (interactive "p")
7900 (let ((beg (point-min)) (end (point-max)))
7901 (while (and (> n 0) (not (eobp)))
7902 ;; If in a completion, move to the end of it.
7903 (when (get-text-property (point) 'mouse-face)
7904 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7905 ;; Move to start of next one.
7906 (unless (get-text-property (point) 'mouse-face)
7907 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7908 (setq n (1- n)))
7909 (while (and (< n 0) (not (bobp)))
7910 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7911 ;; If in a completion, move to the start of it.
7912 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7913 (goto-char (previous-single-property-change
7914 (point) 'mouse-face nil beg)))
7915 ;; Move to end of the previous completion.
7916 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7917 (goto-char (previous-single-property-change
7918 (point) 'mouse-face nil beg)))
7919 ;; Move to the start of that one.
7920 (goto-char (previous-single-property-change
7921 (point) 'mouse-face nil beg))
7922 (setq n (1+ n))))))
7924 (defun choose-completion (&optional event)
7925 "Choose the completion at point.
7926 If EVENT, use EVENT's position to determine the starting position."
7927 (interactive (list last-nonmenu-event))
7928 ;; In case this is run via the mouse, give temporary modes such as
7929 ;; isearch a chance to turn off.
7930 (run-hooks 'mouse-leave-buffer-hook)
7931 (with-current-buffer (window-buffer (posn-window (event-start event)))
7932 (let ((buffer completion-reference-buffer)
7933 (base-size completion-base-size)
7934 (base-position completion-base-position)
7935 (insert-function completion-list-insert-choice-function)
7936 (choice
7937 (save-excursion
7938 (goto-char (posn-point (event-start event)))
7939 (let (beg end)
7940 (cond
7941 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7942 (setq end (point) beg (1+ (point))))
7943 ((and (not (bobp))
7944 (get-text-property (1- (point)) 'mouse-face))
7945 (setq end (1- (point)) beg (point)))
7946 (t (error "No completion here")))
7947 (setq beg (previous-single-property-change beg 'mouse-face))
7948 (setq end (or (next-single-property-change end 'mouse-face)
7949 (point-max)))
7950 (buffer-substring-no-properties beg end)))))
7952 (unless (buffer-live-p buffer)
7953 (error "Destination buffer is dead"))
7954 (quit-window nil (posn-window (event-start event)))
7956 (with-current-buffer buffer
7957 (choose-completion-string
7958 choice buffer
7959 (or base-position
7960 (when base-size
7961 ;; Someone's using old completion code that doesn't know
7962 ;; about base-position yet.
7963 (list (+ base-size (field-beginning))))
7964 ;; If all else fails, just guess.
7965 (list (choose-completion-guess-base-position choice)))
7966 insert-function)))))
7968 ;; Delete the longest partial match for STRING
7969 ;; that can be found before POINT.
7970 (defun choose-completion-guess-base-position (string)
7971 (save-excursion
7972 (let ((opoint (point))
7973 len)
7974 ;; Try moving back by the length of the string.
7975 (goto-char (max (- (point) (length string))
7976 (minibuffer-prompt-end)))
7977 ;; See how far back we were actually able to move. That is the
7978 ;; upper bound on how much we can match and delete.
7979 (setq len (- opoint (point)))
7980 (if completion-ignore-case
7981 (setq string (downcase string)))
7982 (while (and (> len 0)
7983 (let ((tail (buffer-substring (point) opoint)))
7984 (if completion-ignore-case
7985 (setq tail (downcase tail)))
7986 (not (string= tail (substring string 0 len)))))
7987 (setq len (1- len))
7988 (forward-char 1))
7989 (point))))
7991 (defun choose-completion-delete-max-match (string)
7992 (declare (obsolete choose-completion-guess-base-position "23.2"))
7993 (delete-region (choose-completion-guess-base-position string) (point)))
7995 (defvar choose-completion-string-functions nil
7996 "Functions that may override the normal insertion of a completion choice.
7997 These functions are called in order with three arguments:
7998 CHOICE - the string to insert in the buffer,
7999 BUFFER - the buffer in which the choice should be inserted,
8000 BASE-POSITION - where to insert the completion.
8002 If a function in the list returns non-nil, that function is supposed
8003 to have inserted the CHOICE in the BUFFER, and possibly exited
8004 the minibuffer; no further functions will be called.
8006 If all functions in the list return nil, that means to use
8007 the default method of inserting the completion in BUFFER.")
8009 (defun choose-completion-string (choice &optional
8010 buffer base-position insert-function)
8011 "Switch to BUFFER and insert the completion choice CHOICE.
8012 BASE-POSITION says where to insert the completion.
8013 INSERT-FUNCTION says how to insert the completion and falls
8014 back on `completion-list-insert-choice-function' when nil."
8016 ;; If BUFFER is the minibuffer, exit the minibuffer
8017 ;; unless it is reading a file name and CHOICE is a directory,
8018 ;; or completion-no-auto-exit is non-nil.
8020 ;; Some older code may call us passing `base-size' instead of
8021 ;; `base-position'. It's difficult to make any use of `base-size',
8022 ;; so we just ignore it.
8023 (unless (consp base-position)
8024 (message "Obsolete `base-size' passed to choose-completion-string")
8025 (setq base-position nil))
8027 (let* ((buffer (or buffer completion-reference-buffer))
8028 (mini-p (minibufferp buffer)))
8029 ;; If BUFFER is a minibuffer, barf unless it's the currently
8030 ;; active minibuffer.
8031 (if (and mini-p
8032 (not (and (active-minibuffer-window)
8033 (equal buffer
8034 (window-buffer (active-minibuffer-window))))))
8035 (error "Minibuffer is not active for completion")
8036 ;; Set buffer so buffer-local choose-completion-string-functions works.
8037 (set-buffer buffer)
8038 (unless (run-hook-with-args-until-success
8039 'choose-completion-string-functions
8040 ;; The fourth arg used to be `mini-p' but was useless
8041 ;; (since minibufferp can be used on the `buffer' arg)
8042 ;; and indeed unused. The last used to be `base-size', so we
8043 ;; keep it to try and avoid breaking old code.
8044 choice buffer base-position nil)
8045 ;; This remove-text-properties should be unnecessary since `choice'
8046 ;; comes from buffer-substring-no-properties.
8047 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8048 ;; Insert the completion into the buffer where it was requested.
8049 (funcall (or insert-function completion-list-insert-choice-function)
8050 (or (car base-position) (point))
8051 (or (cadr base-position) (point))
8052 choice)
8053 ;; Update point in the window that BUFFER is showing in.
8054 (let ((window (get-buffer-window buffer t)))
8055 (set-window-point window (point)))
8056 ;; If completing for the minibuffer, exit it with this choice.
8057 (and (not completion-no-auto-exit)
8058 (minibufferp buffer)
8059 minibuffer-completion-table
8060 ;; If this is reading a file name, and the file name chosen
8061 ;; is a directory, don't exit the minibuffer.
8062 (let* ((result (buffer-substring (field-beginning) (point)))
8063 (bounds
8064 (completion-boundaries result minibuffer-completion-table
8065 minibuffer-completion-predicate
8066 "")))
8067 (if (eq (car bounds) (length result))
8068 ;; The completion chosen leads to a new set of completions
8069 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8070 (let ((mini (active-minibuffer-window)))
8071 (select-window mini)
8072 (when minibuffer-auto-raise
8073 (raise-frame (window-frame mini))))
8074 (exit-minibuffer))))))))
8076 (define-derived-mode completion-list-mode nil "Completion List"
8077 "Major mode for buffers showing lists of possible completions.
8078 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8079 to select the completion near point.
8080 Or click to select one with the mouse.
8082 \\{completion-list-mode-map}"
8083 (set (make-local-variable 'completion-base-size) nil))
8085 (defun completion-list-mode-finish ()
8086 "Finish setup of the completions buffer.
8087 Called from `temp-buffer-show-hook'."
8088 (when (eq major-mode 'completion-list-mode)
8089 (setq buffer-read-only t)))
8091 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8094 ;; Variables and faces used in `completion-setup-function'.
8096 (defcustom completion-show-help t
8097 "Non-nil means show help message in *Completions* buffer."
8098 :type 'boolean
8099 :version "22.1"
8100 :group 'completion)
8102 ;; This function goes in completion-setup-hook, so that it is called
8103 ;; after the text of the completion list buffer is written.
8104 (defun completion-setup-function ()
8105 (let* ((mainbuf (current-buffer))
8106 (base-dir
8107 ;; FIXME: This is a bad hack. We try to set the default-directory
8108 ;; in the *Completions* buffer so that the relative file names
8109 ;; displayed there can be treated as valid file names, independently
8110 ;; from the completion context. But this suffers from many problems:
8111 ;; - It's not clear when the completions are file names. With some
8112 ;; completion tables (e.g. bzr revision specs), the listed
8113 ;; completions can mix file names and other things.
8114 ;; - It doesn't pay attention to possible quoting.
8115 ;; - With fancy completion styles, the code below will not always
8116 ;; find the right base directory.
8117 (if minibuffer-completing-file-name
8118 (file-name-as-directory
8119 (expand-file-name
8120 (buffer-substring (minibuffer-prompt-end)
8121 (- (point) (or completion-base-size 0))))))))
8122 (with-current-buffer standard-output
8123 (let ((base-size completion-base-size) ;Read before killing localvars.
8124 (base-position completion-base-position)
8125 (insert-fun completion-list-insert-choice-function))
8126 (completion-list-mode)
8127 (set (make-local-variable 'completion-base-size) base-size)
8128 (set (make-local-variable 'completion-base-position) base-position)
8129 (set (make-local-variable 'completion-list-insert-choice-function)
8130 insert-fun))
8131 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8132 (if base-dir (setq default-directory base-dir))
8133 ;; Maybe insert help string.
8134 (when completion-show-help
8135 (goto-char (point-min))
8136 (if (display-mouse-p)
8137 (insert "Click on a completion to select it.\n"))
8138 (insert (substitute-command-keys
8139 "In this buffer, type \\[choose-completion] to \
8140 select the completion near point.\n\n"))))))
8142 (add-hook 'completion-setup-hook 'completion-setup-function)
8144 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8145 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8147 (defun switch-to-completions ()
8148 "Select the completion list window."
8149 (interactive)
8150 (let ((window (or (get-buffer-window "*Completions*" 0)
8151 ;; Make sure we have a completions window.
8152 (progn (minibuffer-completion-help)
8153 (get-buffer-window "*Completions*" 0)))))
8154 (when window
8155 (select-window window)
8156 ;; In the new buffer, go to the first completion.
8157 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8158 (when (bobp)
8159 (next-completion 1)))))
8161 ;;; Support keyboard commands to turn on various modifiers.
8163 ;; These functions -- which are not commands -- each add one modifier
8164 ;; to the following event.
8166 (defun event-apply-alt-modifier (_ignore-prompt)
8167 "\\<function-key-map>Add the Alt modifier to the following event.
8168 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8169 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8170 (defun event-apply-super-modifier (_ignore-prompt)
8171 "\\<function-key-map>Add the Super modifier to the following event.
8172 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8173 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8174 (defun event-apply-hyper-modifier (_ignore-prompt)
8175 "\\<function-key-map>Add the Hyper modifier to the following event.
8176 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8177 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8178 (defun event-apply-shift-modifier (_ignore-prompt)
8179 "\\<function-key-map>Add the Shift modifier to the following event.
8180 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8181 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8182 (defun event-apply-control-modifier (_ignore-prompt)
8183 "\\<function-key-map>Add the Ctrl modifier to the following event.
8184 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8185 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8186 (defun event-apply-meta-modifier (_ignore-prompt)
8187 "\\<function-key-map>Add the Meta modifier to the following event.
8188 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8189 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8191 (defun event-apply-modifier (event symbol lshiftby prefix)
8192 "Apply a modifier flag to event EVENT.
8193 SYMBOL is the name of this modifier, as a symbol.
8194 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8195 PREFIX is the string that represents this modifier in an event type symbol."
8196 (if (numberp event)
8197 (cond ((eq symbol 'control)
8198 (if (and (<= (downcase event) ?z)
8199 (>= (downcase event) ?a))
8200 (- (downcase event) ?a -1)
8201 (if (and (<= (downcase event) ?Z)
8202 (>= (downcase event) ?A))
8203 (- (downcase event) ?A -1)
8204 (logior (lsh 1 lshiftby) event))))
8205 ((eq symbol 'shift)
8206 (if (and (<= (downcase event) ?z)
8207 (>= (downcase event) ?a))
8208 (upcase event)
8209 (logior (lsh 1 lshiftby) event)))
8211 (logior (lsh 1 lshiftby) event)))
8212 (if (memq symbol (event-modifiers event))
8213 event
8214 (let ((event-type (if (symbolp event) event (car event))))
8215 (setq event-type (intern (concat prefix (symbol-name event-type))))
8216 (if (symbolp event)
8217 event-type
8218 (cons event-type (cdr event)))))))
8220 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8221 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8222 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8223 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8224 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8225 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8227 ;;;; Keypad support.
8229 ;; Make the keypad keys act like ordinary typing keys. If people add
8230 ;; bindings for the function key symbols, then those bindings will
8231 ;; override these, so this shouldn't interfere with any existing
8232 ;; bindings.
8234 ;; Also tell read-char how to handle these keys.
8235 (mapc
8236 (lambda (keypad-normal)
8237 (let ((keypad (nth 0 keypad-normal))
8238 (normal (nth 1 keypad-normal)))
8239 (put keypad 'ascii-character normal)
8240 (define-key function-key-map (vector keypad) (vector normal))))
8241 ;; See also kp-keys bound in bindings.el.
8242 '((kp-space ?\s)
8243 (kp-tab ?\t)
8244 (kp-enter ?\r)
8245 (kp-separator ?,)
8246 (kp-equal ?=)
8247 ;; Do the same for various keys that are represented as symbols under
8248 ;; GUIs but naturally correspond to characters.
8249 (backspace 127)
8250 (delete 127)
8251 (tab ?\t)
8252 (linefeed ?\n)
8253 (clear ?\C-l)
8254 (return ?\C-m)
8255 (escape ?\e)
8258 ;;;;
8259 ;;;; forking a twin copy of a buffer.
8260 ;;;;
8262 (defvar clone-buffer-hook nil
8263 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8265 (defvar clone-indirect-buffer-hook nil
8266 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8268 (defun clone-process (process &optional newname)
8269 "Create a twin copy of PROCESS.
8270 If NEWNAME is nil, it defaults to PROCESS' name;
8271 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8272 If PROCESS is associated with a buffer, the new process will be associated
8273 with the current buffer instead.
8274 Returns nil if PROCESS has already terminated."
8275 (setq newname (or newname (process-name process)))
8276 (if (string-match "<[0-9]+>\\'" newname)
8277 (setq newname (substring newname 0 (match-beginning 0))))
8278 (when (memq (process-status process) '(run stop open))
8279 (let* ((process-connection-type (process-tty-name process))
8280 (new-process
8281 (if (memq (process-status process) '(open))
8282 (let ((args (process-contact process t)))
8283 (setq args (plist-put args :name newname))
8284 (setq args (plist-put args :buffer
8285 (if (process-buffer process)
8286 (current-buffer))))
8287 (apply 'make-network-process args))
8288 (apply 'start-process newname
8289 (if (process-buffer process) (current-buffer))
8290 (process-command process)))))
8291 (set-process-query-on-exit-flag
8292 new-process (process-query-on-exit-flag process))
8293 (set-process-inherit-coding-system-flag
8294 new-process (process-inherit-coding-system-flag process))
8295 (set-process-filter new-process (process-filter process))
8296 (set-process-sentinel new-process (process-sentinel process))
8297 (set-process-plist new-process (copy-sequence (process-plist process)))
8298 new-process)))
8300 ;; things to maybe add (currently partly covered by `funcall mode'):
8301 ;; - syntax-table
8302 ;; - overlays
8303 (defun clone-buffer (&optional newname display-flag)
8304 "Create and return a twin copy of the current buffer.
8305 Unlike an indirect buffer, the new buffer can be edited
8306 independently of the old one (if it is not read-only).
8307 NEWNAME is the name of the new buffer. It may be modified by
8308 adding or incrementing <N> at the end as necessary to create a
8309 unique buffer name. If nil, it defaults to the name of the
8310 current buffer, with the proper suffix. If DISPLAY-FLAG is
8311 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8312 clone a file-visiting buffer, or a buffer whose major mode symbol
8313 has a non-nil `no-clone' property, results in an error.
8315 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8316 current buffer with appropriate suffix. However, if a prefix
8317 argument is given, then the command prompts for NEWNAME in the
8318 minibuffer.
8320 This runs the normal hook `clone-buffer-hook' in the new buffer
8321 after it has been set up properly in other respects."
8322 (interactive
8323 (progn
8324 (if buffer-file-name
8325 (error "Cannot clone a file-visiting buffer"))
8326 (if (get major-mode 'no-clone)
8327 (error "Cannot clone a buffer in %s mode" mode-name))
8328 (list (if current-prefix-arg
8329 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8330 t)))
8331 (if buffer-file-name
8332 (error "Cannot clone a file-visiting buffer"))
8333 (if (get major-mode 'no-clone)
8334 (error "Cannot clone a buffer in %s mode" mode-name))
8335 (setq newname (or newname (buffer-name)))
8336 (if (string-match "<[0-9]+>\\'" newname)
8337 (setq newname (substring newname 0 (match-beginning 0))))
8338 (let ((buf (current-buffer))
8339 (ptmin (point-min))
8340 (ptmax (point-max))
8341 (pt (point))
8342 (mk (if mark-active (mark t)))
8343 (modified (buffer-modified-p))
8344 (mode major-mode)
8345 (lvars (buffer-local-variables))
8346 (process (get-buffer-process (current-buffer)))
8347 (new (generate-new-buffer (or newname (buffer-name)))))
8348 (save-restriction
8349 (widen)
8350 (with-current-buffer new
8351 (insert-buffer-substring buf)))
8352 (with-current-buffer new
8353 (narrow-to-region ptmin ptmax)
8354 (goto-char pt)
8355 (if mk (set-mark mk))
8356 (set-buffer-modified-p modified)
8358 ;; Clone the old buffer's process, if any.
8359 (when process (clone-process process))
8361 ;; Now set up the major mode.
8362 (funcall mode)
8364 ;; Set up other local variables.
8365 (mapc (lambda (v)
8366 (condition-case () ;in case var is read-only
8367 (if (symbolp v)
8368 (makunbound v)
8369 (set (make-local-variable (car v)) (cdr v)))
8370 (error nil)))
8371 lvars)
8373 ;; Run any hooks (typically set up by the major mode
8374 ;; for cloning to work properly).
8375 (run-hooks 'clone-buffer-hook))
8376 (if display-flag
8377 ;; Presumably the current buffer is shown in the selected frame, so
8378 ;; we want to display the clone elsewhere.
8379 (let ((same-window-regexps nil)
8380 (same-window-buffer-names))
8381 (pop-to-buffer new)))
8382 new))
8385 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8386 "Create an indirect buffer that is a twin copy of the current buffer.
8388 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8389 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8390 or if not called with a prefix arg, NEWNAME defaults to the current
8391 buffer's name. The name is modified by adding a `<N>' suffix to it
8392 or by incrementing the N in an existing suffix. Trying to clone a
8393 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8394 property results in an error.
8396 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8397 This is always done when called interactively.
8399 Optional third arg NORECORD non-nil means do not put this buffer at the
8400 front of the list of recently selected ones.
8402 Returns the newly created indirect buffer."
8403 (interactive
8404 (progn
8405 (if (get major-mode 'no-clone-indirect)
8406 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8407 (list (if current-prefix-arg
8408 (read-buffer "Name of indirect buffer: " (current-buffer)))
8409 t)))
8410 (if (get major-mode 'no-clone-indirect)
8411 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8412 (setq newname (or newname (buffer-name)))
8413 (if (string-match "<[0-9]+>\\'" newname)
8414 (setq newname (substring newname 0 (match-beginning 0))))
8415 (let* ((name (generate-new-buffer-name newname))
8416 (buffer (make-indirect-buffer (current-buffer) name t)))
8417 (with-current-buffer buffer
8418 (run-hooks 'clone-indirect-buffer-hook))
8419 (when display-flag
8420 (pop-to-buffer buffer nil norecord))
8421 buffer))
8424 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8425 "Like `clone-indirect-buffer' but display in another window."
8426 (interactive
8427 (progn
8428 (if (get major-mode 'no-clone-indirect)
8429 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8430 (list (if current-prefix-arg
8431 (read-buffer "Name of indirect buffer: " (current-buffer)))
8432 t)))
8433 (let ((pop-up-windows t))
8434 (clone-indirect-buffer newname display-flag norecord)))
8437 ;;; Handling of Backspace and Delete keys.
8439 (defcustom normal-erase-is-backspace 'maybe
8440 "Set the default behavior of the Delete and Backspace keys.
8442 If set to t, Delete key deletes forward and Backspace key deletes
8443 backward.
8445 If set to nil, both Delete and Backspace keys delete backward.
8447 If set to `maybe' (which is the default), Emacs automatically
8448 selects a behavior. On window systems, the behavior depends on
8449 the keyboard used. If the keyboard has both a Backspace key and
8450 a Delete key, and both are mapped to their usual meanings, the
8451 option's default value is set to t, so that Backspace can be used
8452 to delete backward, and Delete can be used to delete forward.
8454 If not running under a window system, customizing this option
8455 accomplishes a similar effect by mapping C-h, which is usually
8456 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8457 via `keyboard-translate'. The former functionality of C-h is
8458 available on the F1 key. You should probably not use this
8459 setting if you don't have both Backspace, Delete and F1 keys.
8461 Setting this variable with setq doesn't take effect. Programmatically,
8462 call `normal-erase-is-backspace-mode' (which see) instead."
8463 :type '(choice (const :tag "Off" nil)
8464 (const :tag "Maybe" maybe)
8465 (other :tag "On" t))
8466 :group 'editing-basics
8467 :version "21.1"
8468 :set (lambda (symbol value)
8469 ;; The fboundp is because of a problem with :set when
8470 ;; dumping Emacs. It doesn't really matter.
8471 (if (fboundp 'normal-erase-is-backspace-mode)
8472 (normal-erase-is-backspace-mode (or value 0))
8473 (set-default symbol value))))
8475 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8476 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8477 (unless frame (setq frame (selected-frame)))
8478 (with-selected-frame frame
8479 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8480 (normal-erase-is-backspace-mode
8481 (if (if (eq normal-erase-is-backspace 'maybe)
8482 (and (not noninteractive)
8483 (or (memq system-type '(ms-dos windows-nt))
8484 (memq window-system '(w32 ns))
8485 (and (memq window-system '(x))
8486 (fboundp 'x-backspace-delete-keys-p)
8487 (x-backspace-delete-keys-p))
8488 ;; If the terminal Emacs is running on has erase char
8489 ;; set to ^H, use the Backspace key for deleting
8490 ;; backward, and the Delete key for deleting forward.
8491 (and (null window-system)
8492 (eq tty-erase-char ?\^H))))
8493 normal-erase-is-backspace)
8494 1 0)))))
8496 (define-minor-mode normal-erase-is-backspace-mode
8497 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8498 With a prefix argument ARG, enable this feature if ARG is
8499 positive, and disable it otherwise. If called from Lisp, enable
8500 the mode if ARG is omitted or nil.
8502 On window systems, when this mode is on, Delete is mapped to C-d
8503 and Backspace is mapped to DEL; when this mode is off, both
8504 Delete and Backspace are mapped to DEL. (The remapping goes via
8505 `local-function-key-map', so binding Delete or Backspace in the
8506 global or local keymap will override that.)
8508 In addition, on window systems, the bindings of C-Delete, M-Delete,
8509 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8510 the global keymap in accordance with the functionality of Delete and
8511 Backspace. For example, if Delete is remapped to C-d, which deletes
8512 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8513 to DEL, which deletes backward, C-Delete is bound to
8514 `backward-kill-word'.
8516 If not running on a window system, a similar effect is accomplished by
8517 remapping C-h (normally produced by the Backspace key) and DEL via
8518 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8519 to C-d; if it's off, the keys are not remapped.
8521 When not running on a window system, and this mode is turned on, the
8522 former functionality of C-h is available on the F1 key. You should
8523 probably not turn on this mode on a text-only terminal if you don't
8524 have both Backspace, Delete and F1 keys.
8526 See also `normal-erase-is-backspace'."
8527 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8528 . (lambda (v)
8529 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8530 (if v 1 0))))
8531 (let ((enabled (eq 1 (terminal-parameter
8532 nil 'normal-erase-is-backspace))))
8534 (cond ((or (memq window-system '(x w32 ns pc))
8535 (memq system-type '(ms-dos windows-nt)))
8536 (let ((bindings
8537 `(([M-delete] [M-backspace])
8538 ([C-M-delete] [C-M-backspace])
8539 ([?\e C-delete] [?\e C-backspace]))))
8541 (if enabled
8542 (progn
8543 (define-key local-function-key-map [delete] [deletechar])
8544 (define-key local-function-key-map [kp-delete] [deletechar])
8545 (define-key local-function-key-map [backspace] [?\C-?])
8546 (dolist (b bindings)
8547 ;; Not sure if input-decode-map is really right, but
8548 ;; keyboard-translate-table (used below) only works
8549 ;; for integer events, and key-translation-table is
8550 ;; global (like the global-map, used earlier).
8551 (define-key input-decode-map (car b) nil)
8552 (define-key input-decode-map (cadr b) nil)))
8553 (define-key local-function-key-map [delete] [?\C-?])
8554 (define-key local-function-key-map [kp-delete] [?\C-?])
8555 (define-key local-function-key-map [backspace] [?\C-?])
8556 (dolist (b bindings)
8557 (define-key input-decode-map (car b) (cadr b))
8558 (define-key input-decode-map (cadr b) (car b))))))
8560 (if enabled
8561 (progn
8562 (keyboard-translate ?\C-h ?\C-?)
8563 (keyboard-translate ?\C-? ?\C-d))
8564 (keyboard-translate ?\C-h ?\C-h)
8565 (keyboard-translate ?\C-? ?\C-?))))
8567 (if (called-interactively-p 'interactive)
8568 (message "Delete key deletes %s"
8569 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8570 "forward" "backward")))))
8572 (defvar vis-mode-saved-buffer-invisibility-spec nil
8573 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8575 (define-minor-mode read-only-mode
8576 "Change whether the current buffer is read-only.
8577 With prefix argument ARG, make the buffer read-only if ARG is
8578 positive, otherwise make it writable. If buffer is read-only
8579 and `view-read-only' is non-nil, enter view mode.
8581 Do not call this from a Lisp program unless you really intend to
8582 do the same thing as the \\[read-only-mode] command, including
8583 possibly enabling or disabling View mode. Also, note that this
8584 command works by setting the variable `buffer-read-only', which
8585 does not affect read-only regions caused by text properties. To
8586 ignore read-only status in a Lisp program (whether due to text
8587 properties or buffer state), bind `inhibit-read-only' temporarily
8588 to a non-nil value."
8589 :variable buffer-read-only
8590 (cond
8591 ((and (not buffer-read-only) view-mode)
8592 (View-exit-and-edit)
8593 (make-local-variable 'view-read-only)
8594 (setq view-read-only t)) ; Must leave view mode.
8595 ((and buffer-read-only view-read-only
8596 ;; If view-mode is already active, `view-mode-enter' is a nop.
8597 (not view-mode)
8598 (not (eq (get major-mode 'mode-class) 'special)))
8599 (view-mode-enter))))
8601 (define-minor-mode visible-mode
8602 "Toggle making all invisible text temporarily visible (Visible mode).
8603 With a prefix argument ARG, enable Visible mode if ARG is
8604 positive, and disable it otherwise. If called from Lisp, enable
8605 the mode if ARG is omitted or nil.
8607 This mode works by saving the value of `buffer-invisibility-spec'
8608 and setting it to nil."
8609 :lighter " Vis"
8610 :group 'editing-basics
8611 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8612 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8613 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8614 (when visible-mode
8615 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8616 buffer-invisibility-spec)
8617 (setq buffer-invisibility-spec nil)))
8619 (defvar messages-buffer-mode-map
8620 (let ((map (make-sparse-keymap)))
8621 (set-keymap-parent map special-mode-map)
8622 (define-key map "g" nil) ; nothing to revert
8623 map))
8625 (define-derived-mode messages-buffer-mode special-mode "Messages"
8626 "Major mode used in the \"*Messages*\" buffer.")
8628 (defun messages-buffer ()
8629 "Return the \"*Messages*\" buffer.
8630 If it does not exist, create and it switch it to `messages-buffer-mode'."
8631 (or (get-buffer "*Messages*")
8632 (with-current-buffer (get-buffer-create "*Messages*")
8633 (messages-buffer-mode)
8634 (current-buffer))))
8637 ;; Minibuffer prompt stuff.
8639 ;;(defun minibuffer-prompt-modification (start end)
8640 ;; (error "You cannot modify the prompt"))
8643 ;;(defun minibuffer-prompt-insertion (start end)
8644 ;; (let ((inhibit-modification-hooks t))
8645 ;; (delete-region start end)
8646 ;; ;; Discard undo information for the text insertion itself
8647 ;; ;; and for the text deletion.above.
8648 ;; (when (consp buffer-undo-list)
8649 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8650 ;; (message "You cannot modify the prompt")))
8653 ;;(setq minibuffer-prompt-properties
8654 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8655 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8658 ;;;; Problematic external packages.
8660 ;; rms says this should be done by specifying symbols that define
8661 ;; versions together with bad values. This is therefore not as
8662 ;; flexible as it could be. See the thread:
8663 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8664 (defconst bad-packages-alist
8665 ;; Not sure exactly which semantic versions have problems.
8666 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8667 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8668 "The version of `semantic' loaded does not work in Emacs 22.
8669 It can cause constant high CPU load.
8670 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8671 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8672 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8673 ;; provided the `CUA-mode' feature. Since this is no longer true,
8674 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8675 (CUA-mode t nil
8676 "CUA-mode is now part of the standard GNU Emacs distribution,
8677 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8679 You have loaded an older version of CUA-mode which does not work
8680 correctly with this version of Emacs. You should remove the old
8681 version and use the one distributed with Emacs."))
8682 "Alist of packages known to cause problems in this version of Emacs.
8683 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8684 PACKAGE is either a regular expression to match file names, or a
8685 symbol (a feature name), like for `with-eval-after-load'.
8686 SYMBOL is either the name of a string variable, or t. Upon
8687 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8688 warning using STRING as the message.")
8690 (defun bad-package-check (package)
8691 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8692 (condition-case nil
8693 (let* ((list (assoc package bad-packages-alist))
8694 (symbol (nth 1 list)))
8695 (and list
8696 (boundp symbol)
8697 (or (eq symbol t)
8698 (and (stringp (setq symbol (eval symbol)))
8699 (string-match-p (nth 2 list) symbol)))
8700 (display-warning package (nth 3 list) :warning)))
8701 (error nil)))
8703 (dolist (elem bad-packages-alist)
8704 (let ((pkg (car elem)))
8705 (with-eval-after-load pkg
8706 (bad-package-check pkg))))
8709 ;;; Generic dispatcher commands
8711 ;; Macro `define-alternatives' is used to create generic commands.
8712 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8713 ;; that can have different alternative implementations where choosing
8714 ;; among them is exclusively a matter of user preference.
8716 ;; (define-alternatives COMMAND) creates a new interactive command
8717 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8718 ;; Typically, the user will not need to customize this variable; packages
8719 ;; wanting to add alternative implementations should use
8721 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8723 (defmacro define-alternatives (command &rest customizations)
8724 "Define the new command `COMMAND'.
8726 The argument `COMMAND' should be a symbol.
8728 Running `M-x COMMAND RET' for the first time prompts for which
8729 alternative to use and records the selected command as a custom
8730 variable.
8732 Running `C-u M-x COMMAND RET' prompts again for an alternative
8733 and overwrites the previous choice.
8735 The variable `COMMAND-alternatives' contains an alist with
8736 alternative implementations of COMMAND. `define-alternatives'
8737 does not have any effect until this variable is set.
8739 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8740 `defcustom' keywords and values to add to the declaration of
8741 `COMMAND-alternatives' (typically :group and :version)."
8742 (let* ((command-name (symbol-name command))
8743 (varalt-name (concat command-name "-alternatives"))
8744 (varalt-sym (intern varalt-name))
8745 (varimp-sym (intern (concat command-name "--implementation"))))
8746 `(progn
8748 (defcustom ,varalt-sym nil
8749 ,(format "Alist of alternative implementations for the `%s' command.
8751 Each entry must be a pair (ALTNAME . ALTFUN), where:
8752 ALTNAME - The name shown at user to describe the alternative implementation.
8753 ALTFUN - The function called to implement this alternative."
8754 command-name)
8755 :type '(alist :key-type string :value-type function)
8756 ,@customizations)
8758 (put ',varalt-sym 'definition-name ',command)
8759 (defvar ,varimp-sym nil "Internal use only.")
8761 (defun ,command (&optional arg)
8762 ,(format "Run generic command `%s'.
8763 If used for the first time, or with interactive ARG, ask the user which
8764 implementation to use for `%s'. The variable `%s'
8765 contains the list of implementations currently supported for this command."
8766 command-name command-name varalt-name)
8767 (interactive "P")
8768 (when (or arg (null ,varimp-sym))
8769 (let ((val (completing-read
8770 ,(format-message
8771 "Select implementation for command `%s': "
8772 command-name)
8773 ,varalt-sym nil t)))
8774 (unless (string-equal val "")
8775 (when (null ,varimp-sym)
8776 (message
8777 "Use C-u M-x %s RET`to select another implementation"
8778 ,command-name)
8779 (sit-for 3))
8780 (customize-save-variable ',varimp-sym
8781 (cdr (assoc-string val ,varalt-sym))))))
8782 (if ,varimp-sym
8783 (call-interactively ,varimp-sym)
8784 (message "%s" ,(format-message
8785 "No implementation selected for command `%s'"
8786 command-name)))))))
8789 ;;; Functions for changing capitalization that Do What I Mean
8790 (defun upcase-dwim (arg)
8791 "Upcase words in the region, if active; if not, upcase word at point.
8792 If the region is active, this function calls `upcase-region'.
8793 Otherwise, it calls `upcase-word', with prefix argument passed to it
8794 to upcase ARG words."
8795 (interactive "*p")
8796 (if (use-region-p)
8797 (upcase-region (region-beginning) (region-end))
8798 (upcase-word arg)))
8800 (defun downcase-dwim (arg)
8801 "Downcase words in the region, if active; if not, downcase word at point.
8802 If the region is active, this function calls `downcase-region'.
8803 Otherwise, it calls `downcase-word', with prefix argument passed to it
8804 to downcase ARG words."
8805 (interactive "*p")
8806 (if (use-region-p)
8807 (downcase-region (region-beginning) (region-end))
8808 (downcase-word arg)))
8810 (defun capitalize-dwim (arg)
8811 "Capitalize words in the region, if active; if not, capitalize word at point.
8812 If the region is active, this function calls `capitalize-region'.
8813 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8814 to capitalize ARG words."
8815 (interactive "*p")
8816 (if (use-region-p)
8817 (capitalize-region (region-beginning) (region-end))
8818 (capitalize-word arg)))
8822 (provide 'simple)
8824 ;;; simple.el ends here