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