Fix duckduckgo imagemagick crash
[emacs.git] / lisp / simple.el
blob16f03d2e5f947bdb5718e6d8badc4ce432deaa24
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2013 Free Software Foundation, Inc.
5 ;; Maintainer: FSF
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 (declare-function widget-convert "wid-edit" (type &rest args))
32 (declare-function shell-mode "shell" ())
34 ;;; From compile.el
35 (defvar compilation-current-error)
36 (defvar compilation-context-lines)
38 (defcustom idle-update-delay 0.5
39 "Idle time delay before updating various things on the screen.
40 Various Emacs features that update auxiliary information when point moves
41 wait this many seconds after Emacs becomes idle before doing an update."
42 :type 'number
43 :group 'display
44 :version "22.1")
46 (defgroup killing nil
47 "Killing and yanking commands."
48 :group 'editing)
50 (defgroup paren-matching nil
51 "Highlight (un)matching of parens and expressions."
52 :group 'matching)
54 ;;; next-error support framework
56 (defgroup next-error nil
57 "`next-error' support framework."
58 :group 'compilation
59 :version "22.1")
61 (defface next-error
62 '((t (:inherit region)))
63 "Face used to highlight next error locus."
64 :group 'next-error
65 :version "22.1")
67 (defcustom next-error-highlight 0.5
68 "Highlighting of locations in selected source buffers.
69 If a number, highlight the locus in `next-error' face for the given time
70 in seconds, or until the next command is executed.
71 If t, highlight the locus until the next command is executed, or until
72 some other locus replaces it.
73 If nil, don't highlight the locus in the source buffer.
74 If `fringe-arrow', indicate the locus by the fringe arrow
75 indefinitely until some other locus replaces it."
76 :type '(choice (number :tag "Highlight for specified time")
77 (const :tag "Semipermanent highlighting" t)
78 (const :tag "No highlighting" nil)
79 (const :tag "Fringe arrow" fringe-arrow))
80 :group 'next-error
81 :version "22.1")
83 (defcustom next-error-highlight-no-select 0.5
84 "Highlighting of locations in `next-error-no-select'.
85 If number, highlight the locus in `next-error' face for given time in seconds.
86 If t, highlight the locus indefinitely until some other locus replaces it.
87 If nil, don't highlight the locus in the source buffer.
88 If `fringe-arrow', indicate the locus by the fringe arrow
89 indefinitely until some other locus replaces it."
90 :type '(choice (number :tag "Highlight for specified time")
91 (const :tag "Semipermanent highlighting" t)
92 (const :tag "No highlighting" nil)
93 (const :tag "Fringe arrow" fringe-arrow))
94 :group 'next-error
95 :version "22.1")
97 (defcustom next-error-recenter nil
98 "Display the line in the visited source file recentered as specified.
99 If non-nil, the value is passed directly to `recenter'."
100 :type '(choice (integer :tag "Line to recenter to")
101 (const :tag "Center of window" (4))
102 (const :tag "No recentering" nil))
103 :group 'next-error
104 :version "23.1")
106 (defcustom next-error-hook nil
107 "List of hook functions run by `next-error' after visiting source file."
108 :type 'hook
109 :group 'next-error)
111 (defvar next-error-highlight-timer nil)
113 (defvar next-error-overlay-arrow-position nil)
114 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
115 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
117 (defvar next-error-last-buffer nil
118 "The most recent `next-error' buffer.
119 A buffer becomes most recent when its compilation, grep, or
120 similar mode is started, or when it is used with \\[next-error]
121 or \\[compile-goto-error].")
123 (defvar next-error-function nil
124 "Function to use to find the next error in the current buffer.
125 The function is called with 2 parameters:
126 ARG is an integer specifying by how many errors to move.
127 RESET is a boolean which, if non-nil, says to go back to the beginning
128 of the errors before moving.
129 Major modes providing compile-like functionality should set this variable
130 to indicate to `next-error' that this is a candidate buffer and how
131 to navigate in it.")
132 (make-variable-buffer-local 'next-error-function)
134 (defvar next-error-move-function nil
135 "Function to use to move to an error locus.
136 It takes two arguments, a buffer position in the error buffer
137 and a buffer position in the error locus buffer.
138 The buffer for the error locus should already be current.
139 nil means use goto-char using the second argument position.")
140 (make-variable-buffer-local 'next-error-move-function)
142 (defsubst next-error-buffer-p (buffer
143 &optional avoid-current
144 extra-test-inclusive
145 extra-test-exclusive)
146 "Test if BUFFER is a `next-error' capable buffer.
148 If AVOID-CURRENT is non-nil, treat the current buffer
149 as an absolute last resort only.
151 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
152 that normally would not qualify. If it returns t, the buffer
153 in question is treated as usable.
155 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
156 that would normally be considered usable. If it returns nil,
157 that buffer is rejected."
158 (and (buffer-name buffer) ;First make sure it's live.
159 (not (and avoid-current (eq buffer (current-buffer))))
160 (with-current-buffer buffer
161 (if next-error-function ; This is the normal test.
162 ;; Optionally reject some buffers.
163 (if extra-test-exclusive
164 (funcall extra-test-exclusive)
166 ;; Optionally accept some other buffers.
167 (and extra-test-inclusive
168 (funcall extra-test-inclusive))))))
170 (defun next-error-find-buffer (&optional avoid-current
171 extra-test-inclusive
172 extra-test-exclusive)
173 "Return a `next-error' capable buffer.
175 If AVOID-CURRENT is non-nil, treat the current buffer
176 as an absolute last resort only.
178 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
179 that normally would not qualify. If it returns t, the buffer
180 in question is treated as usable.
182 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
183 that would normally be considered usable. If it returns nil,
184 that buffer is rejected."
186 ;; 1. If one window on the selected frame displays such buffer, return it.
187 (let ((window-buffers
188 (delete-dups
189 (delq nil (mapcar (lambda (w)
190 (if (next-error-buffer-p
191 (window-buffer w)
192 avoid-current
193 extra-test-inclusive extra-test-exclusive)
194 (window-buffer w)))
195 (window-list))))))
196 (if (eq (length window-buffers) 1)
197 (car window-buffers)))
198 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
199 (if (and next-error-last-buffer
200 (next-error-buffer-p next-error-last-buffer avoid-current
201 extra-test-inclusive extra-test-exclusive))
202 next-error-last-buffer)
203 ;; 3. If the current buffer is acceptable, choose it.
204 (if (next-error-buffer-p (current-buffer) avoid-current
205 extra-test-inclusive extra-test-exclusive)
206 (current-buffer))
207 ;; 4. Look for any acceptable buffer.
208 (let ((buffers (buffer-list)))
209 (while (and buffers
210 (not (next-error-buffer-p
211 (car buffers) avoid-current
212 extra-test-inclusive extra-test-exclusive)))
213 (setq buffers (cdr buffers)))
214 (car buffers))
215 ;; 5. Use the current buffer as a last resort if it qualifies,
216 ;; even despite AVOID-CURRENT.
217 (and avoid-current
218 (next-error-buffer-p (current-buffer) nil
219 extra-test-inclusive extra-test-exclusive)
220 (progn
221 (message "This is the only buffer with error message locations")
222 (current-buffer)))
223 ;; 6. Give up.
224 (error "No buffers contain error message locations")))
226 (defun next-error (&optional arg reset)
227 "Visit next `next-error' message and corresponding source code.
229 If all the error messages parsed so far have been processed already,
230 the message buffer is checked for new ones.
232 A prefix ARG specifies how many error messages to move;
233 negative means move back to previous error messages.
234 Just \\[universal-argument] as a prefix means reparse the error message buffer
235 and start at the first error.
237 The RESET argument specifies that we should restart from the beginning.
239 \\[next-error] normally uses the most recently started
240 compilation, grep, or occur buffer. It can also operate on any
241 buffer with output from the \\[compile], \\[grep] commands, or,
242 more generally, on any buffer in Compilation mode or with
243 Compilation Minor mode enabled, or any buffer in which
244 `next-error-function' is bound to an appropriate function.
245 To specify use of a particular buffer for error messages, type
246 \\[next-error] in that buffer when it is the only one displayed
247 in the current frame.
249 Once \\[next-error] has chosen the buffer for error messages, it
250 runs `next-error-hook' with `run-hooks', and stays with that buffer
251 until you use it in some other buffer which uses Compilation mode
252 or Compilation Minor mode.
254 To control which errors are matched, customize the variable
255 `compilation-error-regexp-alist'."
256 (interactive "P")
257 (if (consp arg) (setq reset t arg nil))
258 (when (setq next-error-last-buffer (next-error-find-buffer))
259 ;; we know here that next-error-function is a valid symbol we can funcall
260 (with-current-buffer next-error-last-buffer
261 (funcall next-error-function (prefix-numeric-value arg) reset)
262 (when next-error-recenter
263 (recenter next-error-recenter))
264 (run-hooks 'next-error-hook))))
266 (defun next-error-internal ()
267 "Visit the source code corresponding to the `next-error' message at point."
268 (setq next-error-last-buffer (current-buffer))
269 ;; we know here that next-error-function is a valid symbol we can funcall
270 (with-current-buffer next-error-last-buffer
271 (funcall next-error-function 0 nil)
272 (when next-error-recenter
273 (recenter next-error-recenter))
274 (run-hooks 'next-error-hook)))
276 (defalias 'goto-next-locus 'next-error)
277 (defalias 'next-match 'next-error)
279 (defun previous-error (&optional n)
280 "Visit previous `next-error' message and corresponding source code.
282 Prefix arg N says how many error messages to move backwards (or
283 forwards, if negative).
285 This operates on the output from the \\[compile] and \\[grep] commands."
286 (interactive "p")
287 (next-error (- (or n 1))))
289 (defun first-error (&optional n)
290 "Restart at the first error.
291 Visit corresponding source code.
292 With prefix arg N, visit the source code of the Nth error.
293 This operates on the output from the \\[compile] command, for instance."
294 (interactive "p")
295 (next-error n t))
297 (defun next-error-no-select (&optional n)
298 "Move point to the next error in the `next-error' buffer and highlight match.
299 Prefix arg N says how many error messages to move forwards (or
300 backwards, if negative).
301 Finds and highlights the source line like \\[next-error], but does not
302 select the source buffer."
303 (interactive "p")
304 (let ((next-error-highlight next-error-highlight-no-select))
305 (next-error n))
306 (pop-to-buffer next-error-last-buffer))
308 (defun previous-error-no-select (&optional n)
309 "Move point to the previous error in the `next-error' buffer and highlight match.
310 Prefix arg N says how many error messages to move backwards (or
311 forwards, if negative).
312 Finds and highlights the source line like \\[previous-error], but does not
313 select the source buffer."
314 (interactive "p")
315 (next-error-no-select (- (or n 1))))
317 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
318 (defvar next-error-follow-last-line nil)
320 (define-minor-mode next-error-follow-minor-mode
321 "Minor mode for compilation, occur and diff modes.
322 With a prefix argument ARG, enable mode if ARG is positive, and
323 disable it otherwise. If called from Lisp, enable mode if ARG is
324 omitted or nil.
325 When turned on, cursor motion in the compilation, grep, occur or diff
326 buffer causes automatic display of the corresponding source code location."
327 :group 'next-error :init-value nil :lighter " Fol"
328 (if (not next-error-follow-minor-mode)
329 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
330 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
331 (make-local-variable 'next-error-follow-last-line)))
333 ;; Used as a `post-command-hook' by `next-error-follow-mode'
334 ;; for the *Compilation* *grep* and *Occur* buffers.
335 (defun next-error-follow-mode-post-command-hook ()
336 (unless (equal next-error-follow-last-line (line-number-at-pos))
337 (setq next-error-follow-last-line (line-number-at-pos))
338 (condition-case nil
339 (let ((compilation-context-lines nil))
340 (setq compilation-current-error (point))
341 (next-error-no-select 0))
342 (error t))))
347 (defun fundamental-mode ()
348 "Major mode not specialized for anything in particular.
349 Other major modes are defined by comparison with this one."
350 (interactive)
351 (kill-all-local-variables)
352 (run-mode-hooks))
354 ;; Special major modes to view specially formatted data rather than files.
356 (defvar special-mode-map
357 (let ((map (make-sparse-keymap)))
358 (suppress-keymap map)
359 (define-key map "q" 'quit-window)
360 (define-key map " " 'scroll-up-command)
361 (define-key map [?\S-\ ] 'scroll-down-command)
362 (define-key map "\C-?" 'scroll-down-command)
363 (define-key map "?" 'describe-mode)
364 (define-key map "h" 'describe-mode)
365 (define-key map ">" 'end-of-buffer)
366 (define-key map "<" 'beginning-of-buffer)
367 (define-key map "g" 'revert-buffer)
368 map))
370 (put 'special-mode 'mode-class 'special)
371 (define-derived-mode special-mode nil "Special"
372 "Parent major mode from which special major modes should inherit."
373 (setq buffer-read-only t))
375 ;; Making and deleting lines.
377 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
378 "Propertized string representing a hard newline character.")
380 (defun newline (&optional arg interactive)
381 "Insert a newline, and move to left margin of the new line if it's blank.
382 If option `use-hard-newlines' is non-nil, the newline is marked with the
383 text-property `hard'.
384 With ARG, insert that many newlines.
385 Call `auto-fill-function' if the current column number is greater
386 than the value of `fill-column' and ARG is nil.
387 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
388 (interactive "*P\np")
389 (barf-if-buffer-read-only)
390 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
391 ;; Set last-command-event to tell self-insert what to insert.
392 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
393 (beforepos (point))
394 (last-command-event ?\n)
395 ;; Don't auto-fill if we have a numeric argument.
396 (auto-fill-function (if arg nil auto-fill-function))
397 (postproc
398 ;; Do the rest in post-self-insert-hook, because we want to do it
399 ;; *before* other functions on that hook.
400 (lambda ()
401 ;; Mark the newline(s) `hard'.
402 (if use-hard-newlines
403 (set-hard-newline-properties
404 (- (point) (prefix-numeric-value arg)) (point)))
405 ;; If the newline leaves the previous line blank, and we
406 ;; have a left margin, delete that from the blank line.
407 (save-excursion
408 (goto-char beforepos)
409 (beginning-of-line)
410 (and (looking-at "[ \t]$")
411 (> (current-left-margin) 0)
412 (delete-region (point)
413 (line-end-position))))
414 ;; Indent the line after the newline, except in one case:
415 ;; when we added the newline at the beginning of a line which
416 ;; starts a page.
417 (or was-page-start
418 (move-to-left-margin nil t)))))
419 (if (not interactive)
420 ;; FIXME: For non-interactive uses, many calls actually just want
421 ;; (insert "\n"), so maybe we should do just that, so as to avoid
422 ;; the risk of filling or running abbrevs unexpectedly.
423 (let ((post-self-insert-hook (list postproc)))
424 (self-insert-command (prefix-numeric-value arg)))
425 (unwind-protect
426 (progn
427 (add-hook 'post-self-insert-hook postproc)
428 (self-insert-command (prefix-numeric-value arg)))
429 ;; We first used let-binding to protect the hook, but that was naive
430 ;; since add-hook affects the symbol-default value of the variable,
431 ;; whereas the let-binding might only protect the buffer-local value.
432 (remove-hook 'post-self-insert-hook postproc))))
433 nil)
435 (defun set-hard-newline-properties (from to)
436 (let ((sticky (get-text-property from 'rear-nonsticky)))
437 (put-text-property from to 'hard 't)
438 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
439 (if (and (listp sticky) (not (memq 'hard sticky)))
440 (put-text-property from (point) 'rear-nonsticky
441 (cons 'hard sticky)))))
443 (defun open-line (n)
444 "Insert a newline and leave point before it.
445 If there is a fill prefix and/or a `left-margin', insert them
446 on the new line if the line would have been blank.
447 With arg N, insert N newlines."
448 (interactive "*p")
449 (let* ((do-fill-prefix (and fill-prefix (bolp)))
450 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
451 (loc (point-marker))
452 ;; Don't expand an abbrev before point.
453 (abbrev-mode nil))
454 (newline n)
455 (goto-char loc)
456 (while (> n 0)
457 (cond ((bolp)
458 (if do-left-margin (indent-to (current-left-margin)))
459 (if do-fill-prefix (insert-and-inherit fill-prefix))))
460 (forward-line 1)
461 (setq n (1- n)))
462 (goto-char loc)
463 (end-of-line)))
465 (defun split-line (&optional arg)
466 "Split current line, moving portion beyond point vertically down.
467 If the current line starts with `fill-prefix', insert it on the new
468 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
470 When called from Lisp code, ARG may be a prefix string to copy."
471 (interactive "*P")
472 (skip-chars-forward " \t")
473 (let* ((col (current-column))
474 (pos (point))
475 ;; What prefix should we check for (nil means don't).
476 (prefix (cond ((stringp arg) arg)
477 (arg nil)
478 (t fill-prefix)))
479 ;; Does this line start with it?
480 (have-prfx (and prefix
481 (save-excursion
482 (beginning-of-line)
483 (looking-at (regexp-quote prefix))))))
484 (newline 1)
485 (if have-prfx (insert-and-inherit prefix))
486 (indent-to col 0)
487 (goto-char pos)))
489 (defun delete-indentation (&optional arg)
490 "Join this line to previous and fix up whitespace at join.
491 If there is a fill prefix, delete it from the beginning of this line.
492 With argument, join this line to following line."
493 (interactive "*P")
494 (beginning-of-line)
495 (if arg (forward-line 1))
496 (if (eq (preceding-char) ?\n)
497 (progn
498 (delete-region (point) (1- (point)))
499 ;; If the second line started with the fill prefix,
500 ;; delete the prefix.
501 (if (and fill-prefix
502 (<= (+ (point) (length fill-prefix)) (point-max))
503 (string= fill-prefix
504 (buffer-substring (point)
505 (+ (point) (length fill-prefix)))))
506 (delete-region (point) (+ (point) (length fill-prefix))))
507 (fixup-whitespace))))
509 (defalias 'join-line #'delete-indentation) ; easier to find
511 (defun delete-blank-lines ()
512 "On blank line, delete all surrounding blank lines, leaving just one.
513 On isolated blank line, delete that one.
514 On nonblank line, delete any immediately following blank lines."
515 (interactive "*")
516 (let (thisblank singleblank)
517 (save-excursion
518 (beginning-of-line)
519 (setq thisblank (looking-at "[ \t]*$"))
520 ;; Set singleblank if there is just one blank line here.
521 (setq singleblank
522 (and thisblank
523 (not (looking-at "[ \t]*\n[ \t]*$"))
524 (or (bobp)
525 (progn (forward-line -1)
526 (not (looking-at "[ \t]*$")))))))
527 ;; Delete preceding blank lines, and this one too if it's the only one.
528 (if thisblank
529 (progn
530 (beginning-of-line)
531 (if singleblank (forward-line 1))
532 (delete-region (point)
533 (if (re-search-backward "[^ \t\n]" nil t)
534 (progn (forward-line 1) (point))
535 (point-min)))))
536 ;; Delete following blank lines, unless the current line is blank
537 ;; and there are no following blank lines.
538 (if (not (and thisblank singleblank))
539 (save-excursion
540 (end-of-line)
541 (forward-line 1)
542 (delete-region (point)
543 (if (re-search-forward "[^ \t\n]" nil t)
544 (progn (beginning-of-line) (point))
545 (point-max)))))
546 ;; Handle the special case where point is followed by newline and eob.
547 ;; Delete the line, leaving point at eob.
548 (if (looking-at "^[ \t]*\n\\'")
549 (delete-region (point) (point-max)))))
551 (defcustom delete-trailing-lines t
552 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
553 Trailing lines are deleted only if `delete-trailing-whitespace'
554 is called on the entire buffer (rather than an active region)."
555 :type 'boolean
556 :group 'editing
557 :version "24.3")
559 (defun delete-trailing-whitespace (&optional start end)
560 "Delete trailing whitespace between START and END.
561 If called interactively, START and END are the start/end of the
562 region if the mark is active, or of the buffer's accessible
563 portion if the mark is inactive.
565 This command deletes whitespace characters after the last
566 non-whitespace character in each line between START and END. It
567 does not consider formfeed characters to be whitespace.
569 If this command acts on the entire buffer (i.e. if called
570 interactively with the mark inactive, or called from Lisp with
571 END nil), it also deletes all trailing lines at the end of the
572 buffer if the variable `delete-trailing-lines' is non-nil."
573 (interactive (progn
574 (barf-if-buffer-read-only)
575 (if (use-region-p)
576 (list (region-beginning) (region-end))
577 (list nil nil))))
578 (save-match-data
579 (save-excursion
580 (let ((end-marker (copy-marker (or end (point-max))))
581 (start (or start (point-min))))
582 (goto-char start)
583 (while (re-search-forward "\\s-$" end-marker t)
584 (skip-syntax-backward "-" (line-beginning-position))
585 ;; Don't delete formfeeds, even if they are considered whitespace.
586 (if (looking-at-p ".*\f")
587 (goto-char (match-end 0)))
588 (delete-region (point) (match-end 0)))
589 ;; Delete trailing empty lines.
590 (goto-char end-marker)
591 (when (and (not end)
592 delete-trailing-lines
593 ;; Really the end of buffer.
594 (= (point-max) (1+ (buffer-size)))
595 (<= (skip-chars-backward "\n") -2))
596 (delete-region (1+ (point)) end-marker))
597 (set-marker end-marker nil))))
598 ;; Return nil for the benefit of `write-file-functions'.
599 nil)
601 (defun newline-and-indent ()
602 "Insert a newline, then indent according to major mode.
603 Indentation is done using the value of `indent-line-function'.
604 In programming language modes, this is the same as TAB.
605 In some text modes, where TAB inserts a tab, this command indents to the
606 column specified by the function `current-left-margin'."
607 (interactive "*")
608 (delete-horizontal-space t)
609 (newline)
610 (indent-according-to-mode))
612 (defun reindent-then-newline-and-indent ()
613 "Reindent current line, insert newline, then indent the new line.
614 Indentation of both lines is done according to the current major mode,
615 which means calling the current value of `indent-line-function'.
616 In programming language modes, this is the same as TAB.
617 In some text modes, where TAB inserts a tab, this indents to the
618 column specified by the function `current-left-margin'."
619 (interactive "*")
620 (let ((pos (point)))
621 ;; Be careful to insert the newline before indenting the line.
622 ;; Otherwise, the indentation might be wrong.
623 (newline)
624 (save-excursion
625 (goto-char pos)
626 ;; We are at EOL before the call to indent-according-to-mode, and
627 ;; after it we usually are as well, but not always. We tried to
628 ;; address it with `save-excursion' but that uses a normal marker
629 ;; whereas we need `move after insertion', so we do the save/restore
630 ;; by hand.
631 (setq pos (copy-marker pos t))
632 (indent-according-to-mode)
633 (goto-char pos)
634 ;; Remove the trailing white-space after indentation because
635 ;; indentation may introduce the whitespace.
636 (delete-horizontal-space t))
637 (indent-according-to-mode)))
639 (defcustom read-quoted-char-radix 8
640 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
641 Legitimate radix values are 8, 10 and 16."
642 :type '(choice (const 8) (const 10) (const 16))
643 :group 'editing-basics)
645 (defun read-quoted-char (&optional prompt)
646 "Like `read-char', but do not allow quitting.
647 Also, if the first character read is an octal digit,
648 we read any number of octal digits and return the
649 specified character code. Any nondigit terminates the sequence.
650 If the terminator is RET, it is discarded;
651 any other terminator is used itself as input.
653 The optional argument PROMPT specifies a string to use to prompt the user.
654 The variable `read-quoted-char-radix' controls which radix to use
655 for numeric input."
656 (let ((message-log-max nil) done (first t) (code 0) translated)
657 (while (not done)
658 (let ((inhibit-quit first)
659 ;; Don't let C-h get the help message--only help function keys.
660 (help-char nil)
661 (help-form
662 "Type the special character you want to use,
663 or the octal character code.
664 RET terminates the character code and is discarded;
665 any other non-digit terminates the character code and is then used as input."))
666 (setq translated (read-key (and prompt (format "%s-" prompt))))
667 (if inhibit-quit (setq quit-flag nil)))
668 (if (integerp translated)
669 (setq translated (char-resolve-modifiers translated)))
670 (cond ((null translated))
671 ((not (integerp translated))
672 (setq unread-command-events
673 (listify-key-sequence (this-single-command-raw-keys))
674 done t))
675 ((/= (logand translated ?\M-\^@) 0)
676 ;; Turn a meta-character into a character with the 0200 bit set.
677 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
678 done t))
679 ((and (<= ?0 translated)
680 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
681 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
682 (and prompt (setq prompt (message "%s %c" prompt translated))))
683 ((and (<= ?a (downcase translated))
684 (< (downcase translated)
685 (+ ?a -10 (min 36 read-quoted-char-radix))))
686 (setq code (+ (* code read-quoted-char-radix)
687 (+ 10 (- (downcase translated) ?a))))
688 (and prompt (setq prompt (message "%s %c" prompt translated))))
689 ((and (not first) (eq translated ?\C-m))
690 (setq done t))
691 ((not first)
692 (setq unread-command-events
693 (listify-key-sequence (this-single-command-raw-keys))
694 done t))
695 (t (setq code translated
696 done t)))
697 (setq first nil))
698 code))
700 (defun quoted-insert (arg)
701 "Read next input character and insert it.
702 This is useful for inserting control characters.
703 With argument, insert ARG copies of the character.
705 If the first character you type after this command is an octal digit,
706 you should type a sequence of octal digits which specify a character code.
707 Any nondigit terminates the sequence. If the terminator is a RET,
708 it is discarded; any other terminator is used itself as input.
709 The variable `read-quoted-char-radix' specifies the radix for this feature;
710 set it to 10 or 16 to use decimal or hex instead of octal.
712 In overwrite mode, this function inserts the character anyway, and
713 does not handle octal digits specially. This means that if you use
714 overwrite as your normal editing mode, you can use this function to
715 insert characters when necessary.
717 In binary overwrite mode, this function does overwrite, and octal
718 digits are interpreted as a character code. This is intended to be
719 useful for editing binary files."
720 (interactive "*p")
721 (let* ((char
722 ;; Avoid "obsolete" warnings for translation-table-for-input.
723 (with-no-warnings
724 (let (translation-table-for-input input-method-function)
725 (if (or (not overwrite-mode)
726 (eq overwrite-mode 'overwrite-mode-binary))
727 (read-quoted-char)
728 (read-char))))))
729 ;; This used to assume character codes 0240 - 0377 stand for
730 ;; characters in some single-byte character set, and converted them
731 ;; to Emacs characters. But in 23.1 this feature is deprecated
732 ;; in favor of inserting the corresponding Unicode characters.
733 ;; (if (and enable-multibyte-characters
734 ;; (>= char ?\240)
735 ;; (<= char ?\377))
736 ;; (setq char (unibyte-char-to-multibyte char)))
737 (if (> arg 0)
738 (if (eq overwrite-mode 'overwrite-mode-binary)
739 (delete-char arg)))
740 (while (> arg 0)
741 (insert-and-inherit char)
742 (setq arg (1- arg)))))
744 (defun forward-to-indentation (&optional arg)
745 "Move forward ARG lines and position at first nonblank character."
746 (interactive "^p")
747 (forward-line (or arg 1))
748 (skip-chars-forward " \t"))
750 (defun backward-to-indentation (&optional arg)
751 "Move backward ARG lines and position at first nonblank character."
752 (interactive "^p")
753 (forward-line (- (or arg 1)))
754 (skip-chars-forward " \t"))
756 (defun back-to-indentation ()
757 "Move point to the first non-whitespace character on this line."
758 (interactive "^")
759 (beginning-of-line 1)
760 (skip-syntax-forward " " (line-end-position))
761 ;; Move back over chars that have whitespace syntax but have the p flag.
762 (backward-prefix-chars))
764 (defun fixup-whitespace ()
765 "Fixup white space between objects around point.
766 Leave one space or none, according to the context."
767 (interactive "*")
768 (save-excursion
769 (delete-horizontal-space)
770 (if (or (looking-at "^\\|\\s)")
771 (save-excursion (forward-char -1)
772 (looking-at "$\\|\\s(\\|\\s'")))
774 (insert ?\s))))
776 (defun delete-horizontal-space (&optional backward-only)
777 "Delete all spaces and tabs around point.
778 If BACKWARD-ONLY is non-nil, only delete them before point."
779 (interactive "*P")
780 (let ((orig-pos (point)))
781 (delete-region
782 (if backward-only
783 orig-pos
784 (progn
785 (skip-chars-forward " \t")
786 (constrain-to-field nil orig-pos t)))
787 (progn
788 (skip-chars-backward " \t")
789 (constrain-to-field nil orig-pos)))))
791 (defun just-one-space (&optional n)
792 "Delete all spaces and tabs around point, leaving one space (or N spaces).
793 If N is negative, delete newlines as well, leaving -N spaces."
794 (interactive "*p")
795 (cycle-spacing n nil t))
797 (defvar cycle-spacing--context nil
798 "Store context used in consecutive calls to `cycle-spacing' command.
799 The first time this function is run, it saves the original point
800 position and original spacing around the point in this
801 variable.")
803 (defun cycle-spacing (&optional n preserve-nl-back single-shot)
804 "Manipulate spaces around the point in a smart way.
806 When run as an interactive command, the first time it's called
807 in a sequence, deletes all spaces and tabs around point leaving
808 one (or N spaces). If this does not change content of the
809 buffer, skips to the second step:
811 When run for the second time in a sequence, deletes all the
812 spaces it has previously inserted.
814 When run for the third time, returns the whitespace and point in
815 a state encountered when it had been run for the first time.
817 For example, if buffer contains \"foo ^ bar\" with \"^\" denoting the
818 point, calling `cycle-spacing' command will replace two spaces with
819 a single space, calling it again immediately after, will remove all
820 spaces, and calling it for the third time will bring two spaces back
821 together.
823 If N is negative, delete newlines as well. However, if
824 PRESERVE-NL-BACK is t new line characters prior to the point
825 won't be removed.
827 If SINGLE-SHOT is non-nil, will only perform the first step. In
828 other words, it will work just like `just-one-space' command."
829 (interactive "*p")
830 (let ((orig-pos (point))
831 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
832 (n (abs (or n 1))))
833 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
834 (constrain-to-field nil orig-pos)
835 (cond
836 ;; Command run for the first time or single-shot is non-nil.
837 ((or single-shot
838 (not (equal last-command this-command))
839 (not cycle-spacing--context))
840 (let* ((start (point))
841 (n (- n (skip-chars-forward " " (+ n (point)))))
842 (mid (point))
843 (end (progn
844 (skip-chars-forward skip-characters)
845 (constrain-to-field nil orig-pos t))))
846 (setq cycle-spacing--context ;; Save for later.
847 ;; Special handling for case where there was no space at all.
848 (unless (= start end)
849 (cons orig-pos (buffer-substring start (point)))))
850 ;; If this run causes no change in buffer content, delete all spaces,
851 ;; otherwise delete all excess spaces.
852 (delete-region (if (and (not single-shot) (zerop n) (= mid end))
853 start mid) end)
854 (insert (make-string n ?\s))))
856 ;; Command run for the second time.
857 ((not (equal orig-pos (point)))
858 (delete-region (point) orig-pos))
860 ;; Command run for the third time.
862 (insert (cdr cycle-spacing--context))
863 (goto-char (car cycle-spacing--context))
864 (setq cycle-spacing--context nil)))))
866 (defun beginning-of-buffer (&optional arg)
867 "Move point to the beginning of the buffer.
868 With numeric arg N, put point N/10 of the way from the beginning.
869 If the buffer is narrowed, this command uses the beginning of the
870 accessible part of the buffer.
872 If Transient Mark mode is disabled, leave mark at previous
873 position, unless a \\[universal-argument] prefix is supplied.
875 Don't use this command in Lisp programs!
876 \(goto-char (point-min)) is faster."
877 (interactive "^P")
878 (or (consp arg)
879 (region-active-p)
880 (push-mark))
881 (let ((size (- (point-max) (point-min))))
882 (goto-char (if (and arg (not (consp arg)))
883 (+ (point-min)
884 (if (> size 10000)
885 ;; Avoid overflow for large buffer sizes!
886 (* (prefix-numeric-value arg)
887 (/ size 10))
888 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
889 (point-min))))
890 (if (and arg (not (consp arg))) (forward-line 1)))
891 (put 'beginning-of-buffer 'interactive-only
892 "use `(goto-char (point-min))' instead.")
894 (defun end-of-buffer (&optional arg)
895 "Move point to the end of the buffer.
896 With numeric arg N, put point N/10 of the way from the end.
897 If the buffer is narrowed, this command uses the end of the
898 accessible part of the buffer.
900 If Transient Mark mode is disabled, leave mark at previous
901 position, unless a \\[universal-argument] prefix is supplied.
903 Don't use this command in Lisp programs!
904 \(goto-char (point-max)) is faster."
905 (interactive "^P")
906 (or (consp arg) (region-active-p) (push-mark))
907 (let ((size (- (point-max) (point-min))))
908 (goto-char (if (and arg (not (consp arg)))
909 (- (point-max)
910 (if (> size 10000)
911 ;; Avoid overflow for large buffer sizes!
912 (* (prefix-numeric-value arg)
913 (/ size 10))
914 (/ (* size (prefix-numeric-value arg)) 10)))
915 (point-max))))
916 ;; If we went to a place in the middle of the buffer,
917 ;; adjust it to the beginning of a line.
918 (cond ((and arg (not (consp arg))) (forward-line 1))
919 ((and (eq (current-buffer) (window-buffer))
920 (> (point) (window-end nil t)))
921 ;; If the end of the buffer is not already on the screen,
922 ;; then scroll specially to put it near, but not at, the bottom.
923 (overlay-recenter (point))
924 (recenter -3))))
925 (put 'end-of-buffer 'interactive-only "use `(goto-char (point-max))' instead.")
927 (defcustom delete-active-region t
928 "Whether single-char deletion commands delete an active region.
929 This has an effect only if Transient Mark mode is enabled, and
930 affects `delete-forward-char' and `delete-backward-char', though
931 not `delete-char'.
933 If the value is the symbol `kill', the active region is killed
934 instead of deleted."
935 :type '(choice (const :tag "Delete active region" t)
936 (const :tag "Kill active region" kill)
937 (const :tag "Do ordinary deletion" nil))
938 :group 'killing
939 :version "24.1")
941 (defvar region-extract-function
942 (lambda (delete)
943 (when (region-beginning)
944 (if (eq delete 'delete-only)
945 (delete-region (region-beginning) (region-end))
946 (filter-buffer-substring (region-beginning) (region-end) delete))))
947 "Function to get the region's content.
948 Called with one argument DELETE.
949 If DELETE is `delete-only', then only delete the region and the return value
950 is undefined. If DELETE is nil, just return the content as a string.
951 If anything else, delete the region and return its content as a string.")
953 (defun delete-backward-char (n &optional killflag)
954 "Delete the previous N characters (following if N is negative).
955 If Transient Mark mode is enabled, the mark is active, and N is 1,
956 delete the text in the region and deactivate the mark instead.
957 To disable this, set option `delete-active-region' to nil.
959 Optional second arg KILLFLAG, if non-nil, means to kill (save in
960 kill ring) instead of delete. Interactively, N is the prefix
961 arg, and KILLFLAG is set if N is explicitly specified.
963 In Overwrite mode, single character backward deletion may replace
964 tabs with spaces so as to back over columns, unless point is at
965 the end of the line."
966 (interactive "p\nP")
967 (unless (integerp n)
968 (signal 'wrong-type-argument (list 'integerp n)))
969 (cond ((and (use-region-p)
970 delete-active-region
971 (= n 1))
972 ;; If a region is active, kill or delete it.
973 (if (eq delete-active-region 'kill)
974 (kill-region (region-beginning) (region-end) 'region)
975 (funcall region-extract-function 'delete-only)))
976 ;; In Overwrite mode, maybe untabify while deleting
977 ((null (or (null overwrite-mode)
978 (<= n 0)
979 (memq (char-before) '(?\t ?\n))
980 (eobp)
981 (eq (char-after) ?\n)))
982 (let ((ocol (current-column)))
983 (delete-char (- n) killflag)
984 (save-excursion
985 (insert-char ?\s (- ocol (current-column)) nil))))
986 ;; Otherwise, do simple deletion.
987 (t (delete-char (- n) killflag))))
988 (put 'delete-backward-char 'interactive-only 'delete-char)
990 (defun delete-forward-char (n &optional killflag)
991 "Delete the following N characters (previous if N is negative).
992 If Transient Mark mode is enabled, the mark is active, and N is 1,
993 delete the text in the region and deactivate the mark instead.
994 To disable this, set variable `delete-active-region' to nil.
996 Optional second arg KILLFLAG non-nil means to kill (save in kill
997 ring) instead of delete. Interactively, N is the prefix arg, and
998 KILLFLAG is set if N was explicitly specified."
999 (interactive "p\nP")
1000 (unless (integerp n)
1001 (signal 'wrong-type-argument (list 'integerp n)))
1002 (cond ((and (use-region-p)
1003 delete-active-region
1004 (= n 1))
1005 ;; If a region is active, kill or delete it.
1006 (if (eq delete-active-region 'kill)
1007 (kill-region (region-beginning) (region-end) 'region)
1008 (funcall region-extract-function 'delete-only)))
1010 ;; Otherwise, do simple deletion.
1011 (t (delete-char n killflag))))
1013 (defun mark-whole-buffer ()
1014 "Put point at beginning and mark at end of buffer.
1015 If narrowing is in effect, only uses the accessible part of the buffer.
1016 You probably should not use this function in Lisp programs;
1017 it is usually a mistake for a Lisp function to use any subroutine
1018 that uses or sets the mark."
1019 (interactive)
1020 (push-mark (point))
1021 (push-mark (point-max) nil t)
1022 (goto-char (point-min)))
1025 ;; Counting lines, one way or another.
1027 (defun goto-line (line &optional buffer)
1028 "Go to LINE, counting from line 1 at beginning of buffer.
1029 If called interactively, a numeric prefix argument specifies
1030 LINE; without a numeric prefix argument, read LINE from the
1031 minibuffer.
1033 If optional argument BUFFER is non-nil, switch to that buffer and
1034 move to line LINE there. If called interactively with \\[universal-argument]
1035 as argument, BUFFER is the most recently selected other buffer.
1037 Prior to moving point, this function sets the mark (without
1038 activating it), unless Transient Mark mode is enabled and the
1039 mark is already active.
1041 This function is usually the wrong thing to use in a Lisp program.
1042 What you probably want instead is something like:
1043 (goto-char (point-min))
1044 (forward-line (1- N))
1045 If at all possible, an even better solution is to use char counts
1046 rather than line counts."
1047 (interactive
1048 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1049 (list (prefix-numeric-value current-prefix-arg))
1050 ;; Look for a default, a number in the buffer at point.
1051 (let* ((default
1052 (save-excursion
1053 (skip-chars-backward "0-9")
1054 (if (looking-at "[0-9]")
1055 (string-to-number
1056 (buffer-substring-no-properties
1057 (point)
1058 (progn (skip-chars-forward "0-9")
1059 (point)))))))
1060 ;; Decide if we're switching buffers.
1061 (buffer
1062 (if (consp current-prefix-arg)
1063 (other-buffer (current-buffer) t)))
1064 (buffer-prompt
1065 (if buffer
1066 (concat " in " (buffer-name buffer))
1067 "")))
1068 ;; Read the argument, offering that number (if any) as default.
1069 (list (read-number (format "Goto line%s: " buffer-prompt)
1070 (list default (line-number-at-pos)))
1071 buffer))))
1072 ;; Switch to the desired buffer, one way or another.
1073 (if buffer
1074 (let ((window (get-buffer-window buffer)))
1075 (if window (select-window window)
1076 (switch-to-buffer-other-window buffer))))
1077 ;; Leave mark at previous position
1078 (or (region-active-p) (push-mark))
1079 ;; Move to the specified line number in that buffer.
1080 (save-restriction
1081 (widen)
1082 (goto-char (point-min))
1083 (if (eq selective-display t)
1084 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1085 (forward-line (1- line)))))
1086 (put 'goto-line 'interactive-only 'forward-line)
1088 (defun count-words-region (start end &optional arg)
1089 "Count the number of words in the region.
1090 If called interactively, print a message reporting the number of
1091 lines, words, and characters in the region (whether or not the
1092 region is active); with prefix ARG, report for the entire buffer
1093 rather than the region.
1095 If called from Lisp, return the number of words between positions
1096 START and END."
1097 (interactive (if current-prefix-arg
1098 (list nil nil current-prefix-arg)
1099 (list (region-beginning) (region-end) nil)))
1100 (cond ((not (called-interactively-p 'any))
1101 (count-words start end))
1102 (arg
1103 (count-words--buffer-message))
1105 (count-words--message "Region" start end))))
1107 (defun count-words (start end)
1108 "Count words between START and END.
1109 If called interactively, START and END are normally the start and
1110 end of the buffer; but if the region is active, START and END are
1111 the start and end of the region. Print a message reporting the
1112 number of lines, words, and chars.
1114 If called from Lisp, return the number of words between START and
1115 END, without printing any message."
1116 (interactive (list nil nil))
1117 (cond ((not (called-interactively-p 'any))
1118 (let ((words 0))
1119 (save-excursion
1120 (save-restriction
1121 (narrow-to-region start end)
1122 (goto-char (point-min))
1123 (while (forward-word 1)
1124 (setq words (1+ words)))))
1125 words))
1126 ((use-region-p)
1127 (call-interactively 'count-words-region))
1129 (count-words--buffer-message))))
1131 (defun count-words--buffer-message ()
1132 (count-words--message
1133 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1134 (point-min) (point-max)))
1136 (defun count-words--message (str start end)
1137 (let ((lines (count-lines start end))
1138 (words (count-words start end))
1139 (chars (- end start)))
1140 (message "%s has %d line%s, %d word%s, and %d character%s."
1142 lines (if (= lines 1) "" "s")
1143 words (if (= words 1) "" "s")
1144 chars (if (= chars 1) "" "s"))))
1146 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1148 (defun what-line ()
1149 "Print the current buffer line number and narrowed line number of point."
1150 (interactive)
1151 (let ((start (point-min))
1152 (n (line-number-at-pos)))
1153 (if (= start 1)
1154 (message "Line %d" n)
1155 (save-excursion
1156 (save-restriction
1157 (widen)
1158 (message "line %d (narrowed line %d)"
1159 (+ n (line-number-at-pos start) -1) n))))))
1161 (defun count-lines (start end)
1162 "Return number of lines between START and END.
1163 This is usually the number of newlines between them,
1164 but can be one more if START is not equal to END
1165 and the greater of them is not at the start of a line."
1166 (save-excursion
1167 (save-restriction
1168 (narrow-to-region start end)
1169 (goto-char (point-min))
1170 (if (eq selective-display t)
1171 (save-match-data
1172 (let ((done 0))
1173 (while (re-search-forward "[\n\C-m]" nil t 40)
1174 (setq done (+ 40 done)))
1175 (while (re-search-forward "[\n\C-m]" nil t 1)
1176 (setq done (+ 1 done)))
1177 (goto-char (point-max))
1178 (if (and (/= start end)
1179 (not (bolp)))
1180 (1+ done)
1181 done)))
1182 (- (buffer-size) (forward-line (buffer-size)))))))
1184 (defun line-number-at-pos (&optional pos)
1185 "Return (narrowed) buffer line number at position POS.
1186 If POS is nil, use current buffer location.
1187 Counting starts at (point-min), so the value refers
1188 to the contents of the accessible portion of the buffer."
1189 (let ((opoint (or pos (point))) start)
1190 (save-excursion
1191 (goto-char (point-min))
1192 (setq start (point))
1193 (goto-char opoint)
1194 (forward-line 0)
1195 (1+ (count-lines start (point))))))
1197 (defun what-cursor-position (&optional detail)
1198 "Print info on cursor position (on screen and within buffer).
1199 Also describe the character after point, and give its character code
1200 in octal, decimal and hex.
1202 For a non-ASCII multibyte character, also give its encoding in the
1203 buffer's selected coding system if the coding system encodes the
1204 character safely. If the character is encoded into one byte, that
1205 code is shown in hex. If the character is encoded into more than one
1206 byte, just \"...\" is shown.
1208 In addition, with prefix argument, show details about that character
1209 in *Help* buffer. See also the command `describe-char'."
1210 (interactive "P")
1211 (let* ((char (following-char))
1212 (bidi-fixer
1213 (cond ((memq char '(?\x202a ?\x202b ?\x202d ?\x202e))
1214 ;; If the character is one of LRE, LRO, RLE, RLO, it
1215 ;; will start a directional embedding, which could
1216 ;; completely disrupt the rest of the line (e.g., RLO
1217 ;; will display the rest of the line right-to-left).
1218 ;; So we put an invisible PDF character after these
1219 ;; characters, to end the embedding, which eliminates
1220 ;; any effects on the rest of the line.
1221 (propertize (string ?\x202c) 'invisible t))
1222 ;; Strong right-to-left characters cause reordering of
1223 ;; the following numerical characters which show the
1224 ;; codepoint, so append LRM to countermand that.
1225 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1226 (propertize (string ?\x200e) 'invisible t))
1228 "")))
1229 (beg (point-min))
1230 (end (point-max))
1231 (pos (point))
1232 (total (buffer-size))
1233 (percent (if (> total 50000)
1234 ;; Avoid overflow from multiplying by 100!
1235 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
1236 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
1237 (hscroll (if (= (window-hscroll) 0)
1239 (format " Hscroll=%d" (window-hscroll))))
1240 (col (current-column)))
1241 (if (= pos end)
1242 (if (or (/= beg 1) (/= end (1+ total)))
1243 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1244 pos total percent beg end col hscroll)
1245 (message "point=%d of %d (EOB) column=%d%s"
1246 pos total col hscroll))
1247 (let ((coding buffer-file-coding-system)
1248 encoded encoding-msg display-prop under-display)
1249 (if (or (not coding)
1250 (eq (coding-system-type coding) t))
1251 (setq coding (default-value 'buffer-file-coding-system)))
1252 (if (eq (char-charset char) 'eight-bit)
1253 (setq encoding-msg
1254 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1255 ;; Check if the character is displayed with some `display'
1256 ;; text property. In that case, set under-display to the
1257 ;; buffer substring covered by that property.
1258 (setq display-prop (get-char-property pos 'display))
1259 (if display-prop
1260 (let ((to (or (next-single-char-property-change pos 'display)
1261 (point-max))))
1262 (if (< to (+ pos 4))
1263 (setq under-display "")
1264 (setq under-display "..."
1265 to (+ pos 4)))
1266 (setq under-display
1267 (concat (buffer-substring-no-properties pos to)
1268 under-display)))
1269 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1270 (setq encoding-msg
1271 (if display-prop
1272 (if (not (stringp display-prop))
1273 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1274 char char char under-display)
1275 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1276 char char char under-display display-prop))
1277 (if encoded
1278 (format "(%d, #o%o, #x%x, file %s)"
1279 char char char
1280 (if (> (length encoded) 1)
1281 "..."
1282 (encoded-string-description encoded coding)))
1283 (format "(%d, #o%o, #x%x)" char char char)))))
1284 (if detail
1285 ;; We show the detailed information about CHAR.
1286 (describe-char (point)))
1287 (if (or (/= beg 1) (/= end (1+ total)))
1288 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1289 (if (< char 256)
1290 (single-key-description char)
1291 (buffer-substring-no-properties (point) (1+ (point))))
1292 bidi-fixer
1293 encoding-msg pos total percent beg end col hscroll)
1294 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1295 (if enable-multibyte-characters
1296 (if (< char 128)
1297 (single-key-description char)
1298 (buffer-substring-no-properties (point) (1+ (point))))
1299 (single-key-description char))
1300 bidi-fixer encoding-msg pos total percent col hscroll))))))
1302 ;; Initialize read-expression-map. It is defined at C level.
1303 (defvar read-expression-map
1304 (let ((m (make-sparse-keymap)))
1305 (define-key m "\M-\t" 'completion-at-point)
1306 ;; Might as well bind TAB to completion, since inserting a TAB char is
1307 ;; much too rarely useful.
1308 (define-key m "\t" 'completion-at-point)
1309 (set-keymap-parent m minibuffer-local-map)
1312 (defun read-minibuffer (prompt &optional initial-contents)
1313 "Return a Lisp object read using the minibuffer, unevaluated.
1314 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1315 is a string to insert in the minibuffer before reading.
1316 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1317 Such arguments are used as in `read-from-minibuffer'.)"
1318 ;; Used for interactive spec `x'.
1319 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1320 t 'minibuffer-history))
1322 (defun eval-minibuffer (prompt &optional initial-contents)
1323 "Return value of Lisp expression read using the minibuffer.
1324 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1325 is a string to insert in the minibuffer before reading.
1326 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1327 Such arguments are used as in `read-from-minibuffer'.)"
1328 ;; Used for interactive spec `X'.
1329 (eval (read--expression prompt initial-contents)))
1331 (defvar minibuffer-completing-symbol nil
1332 "Non-nil means completing a Lisp symbol in the minibuffer.")
1333 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1335 (defvar minibuffer-default nil
1336 "The current default value or list of default values in the minibuffer.
1337 The functions `read-from-minibuffer' and `completing-read' bind
1338 this variable locally.")
1340 (defcustom eval-expression-print-level 4
1341 "Value for `print-level' while printing value in `eval-expression'.
1342 A value of nil means no limit."
1343 :group 'lisp
1344 :type '(choice (const :tag "No Limit" nil) integer)
1345 :version "21.1")
1347 (defcustom eval-expression-print-length 12
1348 "Value for `print-length' while printing value in `eval-expression'.
1349 A value of nil means no limit."
1350 :group 'lisp
1351 :type '(choice (const :tag "No Limit" nil) integer)
1352 :version "21.1")
1354 (defcustom eval-expression-debug-on-error t
1355 "If non-nil set `debug-on-error' to t in `eval-expression'.
1356 If nil, don't change the value of `debug-on-error'."
1357 :group 'lisp
1358 :type 'boolean
1359 :version "21.1")
1361 (defun eval-expression-print-format (value)
1362 "Format VALUE as a result of evaluated expression.
1363 Return a formatted string which is displayed in the echo area
1364 in addition to the value printed by prin1 in functions which
1365 display the result of expression evaluation."
1366 (if (and (integerp value)
1367 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1368 (eq this-command last-command)
1369 (if (boundp 'edebug-active) edebug-active)))
1370 (let ((char-string
1371 (if (or (if (boundp 'edebug-active) edebug-active)
1372 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1373 (prin1-char value))))
1374 (if char-string
1375 (format " (#o%o, #x%x, %s)" value value char-string)
1376 (format " (#o%o, #x%x)" value value)))))
1378 (defvar eval-expression-minibuffer-setup-hook nil
1379 "Hook run by `eval-expression' when entering the minibuffer.")
1381 (defun read--expression (prompt &optional initial-contents)
1382 (let ((minibuffer-completing-symbol t))
1383 (minibuffer-with-setup-hook
1384 (lambda ()
1385 (add-hook 'completion-at-point-functions
1386 #'lisp-completion-at-point nil t)
1387 (run-hooks 'eval-expression-minibuffer-setup-hook))
1388 (read-from-minibuffer prompt initial-contents
1389 read-expression-map t
1390 'read-expression-history))))
1392 ;; We define this, rather than making `eval' interactive,
1393 ;; for the sake of completion of names like eval-region, eval-buffer.
1394 (defun eval-expression (exp &optional insert-value)
1395 "Evaluate EXP and print value in the echo area.
1396 When called interactively, read an Emacs Lisp expression and
1397 evaluate it.
1398 Value is also consed on to front of the variable `values'.
1399 Optional argument INSERT-VALUE non-nil (interactively,
1400 with prefix argument) means insert the result into the current buffer
1401 instead of printing it in the echo area. Truncates long output
1402 according to the value of the variables `eval-expression-print-length'
1403 and `eval-expression-print-level'.
1405 If `eval-expression-debug-on-error' is non-nil, which is the default,
1406 this command arranges for all errors to enter the debugger."
1407 (interactive
1408 (list (read--expression "Eval: ")
1409 current-prefix-arg))
1411 (if (null eval-expression-debug-on-error)
1412 (push (eval exp lexical-binding) values)
1413 (let ((old-value (make-symbol "t")) new-value)
1414 ;; Bind debug-on-error to something unique so that we can
1415 ;; detect when evalled code changes it.
1416 (let ((debug-on-error old-value))
1417 (push (eval exp lexical-binding) values)
1418 (setq new-value debug-on-error))
1419 ;; If evalled code has changed the value of debug-on-error,
1420 ;; propagate that change to the global binding.
1421 (unless (eq old-value new-value)
1422 (setq debug-on-error new-value))))
1424 (let ((print-length eval-expression-print-length)
1425 (print-level eval-expression-print-level)
1426 (deactivate-mark))
1427 (if insert-value
1428 (with-no-warnings
1429 (let ((standard-output (current-buffer)))
1430 (prin1 (car values))))
1431 (prog1
1432 (prin1 (car values) t)
1433 (let ((str (eval-expression-print-format (car values))))
1434 (if str (princ str t)))))))
1436 (defun edit-and-eval-command (prompt command)
1437 "Prompting with PROMPT, let user edit COMMAND and eval result.
1438 COMMAND is a Lisp expression. Let user edit that expression in
1439 the minibuffer, then read and evaluate the result."
1440 (let ((command
1441 (let ((print-level nil)
1442 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1443 (unwind-protect
1444 (read-from-minibuffer prompt
1445 (prin1-to-string command)
1446 read-expression-map t
1447 'command-history)
1448 ;; If command was added to command-history as a string,
1449 ;; get rid of that. We want only evaluable expressions there.
1450 (if (stringp (car command-history))
1451 (setq command-history (cdr command-history)))))))
1453 ;; If command to be redone does not match front of history,
1454 ;; add it to the history.
1455 (or (equal command (car command-history))
1456 (setq command-history (cons command command-history)))
1457 (eval command)))
1459 (defun repeat-complex-command (arg)
1460 "Edit and re-evaluate last complex command, or ARGth from last.
1461 A complex command is one which used the minibuffer.
1462 The command is placed in the minibuffer as a Lisp form for editing.
1463 The result is executed, repeating the command as changed.
1464 If the command has been changed or is not the most recent previous
1465 command it is added to the front of the command history.
1466 You can use the minibuffer history commands \
1467 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1468 to get different commands to edit and resubmit."
1469 (interactive "p")
1470 (let ((elt (nth (1- arg) command-history))
1471 newcmd)
1472 (if elt
1473 (progn
1474 (setq newcmd
1475 (let ((print-level nil)
1476 (minibuffer-history-position arg)
1477 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1478 (unwind-protect
1479 (read-from-minibuffer
1480 "Redo: " (prin1-to-string elt) read-expression-map t
1481 (cons 'command-history arg))
1483 ;; If command was added to command-history as a
1484 ;; string, get rid of that. We want only
1485 ;; evaluable expressions there.
1486 (if (stringp (car command-history))
1487 (setq command-history (cdr command-history))))))
1489 ;; If command to be redone does not match front of history,
1490 ;; add it to the history.
1491 (or (equal newcmd (car command-history))
1492 (setq command-history (cons newcmd command-history)))
1493 (unwind-protect
1494 (progn
1495 ;; Trick called-interactively-p into thinking that `newcmd' is
1496 ;; an interactive call (bug#14136).
1497 (add-hook 'called-interactively-p-functions
1498 #'repeat-complex-command--called-interactively-skip)
1499 (eval newcmd))
1500 (remove-hook 'called-interactively-p-functions
1501 #'repeat-complex-command--called-interactively-skip)))
1502 (if command-history
1503 (error "Argument %d is beyond length of command history" arg)
1504 (error "There are no previous complex commands to repeat")))))
1506 (defun repeat-complex-command--called-interactively-skip (i _frame1 frame2)
1507 (and (eq 'eval (cadr frame2))
1508 (eq 'repeat-complex-command
1509 (cadr (backtrace-frame i #'called-interactively-p)))
1512 (defvar extended-command-history nil)
1514 (defun read-extended-command ()
1515 "Read command name to invoke in `execute-extended-command'."
1516 (minibuffer-with-setup-hook
1517 (lambda ()
1518 (set (make-local-variable 'minibuffer-default-add-function)
1519 (lambda ()
1520 ;; Get a command name at point in the original buffer
1521 ;; to propose it after M-n.
1522 (with-current-buffer (window-buffer (minibuffer-selected-window))
1523 (and (commandp (function-called-at-point))
1524 (format "%S" (function-called-at-point)))))))
1525 ;; Read a string, completing from and restricting to the set of
1526 ;; all defined commands. Don't provide any initial input.
1527 ;; Save the command read on the extended-command history list.
1528 (completing-read
1529 (concat (cond
1530 ((eq current-prefix-arg '-) "- ")
1531 ((and (consp current-prefix-arg)
1532 (eq (car current-prefix-arg) 4)) "C-u ")
1533 ((and (consp current-prefix-arg)
1534 (integerp (car current-prefix-arg)))
1535 (format "%d " (car current-prefix-arg)))
1536 ((integerp current-prefix-arg)
1537 (format "%d " current-prefix-arg)))
1538 ;; This isn't strictly correct if `execute-extended-command'
1539 ;; is bound to anything else (e.g. [menu]).
1540 ;; It could use (key-description (this-single-command-keys)),
1541 ;; but actually a prompt other than "M-x" would be confusing,
1542 ;; because "M-x" is a well-known prompt to read a command
1543 ;; and it serves as a shorthand for "Extended command: ".
1544 "M-x ")
1545 obarray 'commandp t nil 'extended-command-history)))
1547 (defcustom suggest-key-bindings t
1548 "Non-nil means show the equivalent key-binding when M-x command has one.
1549 The value can be a length of time to show the message for.
1550 If the value is non-nil and not a number, we wait 2 seconds."
1551 :group 'keyboard
1552 :type '(choice (const :tag "off" nil)
1553 (integer :tag "time" 2)
1554 (other :tag "on")))
1556 (defun execute-extended-command (prefixarg &optional command-name)
1557 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1558 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1559 "Read function name, then read its arguments and call it.
1561 To pass a numeric argument to the command you are invoking, specify
1562 the numeric argument to this command.
1564 Noninteractively, the argument PREFIXARG is the prefix argument to
1565 give to the command you invoke, if it asks for an argument."
1566 (interactive (list current-prefix-arg (read-extended-command)))
1567 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1568 (if (null command-name)
1569 (setq command-name (let ((current-prefix-arg prefixarg)) ; for prompt
1570 (read-extended-command))))
1571 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1572 (binding (and suggest-key-bindings
1573 (not executing-kbd-macro)
1574 (where-is-internal function overriding-local-map t))))
1575 (unless (commandp function)
1576 (error "`%s' is not a valid command name" command-name))
1577 (setq this-command function)
1578 ;; Normally `real-this-command' should never be changed, but here we really
1579 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1580 ;; binding" for <cmd>, so the command the user really wanted to run is
1581 ;; `function' and not `execute-extended-command'. The difference is
1582 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1583 (setq real-this-command function)
1584 (let ((prefix-arg prefixarg))
1585 (command-execute function 'record))
1586 ;; If enabled, show which key runs this command.
1587 (when binding
1588 ;; But first wait, and skip the message if there is input.
1589 (let* ((waited
1590 ;; If this command displayed something in the echo area;
1591 ;; wait a few seconds, then display our suggestion message.
1592 (sit-for (cond
1593 ((zerop (length (current-message))) 0)
1594 ((numberp suggest-key-bindings) suggest-key-bindings)
1595 (t 2)))))
1596 (when (and waited (not (consp unread-command-events)))
1597 (with-temp-message
1598 (format "You can run the command `%s' with %s"
1599 function (key-description binding))
1600 (sit-for (if (numberp suggest-key-bindings)
1601 suggest-key-bindings
1602 2))))))))
1604 (defun command-execute (cmd &optional record-flag keys special)
1605 ;; BEWARE: Called directly from the C code.
1606 "Execute CMD as an editor command.
1607 CMD must be a symbol that satisfies the `commandp' predicate.
1608 Optional second arg RECORD-FLAG non-nil
1609 means unconditionally put this command in the variable `command-history'.
1610 Otherwise, that is done only if an arg is read using the minibuffer.
1611 The argument KEYS specifies the value to use instead of (this-command-keys)
1612 when reading the arguments; if it is nil, (this-command-keys) is used.
1613 The argument SPECIAL, if non-nil, means that this command is executing
1614 a special event, so ignore the prefix argument and don't clear it."
1615 (setq debug-on-next-call nil)
1616 (let ((prefixarg (unless special
1617 (prog1 prefix-arg
1618 (setq current-prefix-arg prefix-arg)
1619 (setq prefix-arg nil)))))
1620 (and (symbolp cmd)
1621 (get cmd 'disabled)
1622 ;; FIXME: Weird calling convention!
1623 (run-hooks 'disabled-command-function))
1624 (let ((final cmd))
1625 (while
1626 (progn
1627 (setq final (indirect-function final))
1628 (if (autoloadp final)
1629 (setq final (autoload-do-load final cmd)))))
1630 (cond
1631 ((arrayp final)
1632 ;; If requested, place the macro in the command history. For
1633 ;; other sorts of commands, call-interactively takes care of this.
1634 (when record-flag
1635 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1636 ;; Don't keep command history around forever.
1637 (when (and (numberp history-length) (> history-length 0))
1638 (let ((cell (nthcdr history-length command-history)))
1639 (if (consp cell) (setcdr cell nil)))))
1640 (execute-kbd-macro final prefixarg))
1642 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1643 (prog1 (call-interactively cmd record-flag keys)
1644 (when (and (symbolp cmd)
1645 (get cmd 'byte-obsolete-info)
1646 (not (get cmd 'command-execute-obsolete-warned)))
1647 (put cmd 'command-execute-obsolete-warned t)
1648 (message "%s" (macroexp--obsolete-warning
1649 cmd (get cmd 'byte-obsolete-info) "command")))))))))
1651 (defvar minibuffer-history nil
1652 "Default minibuffer history list.
1653 This is used for all minibuffer input
1654 except when an alternate history list is specified.
1656 Maximum length of the history list is determined by the value
1657 of `history-length', which see.")
1658 (defvar minibuffer-history-sexp-flag nil
1659 "Control whether history list elements are expressions or strings.
1660 If the value of this variable equals current minibuffer depth,
1661 they are expressions; otherwise they are strings.
1662 \(That convention is designed to do the right thing for
1663 recursive uses of the minibuffer.)")
1664 (setq minibuffer-history-variable 'minibuffer-history)
1665 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1666 (defvar minibuffer-history-search-history nil)
1668 (defvar minibuffer-text-before-history nil
1669 "Text that was in this minibuffer before any history commands.
1670 This is nil if there have not yet been any history commands
1671 in this use of the minibuffer.")
1673 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1675 (defun minibuffer-history-initialize ()
1676 (setq minibuffer-text-before-history nil))
1678 (defun minibuffer-avoid-prompt (_new _old)
1679 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1680 (constrain-to-field nil (point-max)))
1682 (defcustom minibuffer-history-case-insensitive-variables nil
1683 "Minibuffer history variables for which matching should ignore case.
1684 If a history variable is a member of this list, then the
1685 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1686 commands ignore case when searching it, regardless of `case-fold-search'."
1687 :type '(repeat variable)
1688 :group 'minibuffer)
1690 (defun previous-matching-history-element (regexp n)
1691 "Find the previous history element that matches REGEXP.
1692 \(Previous history elements refer to earlier actions.)
1693 With prefix argument N, search for Nth previous match.
1694 If N is negative, find the next or Nth next match.
1695 Normally, history elements are matched case-insensitively if
1696 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1697 makes the search case-sensitive.
1698 See also `minibuffer-history-case-insensitive-variables'."
1699 (interactive
1700 (let* ((enable-recursive-minibuffers t)
1701 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1703 minibuffer-local-map
1705 'minibuffer-history-search-history
1706 (car minibuffer-history-search-history))))
1707 ;; Use the last regexp specified, by default, if input is empty.
1708 (list (if (string= regexp "")
1709 (if minibuffer-history-search-history
1710 (car minibuffer-history-search-history)
1711 (user-error "No previous history search regexp"))
1712 regexp)
1713 (prefix-numeric-value current-prefix-arg))))
1714 (unless (zerop n)
1715 (if (and (zerop minibuffer-history-position)
1716 (null minibuffer-text-before-history))
1717 (setq minibuffer-text-before-history
1718 (minibuffer-contents-no-properties)))
1719 (let ((history (symbol-value minibuffer-history-variable))
1720 (case-fold-search
1721 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1722 ;; On some systems, ignore case for file names.
1723 (if (memq minibuffer-history-variable
1724 minibuffer-history-case-insensitive-variables)
1726 ;; Respect the user's setting for case-fold-search:
1727 case-fold-search)
1728 nil))
1729 prevpos
1730 match-string
1731 match-offset
1732 (pos minibuffer-history-position))
1733 (while (/= n 0)
1734 (setq prevpos pos)
1735 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1736 (when (= pos prevpos)
1737 (user-error (if (= pos 1)
1738 "No later matching history item"
1739 "No earlier matching history item")))
1740 (setq match-string
1741 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1742 (let ((print-level nil))
1743 (prin1-to-string (nth (1- pos) history)))
1744 (nth (1- pos) history)))
1745 (setq match-offset
1746 (if (< n 0)
1747 (and (string-match regexp match-string)
1748 (match-end 0))
1749 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1750 (match-beginning 1))))
1751 (when match-offset
1752 (setq n (+ n (if (< n 0) 1 -1)))))
1753 (setq minibuffer-history-position pos)
1754 (goto-char (point-max))
1755 (delete-minibuffer-contents)
1756 (insert match-string)
1757 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1758 (if (memq (car (car command-history)) '(previous-matching-history-element
1759 next-matching-history-element))
1760 (setq command-history (cdr command-history))))
1762 (defun next-matching-history-element (regexp n)
1763 "Find the next history element that matches REGEXP.
1764 \(The next history element refers to a more recent action.)
1765 With prefix argument N, search for Nth next match.
1766 If N is negative, find the previous or Nth previous match.
1767 Normally, history elements are matched case-insensitively if
1768 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1769 makes the search case-sensitive."
1770 (interactive
1771 (let* ((enable-recursive-minibuffers t)
1772 (regexp (read-from-minibuffer "Next element matching (regexp): "
1774 minibuffer-local-map
1776 'minibuffer-history-search-history
1777 (car minibuffer-history-search-history))))
1778 ;; Use the last regexp specified, by default, if input is empty.
1779 (list (if (string= regexp "")
1780 (if minibuffer-history-search-history
1781 (car minibuffer-history-search-history)
1782 (user-error "No previous history search regexp"))
1783 regexp)
1784 (prefix-numeric-value current-prefix-arg))))
1785 (previous-matching-history-element regexp (- n)))
1787 (defvar minibuffer-temporary-goal-position nil)
1789 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1790 "Function run by `goto-history-element' before consuming default values.
1791 This is useful to dynamically add more elements to the list of default values
1792 when `goto-history-element' reaches the end of this list.
1793 Before calling this function `goto-history-element' sets the variable
1794 `minibuffer-default-add-done' to t, so it will call this function only
1795 once. In special cases, when this function needs to be called more
1796 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1797 overriding the setting of this variable to t in `goto-history-element'.")
1799 (defvar minibuffer-default-add-done nil
1800 "When nil, add more elements to the end of the list of default values.
1801 The value nil causes `goto-history-element' to add more elements to
1802 the list of defaults when it reaches the end of this list. It does
1803 this by calling a function defined by `minibuffer-default-add-function'.")
1805 (make-variable-buffer-local 'minibuffer-default-add-done)
1807 (defun minibuffer-default-add-completions ()
1808 "Return a list of all completions without the default value.
1809 This function is used to add all elements of the completion table to
1810 the end of the list of defaults just after the default value."
1811 (let ((def minibuffer-default)
1812 (all (all-completions ""
1813 minibuffer-completion-table
1814 minibuffer-completion-predicate)))
1815 (if (listp def)
1816 (append def all)
1817 (cons def (delete def all)))))
1819 (defun goto-history-element (nabs)
1820 "Puts element of the minibuffer history in the minibuffer.
1821 The argument NABS specifies the absolute history position."
1822 (interactive "p")
1823 (when (and (not minibuffer-default-add-done)
1824 (functionp minibuffer-default-add-function)
1825 (< nabs (- (if (listp minibuffer-default)
1826 (length minibuffer-default)
1827 1))))
1828 (setq minibuffer-default-add-done t
1829 minibuffer-default (funcall minibuffer-default-add-function)))
1830 (let ((minimum (if minibuffer-default
1831 (- (if (listp minibuffer-default)
1832 (length minibuffer-default)
1835 elt minibuffer-returned-to-present)
1836 (if (and (zerop minibuffer-history-position)
1837 (null minibuffer-text-before-history))
1838 (setq minibuffer-text-before-history
1839 (minibuffer-contents-no-properties)))
1840 (if (< nabs minimum)
1841 (user-error (if minibuffer-default
1842 "End of defaults; no next item"
1843 "End of history; no default available")))
1844 (if (> nabs (length (symbol-value minibuffer-history-variable)))
1845 (user-error "Beginning of history; no preceding item"))
1846 (unless (memq last-command '(next-history-element
1847 previous-history-element))
1848 (let ((prompt-end (minibuffer-prompt-end)))
1849 (set (make-local-variable 'minibuffer-temporary-goal-position)
1850 (cond ((<= (point) prompt-end) prompt-end)
1851 ((eobp) nil)
1852 (t (point))))))
1853 (goto-char (point-max))
1854 (delete-minibuffer-contents)
1855 (setq minibuffer-history-position nabs)
1856 (cond ((< nabs 0)
1857 (setq elt (if (listp minibuffer-default)
1858 (nth (1- (abs nabs)) minibuffer-default)
1859 minibuffer-default)))
1860 ((= nabs 0)
1861 (setq elt (or minibuffer-text-before-history ""))
1862 (setq minibuffer-returned-to-present t)
1863 (setq minibuffer-text-before-history nil))
1864 (t (setq elt (nth (1- minibuffer-history-position)
1865 (symbol-value minibuffer-history-variable)))))
1866 (insert
1867 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1868 (not minibuffer-returned-to-present))
1869 (let ((print-level nil))
1870 (prin1-to-string elt))
1871 elt))
1872 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
1874 (defun next-history-element (n)
1875 "Puts next element of the minibuffer history in the minibuffer.
1876 With argument N, it uses the Nth following element."
1877 (interactive "p")
1878 (or (zerop n)
1879 (goto-history-element (- minibuffer-history-position n))))
1881 (defun previous-history-element (n)
1882 "Puts previous element of the minibuffer history in the minibuffer.
1883 With argument N, it uses the Nth previous element."
1884 (interactive "p")
1885 (or (zerop n)
1886 (goto-history-element (+ minibuffer-history-position n))))
1888 (defun next-complete-history-element (n)
1889 "Get next history element which completes the minibuffer before the point.
1890 The contents of the minibuffer after the point are deleted, and replaced
1891 by the new completion."
1892 (interactive "p")
1893 (let ((point-at-start (point)))
1894 (next-matching-history-element
1895 (concat
1896 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1898 ;; next-matching-history-element always puts us at (point-min).
1899 ;; Move to the position we were at before changing the buffer contents.
1900 ;; This is still sensible, because the text before point has not changed.
1901 (goto-char point-at-start)))
1903 (defun previous-complete-history-element (n)
1905 Get previous history element which completes the minibuffer before the point.
1906 The contents of the minibuffer after the point are deleted, and replaced
1907 by the new completion."
1908 (interactive "p")
1909 (next-complete-history-element (- n)))
1911 ;; For compatibility with the old subr of the same name.
1912 (defun minibuffer-prompt-width ()
1913 "Return the display width of the minibuffer prompt.
1914 Return 0 if current buffer is not a minibuffer."
1915 ;; Return the width of everything before the field at the end of
1916 ;; the buffer; this should be 0 for normal buffers.
1917 (1- (minibuffer-prompt-end)))
1919 ;; isearch minibuffer history
1920 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
1922 (defvar minibuffer-history-isearch-message-overlay)
1923 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
1925 (defun minibuffer-history-isearch-setup ()
1926 "Set up a minibuffer for using isearch to search the minibuffer history.
1927 Intended to be added to `minibuffer-setup-hook'."
1928 (set (make-local-variable 'isearch-search-fun-function)
1929 'minibuffer-history-isearch-search)
1930 (set (make-local-variable 'isearch-message-function)
1931 'minibuffer-history-isearch-message)
1932 (set (make-local-variable 'isearch-wrap-function)
1933 'minibuffer-history-isearch-wrap)
1934 (set (make-local-variable 'isearch-push-state-function)
1935 'minibuffer-history-isearch-push-state)
1936 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
1938 (defun minibuffer-history-isearch-end ()
1939 "Clean up the minibuffer after terminating isearch in the minibuffer."
1940 (if minibuffer-history-isearch-message-overlay
1941 (delete-overlay minibuffer-history-isearch-message-overlay)))
1943 (defun minibuffer-history-isearch-search ()
1944 "Return the proper search function, for isearch in minibuffer history."
1945 (lambda (string bound noerror)
1946 (let ((search-fun
1947 ;; Use standard functions to search within minibuffer text
1948 (isearch-search-fun-default))
1949 found)
1950 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1951 ;; searching forward. Lazy-highlight calls this lambda with the
1952 ;; bound arg, so skip the minibuffer prompt.
1953 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
1954 (goto-char (minibuffer-prompt-end)))
1956 ;; 1. First try searching in the initial minibuffer text
1957 (funcall search-fun string
1958 (if isearch-forward bound (minibuffer-prompt-end))
1959 noerror)
1960 ;; 2. If the above search fails, start putting next/prev history
1961 ;; elements in the minibuffer successively, and search the string
1962 ;; in them. Do this only when bound is nil (i.e. not while
1963 ;; lazy-highlighting search strings in the current minibuffer text).
1964 (unless bound
1965 (condition-case nil
1966 (progn
1967 (while (not found)
1968 (cond (isearch-forward
1969 (next-history-element 1)
1970 (goto-char (minibuffer-prompt-end)))
1972 (previous-history-element 1)
1973 (goto-char (point-max))))
1974 (setq isearch-barrier (point) isearch-opoint (point))
1975 ;; After putting the next/prev history element, search
1976 ;; the string in them again, until next-history-element
1977 ;; or previous-history-element raises an error at the
1978 ;; beginning/end of history.
1979 (setq found (funcall search-fun string
1980 (unless isearch-forward
1981 ;; For backward search, don't search
1982 ;; in the minibuffer prompt
1983 (minibuffer-prompt-end))
1984 noerror)))
1985 ;; Return point of the new search result
1986 (point))
1987 ;; Return nil when next(prev)-history-element fails
1988 (error nil)))))))
1990 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
1991 "Display the minibuffer history search prompt.
1992 If there are no search errors, this function displays an overlay with
1993 the isearch prompt which replaces the original minibuffer prompt.
1994 Otherwise, it displays the standard isearch message returned from
1995 the function `isearch-message'."
1996 (if (not (and (minibufferp) isearch-success (not isearch-error)))
1997 ;; Use standard function `isearch-message' when not in the minibuffer,
1998 ;; or search fails, or has an error (like incomplete regexp).
1999 ;; This function overwrites minibuffer text with isearch message,
2000 ;; so it's possible to see what is wrong in the search string.
2001 (isearch-message c-q-hack ellipsis)
2002 ;; Otherwise, put the overlay with the standard isearch prompt over
2003 ;; the initial minibuffer prompt.
2004 (if (overlayp minibuffer-history-isearch-message-overlay)
2005 (move-overlay minibuffer-history-isearch-message-overlay
2006 (point-min) (minibuffer-prompt-end))
2007 (setq minibuffer-history-isearch-message-overlay
2008 (make-overlay (point-min) (minibuffer-prompt-end)))
2009 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2010 (overlay-put minibuffer-history-isearch-message-overlay
2011 'display (isearch-message-prefix c-q-hack ellipsis))
2012 ;; And clear any previous isearch message.
2013 (message "")))
2015 (defun minibuffer-history-isearch-wrap ()
2016 "Wrap the minibuffer history search when search fails.
2017 Move point to the first history element for a forward search,
2018 or to the last history element for a backward search."
2019 ;; When `minibuffer-history-isearch-search' fails on reaching the
2020 ;; beginning/end of the history, wrap the search to the first/last
2021 ;; minibuffer history element.
2022 (if isearch-forward
2023 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2024 (goto-history-element 0))
2025 (setq isearch-success t)
2026 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2028 (defun minibuffer-history-isearch-push-state ()
2029 "Save a function restoring the state of minibuffer history search.
2030 Save `minibuffer-history-position' to the additional state parameter
2031 in the search status stack."
2032 (let ((pos minibuffer-history-position))
2033 (lambda (cmd)
2034 (minibuffer-history-isearch-pop-state cmd pos))))
2036 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2037 "Restore the minibuffer history search state.
2038 Go to the history element by the absolute history position HIST-POS."
2039 (goto-history-element hist-pos))
2042 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2043 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2045 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2046 "Table mapping redo records to the corresponding undo one.
2047 A redo record for undo-in-region maps to t.
2048 A redo record for ordinary undo maps to the following (earlier) undo.")
2050 (defvar undo-in-region nil
2051 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2053 (defvar undo-no-redo nil
2054 "If t, `undo' doesn't go through redo entries.")
2056 (defvar pending-undo-list nil
2057 "Within a run of consecutive undo commands, list remaining to be undone.
2058 If t, we undid all the way to the end of it.")
2060 (defun undo (&optional arg)
2061 "Undo some previous changes.
2062 Repeat this command to undo more changes.
2063 A numeric ARG serves as a repeat count.
2065 In Transient Mark mode when the mark is active, only undo changes within
2066 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2067 as an argument limits undo to changes within the current region."
2068 (interactive "*P")
2069 ;; Make last-command indicate for the next command that this was an undo.
2070 ;; That way, another undo will undo more.
2071 ;; If we get to the end of the undo history and get an error,
2072 ;; another undo command will find the undo history empty
2073 ;; and will get another error. To begin undoing the undos,
2074 ;; you must type some other command.
2075 (let* ((modified (buffer-modified-p))
2076 ;; For an indirect buffer, look in the base buffer for the
2077 ;; auto-save data.
2078 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2079 (recent-save (with-current-buffer base-buffer
2080 (recent-auto-save-p)))
2081 message)
2082 ;; If we get an error in undo-start,
2083 ;; the next command should not be a "consecutive undo".
2084 ;; So set `this-command' to something other than `undo'.
2085 (setq this-command 'undo-start)
2087 (unless (and (eq last-command 'undo)
2088 (or (eq pending-undo-list t)
2089 ;; If something (a timer or filter?) changed the buffer
2090 ;; since the previous command, don't continue the undo seq.
2091 (let ((list buffer-undo-list))
2092 (while (eq (car list) nil)
2093 (setq list (cdr list)))
2094 ;; If the last undo record made was made by undo
2095 ;; it shows nothing else happened in between.
2096 (gethash list undo-equiv-table))))
2097 (setq undo-in-region
2098 (or (region-active-p) (and arg (not (numberp arg)))))
2099 (if undo-in-region
2100 (undo-start (region-beginning) (region-end))
2101 (undo-start))
2102 ;; get rid of initial undo boundary
2103 (undo-more 1))
2104 ;; If we got this far, the next command should be a consecutive undo.
2105 (setq this-command 'undo)
2106 ;; Check to see whether we're hitting a redo record, and if
2107 ;; so, ask the user whether she wants to skip the redo/undo pair.
2108 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2109 (or (eq (selected-window) (minibuffer-window))
2110 (setq message (format "%s%s!"
2111 (if (or undo-no-redo (not equiv))
2112 "Undo" "Redo")
2113 (if undo-in-region " in region" ""))))
2114 (when (and (consp equiv) undo-no-redo)
2115 ;; The equiv entry might point to another redo record if we have done
2116 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2117 (while (let ((next (gethash equiv undo-equiv-table)))
2118 (if next (setq equiv next))))
2119 (setq pending-undo-list equiv)))
2120 (undo-more
2121 (if (numberp arg)
2122 (prefix-numeric-value arg)
2124 ;; Record the fact that the just-generated undo records come from an
2125 ;; undo operation--that is, they are redo records.
2126 ;; In the ordinary case (not within a region), map the redo
2127 ;; record to the following undos.
2128 ;; I don't know how to do that in the undo-in-region case.
2129 (let ((list buffer-undo-list))
2130 ;; Strip any leading undo boundaries there might be, like we do
2131 ;; above when checking.
2132 (while (eq (car list) nil)
2133 (setq list (cdr list)))
2134 (puthash list (if undo-in-region t pending-undo-list)
2135 undo-equiv-table))
2136 ;; Don't specify a position in the undo record for the undo command.
2137 ;; Instead, undoing this should move point to where the change is.
2138 (let ((tail buffer-undo-list)
2139 (prev nil))
2140 (while (car tail)
2141 (when (integerp (car tail))
2142 (let ((pos (car tail)))
2143 (if prev
2144 (setcdr prev (cdr tail))
2145 (setq buffer-undo-list (cdr tail)))
2146 (setq tail (cdr tail))
2147 (while (car tail)
2148 (if (eq pos (car tail))
2149 (if prev
2150 (setcdr prev (cdr tail))
2151 (setq buffer-undo-list (cdr tail)))
2152 (setq prev tail))
2153 (setq tail (cdr tail)))
2154 (setq tail nil)))
2155 (setq prev tail tail (cdr tail))))
2156 ;; Record what the current undo list says,
2157 ;; so the next command can tell if the buffer was modified in between.
2158 (and modified (not (buffer-modified-p))
2159 (with-current-buffer base-buffer
2160 (delete-auto-save-file-if-necessary recent-save)))
2161 ;; Display a message announcing success.
2162 (if message
2163 (message "%s" message))))
2165 (defun buffer-disable-undo (&optional buffer)
2166 "Make BUFFER stop keeping undo information.
2167 No argument or nil as argument means do this for the current buffer."
2168 (interactive)
2169 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2170 (setq buffer-undo-list t)))
2172 (defun undo-only (&optional arg)
2173 "Undo some previous changes.
2174 Repeat this command to undo more changes.
2175 A numeric ARG serves as a repeat count.
2176 Contrary to `undo', this will not redo a previous undo."
2177 (interactive "*p")
2178 (let ((undo-no-redo t)) (undo arg)))
2180 (defvar undo-in-progress nil
2181 "Non-nil while performing an undo.
2182 Some change-hooks test this variable to do something different.")
2184 (defun undo-more (n)
2185 "Undo back N undo-boundaries beyond what was already undone recently.
2186 Call `undo-start' to get ready to undo recent changes,
2187 then call `undo-more' one or more times to undo them."
2188 (or (listp pending-undo-list)
2189 (user-error (concat "No further undo information"
2190 (and undo-in-region " for region"))))
2191 (let ((undo-in-progress t))
2192 ;; Note: The following, while pulling elements off
2193 ;; `pending-undo-list' will call primitive change functions which
2194 ;; will push more elements onto `buffer-undo-list'.
2195 (setq pending-undo-list (primitive-undo n pending-undo-list))
2196 (if (null pending-undo-list)
2197 (setq pending-undo-list t))))
2199 (defun primitive-undo (n list)
2200 "Undo N records from the front of the list LIST.
2201 Return what remains of the list."
2203 ;; This is a good feature, but would make undo-start
2204 ;; unable to do what is expected.
2205 ;;(when (null (car (list)))
2206 ;; ;; If the head of the list is a boundary, it is the boundary
2207 ;; ;; preceding this command. Get rid of it and don't count it.
2208 ;; (setq list (cdr list))))
2210 (let ((arg n)
2211 ;; In a writable buffer, enable undoing read-only text that is
2212 ;; so because of text properties.
2213 (inhibit-read-only t)
2214 ;; Don't let `intangible' properties interfere with undo.
2215 (inhibit-point-motion-hooks t)
2216 ;; We use oldlist only to check for EQ. ++kfs
2217 (oldlist buffer-undo-list)
2218 (did-apply nil)
2219 (next nil))
2220 (while (> arg 0)
2221 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2222 ;; Handle an integer by setting point to that value.
2223 (pcase next
2224 ((pred integerp) (goto-char next))
2225 ;; Element (t . TIME) records previous modtime.
2226 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2227 ;; UNKNOWN_MODTIME_NSECS.
2228 (`(t . ,time)
2229 ;; If this records an obsolete save
2230 ;; (not matching the actual disk file)
2231 ;; then don't mark unmodified.
2232 (when (or (equal time (visited-file-modtime))
2233 (and (consp time)
2234 (equal (list (car time) (cdr time))
2235 (visited-file-modtime))))
2236 (when (fboundp 'unlock-buffer)
2237 (unlock-buffer))
2238 (set-buffer-modified-p nil)))
2239 ;; Element (nil PROP VAL BEG . END) is property change.
2240 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2241 (when (or (> (point-min) beg) (< (point-max) end))
2242 (error "Changes to be undone are outside visible portion of buffer"))
2243 (put-text-property beg end prop val))
2244 ;; Element (BEG . END) means range was inserted.
2245 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2246 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2247 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2248 (when (or (> (point-min) beg) (< (point-max) end))
2249 (error "Changes to be undone are outside visible portion of buffer"))
2250 ;; Set point first thing, so that undoing this undo
2251 ;; does not send point back to where it is now.
2252 (goto-char beg)
2253 (delete-region beg end))
2254 ;; Element (apply FUN . ARGS) means call FUN to undo.
2255 (`(apply . ,fun-args)
2256 (let ((currbuff (current-buffer)))
2257 (if (integerp (car fun-args))
2258 ;; Long format: (apply DELTA START END FUN . ARGS).
2259 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2260 (start-mark (copy-marker start nil))
2261 (end-mark (copy-marker end t)))
2262 (when (or (> (point-min) start) (< (point-max) end))
2263 (error "Changes to be undone are outside visible portion of buffer"))
2264 (apply fun args) ;; Use `save-current-buffer'?
2265 ;; Check that the function did what the entry
2266 ;; said it would do.
2267 (unless (and (= start start-mark)
2268 (= (+ delta end) end-mark))
2269 (error "Changes to be undone by function different than announced"))
2270 (set-marker start-mark nil)
2271 (set-marker end-mark nil))
2272 (apply fun-args))
2273 (unless (eq currbuff (current-buffer))
2274 (error "Undo function switched buffer"))
2275 (setq did-apply t)))
2276 ;; Element (STRING . POS) means STRING was deleted.
2277 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2278 (when (let ((apos (abs pos)))
2279 (or (< apos (point-min)) (> apos (point-max))))
2280 (error "Changes to be undone are outside visible portion of buffer"))
2281 (if (< pos 0)
2282 (progn
2283 (goto-char (- pos))
2284 (insert string))
2285 (goto-char pos)
2286 ;; Now that we record marker adjustments
2287 ;; (caused by deletion) for undo,
2288 ;; we should always insert after markers,
2289 ;; so that undoing the marker adjustments
2290 ;; put the markers back in the right place.
2291 (insert string)
2292 (goto-char pos)))
2293 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2294 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2295 (when (marker-buffer marker)
2296 (set-marker marker
2297 (- marker offset)
2298 (marker-buffer marker))))
2299 (_ (error "Unrecognized entry in undo list %S" next))))
2300 (setq arg (1- arg)))
2301 ;; Make sure an apply entry produces at least one undo entry,
2302 ;; so the test in `undo' for continuing an undo series
2303 ;; will work right.
2304 (if (and did-apply
2305 (eq oldlist buffer-undo-list))
2306 (setq buffer-undo-list
2307 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2308 list)
2310 ;; Deep copy of a list
2311 (defun undo-copy-list (list)
2312 "Make a copy of undo list LIST."
2313 (mapcar 'undo-copy-list-1 list))
2315 (defun undo-copy-list-1 (elt)
2316 (if (consp elt)
2317 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2318 elt))
2320 (defun undo-start (&optional beg end)
2321 "Set `pending-undo-list' to the front of the undo list.
2322 The next call to `undo-more' will undo the most recently made change.
2323 If BEG and END are specified, then only undo elements
2324 that apply to text between BEG and END are used; other undo elements
2325 are ignored. If BEG and END are nil, all undo elements are used."
2326 (if (eq buffer-undo-list t)
2327 (user-error "No undo information in this buffer"))
2328 (setq pending-undo-list
2329 (if (and beg end (not (= beg end)))
2330 (undo-make-selective-list (min beg end) (max beg end))
2331 buffer-undo-list)))
2333 (defvar undo-adjusted-markers)
2335 (defun undo-make-selective-list (start end)
2336 "Return a list of undo elements for the region START to END.
2337 The elements come from `buffer-undo-list', but we keep only
2338 the elements inside this region, and discard those outside this region.
2339 If we find an element that crosses an edge of this region,
2340 we stop and ignore all further elements."
2341 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
2342 (undo-list (list nil))
2343 undo-adjusted-markers
2344 some-rejected
2345 undo-elt temp-undo-list delta)
2346 (while undo-list-copy
2347 (setq undo-elt (car undo-list-copy))
2348 (let ((keep-this
2349 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
2350 ;; This is a "was unmodified" element.
2351 ;; Keep it if we have kept everything thus far.
2352 (not some-rejected))
2354 (undo-elt-in-region undo-elt start end)))))
2355 (if keep-this
2356 (progn
2357 (setq end (+ end (cdr (undo-delta undo-elt))))
2358 ;; Don't put two nils together in the list
2359 (if (not (and (eq (car undo-list) nil)
2360 (eq undo-elt nil)))
2361 (setq undo-list (cons undo-elt undo-list))))
2362 (if (undo-elt-crosses-region undo-elt start end)
2363 (setq undo-list-copy nil)
2364 (setq some-rejected t)
2365 (setq temp-undo-list (cdr undo-list-copy))
2366 (setq delta (undo-delta undo-elt))
2368 (when (/= (cdr delta) 0)
2369 (let ((position (car delta))
2370 (offset (cdr delta)))
2372 ;; Loop down the earlier events adjusting their buffer
2373 ;; positions to reflect the fact that a change to the buffer
2374 ;; isn't being undone. We only need to process those element
2375 ;; types which undo-elt-in-region will return as being in
2376 ;; the region since only those types can ever get into the
2377 ;; output
2379 (while temp-undo-list
2380 (setq undo-elt (car temp-undo-list))
2381 (cond ((integerp undo-elt)
2382 (if (>= undo-elt position)
2383 (setcar temp-undo-list (- undo-elt offset))))
2384 ((atom undo-elt) nil)
2385 ((stringp (car undo-elt))
2386 ;; (TEXT . POSITION)
2387 (let ((text-pos (abs (cdr undo-elt)))
2388 (point-at-end (< (cdr undo-elt) 0 )))
2389 (if (>= text-pos position)
2390 (setcdr undo-elt (* (if point-at-end -1 1)
2391 (- text-pos offset))))))
2392 ((integerp (car undo-elt))
2393 ;; (BEGIN . END)
2394 (when (>= (car undo-elt) position)
2395 (setcar undo-elt (- (car undo-elt) offset))
2396 (setcdr undo-elt (- (cdr undo-elt) offset))))
2397 ((null (car undo-elt))
2398 ;; (nil PROPERTY VALUE BEG . END)
2399 (let ((tail (nthcdr 3 undo-elt)))
2400 (when (>= (car tail) position)
2401 (setcar tail (- (car tail) offset))
2402 (setcdr tail (- (cdr tail) offset))))))
2403 (setq temp-undo-list (cdr temp-undo-list))))))))
2404 (setq undo-list-copy (cdr undo-list-copy)))
2405 (nreverse undo-list)))
2407 (defun undo-elt-in-region (undo-elt start end)
2408 "Determine whether UNDO-ELT falls inside the region START ... END.
2409 If it crosses the edge, we return nil."
2410 (cond ((integerp undo-elt)
2411 (and (>= undo-elt start)
2412 (<= undo-elt end)))
2413 ((eq undo-elt nil)
2415 ((atom undo-elt)
2416 nil)
2417 ((stringp (car undo-elt))
2418 ;; (TEXT . POSITION)
2419 (and (>= (abs (cdr undo-elt)) start)
2420 (< (abs (cdr undo-elt)) end)))
2421 ((and (consp undo-elt) (markerp (car undo-elt)))
2422 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
2423 ;; See if MARKER is inside the region.
2424 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
2425 (unless alist-elt
2426 (setq alist-elt (cons (car undo-elt)
2427 (marker-position (car undo-elt))))
2428 (setq undo-adjusted-markers
2429 (cons alist-elt undo-adjusted-markers)))
2430 (and (cdr alist-elt)
2431 (>= (cdr alist-elt) start)
2432 (<= (cdr alist-elt) end))))
2433 ((null (car undo-elt))
2434 ;; (nil PROPERTY VALUE BEG . END)
2435 (let ((tail (nthcdr 3 undo-elt)))
2436 (and (>= (car tail) start)
2437 (<= (cdr tail) end))))
2438 ((integerp (car undo-elt))
2439 ;; (BEGIN . END)
2440 (and (>= (car undo-elt) start)
2441 (<= (cdr undo-elt) end)))))
2443 (defun undo-elt-crosses-region (undo-elt start end)
2444 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2445 This assumes we have already decided that UNDO-ELT
2446 is not *inside* the region START...END."
2447 (cond ((atom undo-elt) nil)
2448 ((null (car undo-elt))
2449 ;; (nil PROPERTY VALUE BEG . END)
2450 (let ((tail (nthcdr 3 undo-elt)))
2451 (and (< (car tail) end)
2452 (> (cdr tail) start))))
2453 ((integerp (car undo-elt))
2454 ;; (BEGIN . END)
2455 (and (< (car undo-elt) end)
2456 (> (cdr undo-elt) start)))))
2458 ;; Return the first affected buffer position and the delta for an undo element
2459 ;; delta is defined as the change in subsequent buffer positions if we *did*
2460 ;; the undo.
2461 (defun undo-delta (undo-elt)
2462 (if (consp undo-elt)
2463 (cond ((stringp (car undo-elt))
2464 ;; (TEXT . POSITION)
2465 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2466 ((integerp (car undo-elt))
2467 ;; (BEGIN . END)
2468 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2470 '(0 . 0)))
2471 '(0 . 0)))
2473 (defcustom undo-ask-before-discard nil
2474 "If non-nil ask about discarding undo info for the current command.
2475 Normally, Emacs discards the undo info for the current command if
2476 it exceeds `undo-outer-limit'. But if you set this option
2477 non-nil, it asks in the echo area whether to discard the info.
2478 If you answer no, there is a slight risk that Emacs might crash, so
2479 only do it if you really want to undo the command.
2481 This option is mainly intended for debugging. You have to be
2482 careful if you use it for other purposes. Garbage collection is
2483 inhibited while the question is asked, meaning that Emacs might
2484 leak memory. So you should make sure that you do not wait
2485 excessively long before answering the question."
2486 :type 'boolean
2487 :group 'undo
2488 :version "22.1")
2490 (defvar undo-extra-outer-limit nil
2491 "If non-nil, an extra level of size that's ok in an undo item.
2492 We don't ask the user about truncating the undo list until the
2493 current item gets bigger than this amount.
2495 This variable only matters if `undo-ask-before-discard' is non-nil.")
2496 (make-variable-buffer-local 'undo-extra-outer-limit)
2498 ;; When the first undo batch in an undo list is longer than
2499 ;; undo-outer-limit, this function gets called to warn the user that
2500 ;; the undo info for the current command was discarded. Garbage
2501 ;; collection is inhibited around the call, so it had better not do a
2502 ;; lot of consing.
2503 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2504 (defun undo-outer-limit-truncate (size)
2505 (if undo-ask-before-discard
2506 (when (or (null undo-extra-outer-limit)
2507 (> size undo-extra-outer-limit))
2508 ;; Don't ask the question again unless it gets even bigger.
2509 ;; This applies, in particular, if the user quits from the question.
2510 ;; Such a quit quits out of GC, but something else will call GC
2511 ;; again momentarily. It will call this function again,
2512 ;; but we don't want to ask the question again.
2513 (setq undo-extra-outer-limit (+ size 50000))
2514 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2515 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2516 (buffer-name) size)))
2517 (progn (setq buffer-undo-list nil)
2518 (setq undo-extra-outer-limit nil)
2520 nil))
2521 (display-warning '(undo discard-info)
2522 (concat
2523 (format "Buffer `%s' undo info was %d bytes long.\n"
2524 (buffer-name) size)
2525 "The undo info was discarded because it exceeded \
2526 `undo-outer-limit'.
2528 This is normal if you executed a command that made a huge change
2529 to the buffer. In that case, to prevent similar problems in the
2530 future, set `undo-outer-limit' to a value that is large enough to
2531 cover the maximum size of normal changes you expect a single
2532 command to make, but not so large that it might exceed the
2533 maximum memory allotted to Emacs.
2535 If you did not execute any such command, the situation is
2536 probably due to a bug and you should report it.
2538 You can disable the popping up of this buffer by adding the entry
2539 \(undo discard-info) to the user option `warning-suppress-types',
2540 which is defined in the `warnings' library.\n")
2541 :warning)
2542 (setq buffer-undo-list nil)
2545 (defvar shell-command-history nil
2546 "History list for some commands that read shell commands.
2548 Maximum length of the history list is determined by the value
2549 of `history-length', which see.")
2551 (defvar shell-command-switch (purecopy "-c")
2552 "Switch used to have the shell execute its command line argument.")
2554 (defvar shell-command-default-error-buffer nil
2555 "Buffer name for `shell-command' and `shell-command-on-region' error output.
2556 This buffer is used when `shell-command' or `shell-command-on-region'
2557 is run interactively. A value of nil means that output to stderr and
2558 stdout will be intermixed in the output stream.")
2560 (declare-function mailcap-file-default-commands "mailcap" (files))
2561 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2563 (defun minibuffer-default-add-shell-commands ()
2564 "Return a list of all commands associated with the current file.
2565 This function is used to add all related commands retrieved by `mailcap'
2566 to the end of the list of defaults just after the default value."
2567 (interactive)
2568 (let* ((filename (if (listp minibuffer-default)
2569 (car minibuffer-default)
2570 minibuffer-default))
2571 (commands (and filename (require 'mailcap nil t)
2572 (mailcap-file-default-commands (list filename)))))
2573 (setq commands (mapcar (lambda (command)
2574 (concat command " " filename))
2575 commands))
2576 (if (listp minibuffer-default)
2577 (append minibuffer-default commands)
2578 (cons minibuffer-default commands))))
2580 (declare-function shell-completion-vars "shell" ())
2582 (defvar minibuffer-local-shell-command-map
2583 (let ((map (make-sparse-keymap)))
2584 (set-keymap-parent map minibuffer-local-map)
2585 (define-key map "\t" 'completion-at-point)
2586 map)
2587 "Keymap used for completing shell commands in minibuffer.")
2589 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
2590 "Read a shell command from the minibuffer.
2591 The arguments are the same as the ones of `read-from-minibuffer',
2592 except READ and KEYMAP are missing and HIST defaults
2593 to `shell-command-history'."
2594 (require 'shell)
2595 (minibuffer-with-setup-hook
2596 (lambda ()
2597 (shell-completion-vars)
2598 (set (make-local-variable 'minibuffer-default-add-function)
2599 'minibuffer-default-add-shell-commands))
2600 (apply 'read-from-minibuffer prompt initial-contents
2601 minibuffer-local-shell-command-map
2603 (or hist 'shell-command-history)
2604 args)))
2606 (defcustom async-shell-command-buffer 'confirm-new-buffer
2607 "What to do when the output buffer is used by another shell command.
2608 This option specifies how to resolve the conflict where a new command
2609 wants to direct its output to the buffer `*Async Shell Command*',
2610 but this buffer is already taken by another running shell command.
2612 The value `confirm-kill-process' is used to ask for confirmation before
2613 killing the already running process and running a new process
2614 in the same buffer, `confirm-new-buffer' for confirmation before running
2615 the command in a new buffer with a name other than the default buffer name,
2616 `new-buffer' for doing the same without confirmation,
2617 `confirm-rename-buffer' for confirmation before renaming the existing
2618 output buffer and running a new command in the default buffer,
2619 `rename-buffer' for doing the same without confirmation."
2620 :type '(choice (const :tag "Confirm killing of running command"
2621 confirm-kill-process)
2622 (const :tag "Confirm creation of a new buffer"
2623 confirm-new-buffer)
2624 (const :tag "Create a new buffer"
2625 new-buffer)
2626 (const :tag "Confirm renaming of existing buffer"
2627 confirm-rename-buffer)
2628 (const :tag "Rename the existing buffer"
2629 rename-buffer))
2630 :group 'shell
2631 :version "24.3")
2633 (defun async-shell-command (command &optional output-buffer error-buffer)
2634 "Execute string COMMAND asynchronously in background.
2636 Like `shell-command', but adds `&' at the end of COMMAND
2637 to execute it asynchronously.
2639 The output appears in the buffer `*Async Shell Command*'.
2640 That buffer is in shell mode.
2642 In Elisp, you will often be better served by calling `start-process'
2643 directly, since it offers more control and does not impose the use of a
2644 shell (with its need to quote arguments)."
2645 (interactive
2646 (list
2647 (read-shell-command "Async shell command: " nil nil
2648 (let ((filename
2649 (cond
2650 (buffer-file-name)
2651 ((eq major-mode 'dired-mode)
2652 (dired-get-filename nil t)))))
2653 (and filename (file-relative-name filename))))
2654 current-prefix-arg
2655 shell-command-default-error-buffer))
2656 (unless (string-match "&[ \t]*\\'" command)
2657 (setq command (concat command " &")))
2658 (shell-command command output-buffer error-buffer))
2660 (defun shell-command (command &optional output-buffer error-buffer)
2661 "Execute string COMMAND in inferior shell; display output, if any.
2662 With prefix argument, insert the COMMAND's output at point.
2664 If COMMAND ends in `&', execute it asynchronously.
2665 The output appears in the buffer `*Async Shell Command*'.
2666 That buffer is in shell mode. You can also use
2667 `async-shell-command' that automatically adds `&'.
2669 Otherwise, COMMAND is executed synchronously. The output appears in
2670 the buffer `*Shell Command Output*'. If the output is short enough to
2671 display in the echo area (which is determined by the variables
2672 `resize-mini-windows' and `max-mini-window-height'), it is shown
2673 there, but it is nonetheless available in buffer `*Shell Command
2674 Output*' even though that buffer is not automatically displayed.
2676 To specify a coding system for converting non-ASCII characters
2677 in the shell command output, use \\[universal-coding-system-argument] \
2678 before this command.
2680 Noninteractive callers can specify coding systems by binding
2681 `coding-system-for-read' and `coding-system-for-write'.
2683 The optional second argument OUTPUT-BUFFER, if non-nil,
2684 says to put the output in some other buffer.
2685 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2686 If OUTPUT-BUFFER is not a buffer and not nil,
2687 insert output in current buffer. (This cannot be done asynchronously.)
2688 In either case, the buffer is first erased, and the output is
2689 inserted after point (leaving mark after it).
2691 If the command terminates without error, but generates output,
2692 and you did not specify \"insert it in the current buffer\",
2693 the output can be displayed in the echo area or in its buffer.
2694 If the output is short enough to display in the echo area
2695 \(determined by the variable `max-mini-window-height' if
2696 `resize-mini-windows' is non-nil), it is shown there.
2697 Otherwise,the buffer containing the output is displayed.
2699 If there is output and an error, and you did not specify \"insert it
2700 in the current buffer\", a message about the error goes at the end
2701 of the output.
2703 If there is no output, or if output is inserted in the current buffer,
2704 then `*Shell Command Output*' is deleted.
2706 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2707 or buffer name to which to direct the command's standard error output.
2708 If it is nil, error output is mingled with regular output.
2709 In an interactive call, the variable `shell-command-default-error-buffer'
2710 specifies the value of ERROR-BUFFER.
2712 In Elisp, you will often be better served by calling `call-process' or
2713 `start-process' directly, since it offers more control and does not impose
2714 the use of a shell (with its need to quote arguments)."
2716 (interactive
2717 (list
2718 (read-shell-command "Shell command: " nil nil
2719 (let ((filename
2720 (cond
2721 (buffer-file-name)
2722 ((eq major-mode 'dired-mode)
2723 (dired-get-filename nil t)))))
2724 (and filename (file-relative-name filename))))
2725 current-prefix-arg
2726 shell-command-default-error-buffer))
2727 ;; Look for a handler in case default-directory is a remote file name.
2728 (let ((handler
2729 (find-file-name-handler (directory-file-name default-directory)
2730 'shell-command)))
2731 (if handler
2732 (funcall handler 'shell-command command output-buffer error-buffer)
2733 (if (and output-buffer
2734 (not (or (bufferp output-buffer) (stringp output-buffer))))
2735 ;; Output goes in current buffer.
2736 (let ((error-file
2737 (if error-buffer
2738 (make-temp-file
2739 (expand-file-name "scor"
2740 (or small-temporary-file-directory
2741 temporary-file-directory)))
2742 nil)))
2743 (barf-if-buffer-read-only)
2744 (push-mark nil t)
2745 ;; We do not use -f for csh; we will not support broken use of
2746 ;; .cshrcs. Even the BSD csh manual says to use
2747 ;; "if ($?prompt) exit" before things which are not useful
2748 ;; non-interactively. Besides, if someone wants their other
2749 ;; aliases for shell commands then they can still have them.
2750 (call-process shell-file-name nil
2751 (if error-file
2752 (list t error-file)
2754 nil shell-command-switch command)
2755 (when (and error-file (file-exists-p error-file))
2756 (if (< 0 (nth 7 (file-attributes error-file)))
2757 (with-current-buffer (get-buffer-create error-buffer)
2758 (let ((pos-from-end (- (point-max) (point))))
2759 (or (bobp)
2760 (insert "\f\n"))
2761 ;; Do no formatting while reading error file,
2762 ;; because that can run a shell command, and we
2763 ;; don't want that to cause an infinite recursion.
2764 (format-insert-file error-file nil)
2765 ;; Put point after the inserted errors.
2766 (goto-char (- (point-max) pos-from-end)))
2767 (display-buffer (current-buffer))))
2768 (delete-file error-file))
2769 ;; This is like exchange-point-and-mark, but doesn't
2770 ;; activate the mark. It is cleaner to avoid activation,
2771 ;; even though the command loop would deactivate the mark
2772 ;; because we inserted text.
2773 (goto-char (prog1 (mark t)
2774 (set-marker (mark-marker) (point)
2775 (current-buffer)))))
2776 ;; Output goes in a separate buffer.
2777 ;; Preserve the match data in case called from a program.
2778 (save-match-data
2779 (if (string-match "[ \t]*&[ \t]*\\'" command)
2780 ;; Command ending with ampersand means asynchronous.
2781 (let ((buffer (get-buffer-create
2782 (or output-buffer "*Async Shell Command*")))
2783 (directory default-directory)
2784 proc)
2785 ;; Remove the ampersand.
2786 (setq command (substring command 0 (match-beginning 0)))
2787 ;; Ask the user what to do with already running process.
2788 (setq proc (get-buffer-process buffer))
2789 (when proc
2790 (cond
2791 ((eq async-shell-command-buffer 'confirm-kill-process)
2792 ;; If will kill a process, query first.
2793 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
2794 (kill-process proc)
2795 (error "Shell command in progress")))
2796 ((eq async-shell-command-buffer 'confirm-new-buffer)
2797 ;; If will create a new buffer, query first.
2798 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
2799 (setq buffer (generate-new-buffer
2800 (or output-buffer "*Async Shell Command*")))
2801 (error "Shell command in progress")))
2802 ((eq async-shell-command-buffer 'new-buffer)
2803 ;; It will create a new buffer.
2804 (setq buffer (generate-new-buffer
2805 (or output-buffer "*Async Shell Command*"))))
2806 ((eq async-shell-command-buffer 'confirm-rename-buffer)
2807 ;; If will rename the buffer, query first.
2808 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
2809 (progn
2810 (with-current-buffer buffer
2811 (rename-uniquely))
2812 (setq buffer (get-buffer-create
2813 (or output-buffer "*Async Shell Command*"))))
2814 (error "Shell command in progress")))
2815 ((eq async-shell-command-buffer 'rename-buffer)
2816 ;; It will rename the buffer.
2817 (with-current-buffer buffer
2818 (rename-uniquely))
2819 (setq buffer (get-buffer-create
2820 (or output-buffer "*Async Shell Command*"))))))
2821 (with-current-buffer buffer
2822 (setq buffer-read-only nil)
2823 ;; Setting buffer-read-only to nil doesn't suffice
2824 ;; if some text has a non-nil read-only property,
2825 ;; which comint sometimes adds for prompts.
2826 (let ((inhibit-read-only t))
2827 (erase-buffer))
2828 (display-buffer buffer)
2829 (setq default-directory directory)
2830 (setq proc (start-process "Shell" buffer shell-file-name
2831 shell-command-switch command))
2832 (setq mode-line-process '(":%s"))
2833 (require 'shell) (shell-mode)
2834 (set-process-sentinel proc 'shell-command-sentinel)
2835 ;; Use the comint filter for proper handling of carriage motion
2836 ;; (see `comint-inhibit-carriage-motion'),.
2837 (set-process-filter proc 'comint-output-filter)
2839 ;; Otherwise, command is executed synchronously.
2840 (shell-command-on-region (point) (point) command
2841 output-buffer nil error-buffer)))))))
2843 (defun display-message-or-buffer (message
2844 &optional buffer-name not-this-window frame)
2845 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2846 MESSAGE may be either a string or a buffer.
2848 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2849 the maximum height of the echo area, as defined by `max-mini-window-height'
2850 if `resize-mini-windows' is non-nil.
2852 Returns either the string shown in the echo area, or when a pop-up
2853 buffer is used, the window used to display it.
2855 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2856 name of the buffer used to display it in the case where a pop-up buffer
2857 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2858 string and it is displayed in the echo area, it is not specified whether
2859 the contents are inserted into the buffer anyway.
2861 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2862 and only used if a buffer is displayed."
2863 (cond ((and (stringp message) (not (string-match "\n" message)))
2864 ;; Trivial case where we can use the echo area
2865 (message "%s" message))
2866 ((and (stringp message)
2867 (= (string-match "\n" message) (1- (length message))))
2868 ;; Trivial case where we can just remove single trailing newline
2869 (message "%s" (substring message 0 (1- (length message)))))
2871 ;; General case
2872 (with-current-buffer
2873 (if (bufferp message)
2874 message
2875 (get-buffer-create (or buffer-name "*Message*")))
2877 (unless (bufferp message)
2878 (erase-buffer)
2879 (insert message))
2881 (let ((lines
2882 (if (= (buffer-size) 0)
2884 (count-screen-lines nil nil nil (minibuffer-window)))))
2885 (cond ((= lines 0))
2886 ((and (or (<= lines 1)
2887 (<= lines
2888 (if resize-mini-windows
2889 (cond ((floatp max-mini-window-height)
2890 (* (frame-height)
2891 max-mini-window-height))
2892 ((integerp max-mini-window-height)
2893 max-mini-window-height)
2896 1)))
2897 ;; Don't use the echo area if the output buffer is
2898 ;; already displayed in the selected frame.
2899 (not (get-buffer-window (current-buffer))))
2900 ;; Echo area
2901 (goto-char (point-max))
2902 (when (bolp)
2903 (backward-char 1))
2904 (message "%s" (buffer-substring (point-min) (point))))
2906 ;; Buffer
2907 (goto-char (point-min))
2908 (display-buffer (current-buffer)
2909 not-this-window frame))))))))
2912 ;; We have a sentinel to prevent insertion of a termination message
2913 ;; in the buffer itself.
2914 (defun shell-command-sentinel (process signal)
2915 (if (memq (process-status process) '(exit signal))
2916 (message "%s: %s."
2917 (car (cdr (cdr (process-command process))))
2918 (substring signal 0 -1))))
2920 (defun shell-command-on-region (start end command
2921 &optional output-buffer replace
2922 error-buffer display-error-buffer)
2923 "Execute string COMMAND in inferior shell with region as input.
2924 Normally display output (if any) in temp buffer `*Shell Command Output*';
2925 Prefix arg means replace the region with it. Return the exit code of
2926 COMMAND.
2928 To specify a coding system for converting non-ASCII characters
2929 in the input and output to the shell command, use \\[universal-coding-system-argument]
2930 before this command. By default, the input (from the current buffer)
2931 is encoded using coding-system specified by `process-coding-system-alist',
2932 falling back to `default-process-coding-system' if no match for COMMAND
2933 is found in `process-coding-system-alist'.
2935 Noninteractive callers can specify coding systems by binding
2936 `coding-system-for-read' and `coding-system-for-write'.
2938 If the command generates output, the output may be displayed
2939 in the echo area or in a buffer.
2940 If the output is short enough to display in the echo area
2941 \(determined by the variable `max-mini-window-height' if
2942 `resize-mini-windows' is non-nil), it is shown there.
2943 Otherwise it is displayed in the buffer `*Shell Command Output*'.
2944 The output is available in that buffer in both cases.
2946 If there is output and an error, a message about the error
2947 appears at the end of the output. If there is no output, or if
2948 output is inserted in the current buffer, the buffer `*Shell
2949 Command Output*' is deleted.
2951 Optional fourth arg OUTPUT-BUFFER specifies where to put the
2952 command's output. If the value is a buffer or buffer name,
2953 put the output there. If the value is nil, use the buffer
2954 `*Shell Command Output*'. Any other value, excluding nil,
2955 means to insert the output in the current buffer. In either case,
2956 the output is inserted after point (leaving mark after it).
2958 Optional fifth arg REPLACE, if non-nil, means to insert the
2959 output in place of text from START to END, putting point and mark
2960 around it.
2962 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
2963 or buffer name to which to direct the command's standard error
2964 output. If nil, error output is mingled with regular output.
2965 When called interactively, `shell-command-default-error-buffer'
2966 is used for ERROR-BUFFER.
2968 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
2969 display the error buffer if there were any errors. When called
2970 interactively, this is t."
2971 (interactive (let (string)
2972 (unless (mark)
2973 (error "The mark is not set now, so there is no region"))
2974 ;; Do this before calling region-beginning
2975 ;; and region-end, in case subprocess output
2976 ;; relocates them while we are in the minibuffer.
2977 (setq string (read-shell-command "Shell command on region: "))
2978 ;; call-interactively recognizes region-beginning and
2979 ;; region-end specially, leaving them in the history.
2980 (list (region-beginning) (region-end)
2981 string
2982 current-prefix-arg
2983 current-prefix-arg
2984 shell-command-default-error-buffer
2985 t)))
2986 (let ((error-file
2987 (if error-buffer
2988 (make-temp-file
2989 (expand-file-name "scor"
2990 (or small-temporary-file-directory
2991 temporary-file-directory)))
2992 nil))
2993 exit-status)
2994 (if (or replace
2995 (and output-buffer
2996 (not (or (bufferp output-buffer) (stringp output-buffer)))))
2997 ;; Replace specified region with output from command.
2998 (let ((swap (and replace (< start end))))
2999 ;; Don't muck with mark unless REPLACE says we should.
3000 (goto-char start)
3001 (and replace (push-mark (point) 'nomsg))
3002 (setq exit-status
3003 (call-process-region start end shell-file-name replace
3004 (if error-file
3005 (list t error-file)
3007 nil shell-command-switch command))
3008 ;; It is rude to delete a buffer which the command is not using.
3009 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3010 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3011 ;; (kill-buffer shell-buffer)))
3012 ;; Don't muck with mark unless REPLACE says we should.
3013 (and replace swap (exchange-point-and-mark)))
3014 ;; No prefix argument: put the output in a temp buffer,
3015 ;; replacing its entire contents.
3016 (let ((buffer (get-buffer-create
3017 (or output-buffer "*Shell Command Output*"))))
3018 (unwind-protect
3019 (if (eq buffer (current-buffer))
3020 ;; If the input is the same buffer as the output,
3021 ;; delete everything but the specified region,
3022 ;; then replace that region with the output.
3023 (progn (setq buffer-read-only nil)
3024 (delete-region (max start end) (point-max))
3025 (delete-region (point-min) (min start end))
3026 (setq exit-status
3027 (call-process-region (point-min) (point-max)
3028 shell-file-name t
3029 (if error-file
3030 (list t error-file)
3032 nil shell-command-switch
3033 command)))
3034 ;; Clear the output buffer, then run the command with
3035 ;; output there.
3036 (let ((directory default-directory))
3037 (with-current-buffer buffer
3038 (setq buffer-read-only nil)
3039 (if (not output-buffer)
3040 (setq default-directory directory))
3041 (erase-buffer)))
3042 (setq exit-status
3043 (call-process-region start end shell-file-name nil
3044 (if error-file
3045 (list buffer error-file)
3046 buffer)
3047 nil shell-command-switch command)))
3048 ;; Report the output.
3049 (with-current-buffer buffer
3050 (setq mode-line-process
3051 (cond ((null exit-status)
3052 " - Error")
3053 ((stringp exit-status)
3054 (format " - Signal [%s]" exit-status))
3055 ((not (equal 0 exit-status))
3056 (format " - Exit [%d]" exit-status)))))
3057 (if (with-current-buffer buffer (> (point-max) (point-min)))
3058 ;; There's some output, display it
3059 (display-message-or-buffer buffer)
3060 ;; No output; error?
3061 (let ((output
3062 (if (and error-file
3063 (< 0 (nth 7 (file-attributes error-file))))
3064 (format "some error output%s"
3065 (if shell-command-default-error-buffer
3066 (format " to the \"%s\" buffer"
3067 shell-command-default-error-buffer)
3068 ""))
3069 "no output")))
3070 (cond ((null exit-status)
3071 (message "(Shell command failed with error)"))
3072 ((equal 0 exit-status)
3073 (message "(Shell command succeeded with %s)"
3074 output))
3075 ((stringp exit-status)
3076 (message "(Shell command killed by signal %s)"
3077 exit-status))
3079 (message "(Shell command failed with code %d and %s)"
3080 exit-status output))))
3081 ;; Don't kill: there might be useful info in the undo-log.
3082 ;; (kill-buffer buffer)
3083 ))))
3085 (when (and error-file (file-exists-p error-file))
3086 (if (< 0 (nth 7 (file-attributes error-file)))
3087 (with-current-buffer (get-buffer-create error-buffer)
3088 (let ((pos-from-end (- (point-max) (point))))
3089 (or (bobp)
3090 (insert "\f\n"))
3091 ;; Do no formatting while reading error file,
3092 ;; because that can run a shell command, and we
3093 ;; don't want that to cause an infinite recursion.
3094 (format-insert-file error-file nil)
3095 ;; Put point after the inserted errors.
3096 (goto-char (- (point-max) pos-from-end)))
3097 (and display-error-buffer
3098 (display-buffer (current-buffer)))))
3099 (delete-file error-file))
3100 exit-status))
3102 (defun shell-command-to-string (command)
3103 "Execute shell command COMMAND and return its output as a string."
3104 (with-output-to-string
3105 (with-current-buffer
3106 standard-output
3107 (process-file shell-file-name nil t nil shell-command-switch command))))
3109 (defun process-file (program &optional infile buffer display &rest args)
3110 "Process files synchronously in a separate process.
3111 Similar to `call-process', but may invoke a file handler based on
3112 `default-directory'. The current working directory of the
3113 subprocess is `default-directory'.
3115 File names in INFILE and BUFFER are handled normally, but file
3116 names in ARGS should be relative to `default-directory', as they
3117 are passed to the process verbatim. \(This is a difference to
3118 `call-process' which does not support file handlers for INFILE
3119 and BUFFER.\)
3121 Some file handlers might not support all variants, for example
3122 they might behave as if DISPLAY was nil, regardless of the actual
3123 value passed."
3124 (let ((fh (find-file-name-handler default-directory 'process-file))
3125 lc stderr-file)
3126 (unwind-protect
3127 (if fh (apply fh 'process-file program infile buffer display args)
3128 (when infile (setq lc (file-local-copy infile)))
3129 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3130 (make-temp-file "emacs")))
3131 (prog1
3132 (apply 'call-process program
3133 (or lc infile)
3134 (if stderr-file (list (car buffer) stderr-file) buffer)
3135 display args)
3136 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3137 (when stderr-file (delete-file stderr-file))
3138 (when lc (delete-file lc)))))
3140 (defvar process-file-side-effects t
3141 "Whether a call of `process-file' changes remote files.
3143 By default, this variable is always set to `t', meaning that a
3144 call of `process-file' could potentially change any file on a
3145 remote host. When set to `nil', a file handler could optimize
3146 its behavior with respect to remote file attribute caching.
3148 You should only ever change this variable with a let-binding;
3149 never with `setq'.")
3151 (defun start-file-process (name buffer program &rest program-args)
3152 "Start a program in a subprocess. Return the process object for it.
3154 Similar to `start-process', but may invoke a file handler based on
3155 `default-directory'. See Info node `(elisp)Magic File Names'.
3157 This handler ought to run PROGRAM, perhaps on the local host,
3158 perhaps on a remote host that corresponds to `default-directory'.
3159 In the latter case, the local part of `default-directory' becomes
3160 the working directory of the process.
3162 PROGRAM and PROGRAM-ARGS might be file names. They are not
3163 objects of file handler invocation. File handlers might not
3164 support pty association, if PROGRAM is nil."
3165 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3166 (if fh (apply fh 'start-file-process name buffer program program-args)
3167 (apply 'start-process name buffer program program-args))))
3169 ;;;; Process menu
3171 (defvar tabulated-list-format)
3172 (defvar tabulated-list-entries)
3173 (defvar tabulated-list-sort-key)
3174 (declare-function tabulated-list-init-header "tabulated-list" ())
3175 (declare-function tabulated-list-print "tabulated-list"
3176 (&optional remember-pos))
3178 (defvar process-menu-query-only nil)
3180 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3181 "Major mode for listing the processes called by Emacs."
3182 (setq tabulated-list-format [("Process" 15 t)
3183 ("Status" 7 t)
3184 ("Buffer" 15 t)
3185 ("TTY" 12 t)
3186 ("Command" 0 t)])
3187 (make-local-variable 'process-menu-query-only)
3188 (setq tabulated-list-sort-key (cons "Process" nil))
3189 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3190 (tabulated-list-init-header))
3192 (defun list-processes--refresh ()
3193 "Recompute the list of processes for the Process List buffer.
3194 Also, delete any process that is exited or signaled."
3195 (setq tabulated-list-entries nil)
3196 (dolist (p (process-list))
3197 (cond ((memq (process-status p) '(exit signal closed))
3198 (delete-process p))
3199 ((or (not process-menu-query-only)
3200 (process-query-on-exit-flag p))
3201 (let* ((buf (process-buffer p))
3202 (type (process-type p))
3203 (name (process-name p))
3204 (status (symbol-name (process-status p)))
3205 (buf-label (if (buffer-live-p buf)
3206 `(,(buffer-name buf)
3207 face link
3208 help-echo ,(concat "Visit buffer `"
3209 (buffer-name buf) "'")
3210 follow-link t
3211 process-buffer ,buf
3212 action process-menu-visit-buffer)
3213 "--"))
3214 (tty (or (process-tty-name p) "--"))
3215 (cmd
3216 (if (memq type '(network serial))
3217 (let ((contact (process-contact p t)))
3218 (if (eq type 'network)
3219 (format "(%s %s)"
3220 (if (plist-get contact :type)
3221 "datagram"
3222 "network")
3223 (if (plist-get contact :server)
3224 (format "server on %s"
3226 (plist-get contact :host)
3227 (plist-get contact :local)))
3228 (format "connection to %s"
3229 (plist-get contact :host))))
3230 (format "(serial port %s%s)"
3231 (or (plist-get contact :port) "?")
3232 (let ((speed (plist-get contact :speed)))
3233 (if speed
3234 (format " at %s b/s" speed)
3235 "")))))
3236 (mapconcat 'identity (process-command p) " "))))
3237 (push (list p (vector name status buf-label tty cmd))
3238 tabulated-list-entries))))))
3240 (defun process-menu-visit-buffer (button)
3241 (display-buffer (button-get button 'process-buffer)))
3243 (defun list-processes (&optional query-only buffer)
3244 "Display a list of all processes that are Emacs sub-processes.
3245 If optional argument QUERY-ONLY is non-nil, only processes with
3246 the query-on-exit flag set are listed.
3247 Any process listed as exited or signaled is actually eliminated
3248 after the listing is made.
3249 Optional argument BUFFER specifies a buffer to use, instead of
3250 \"*Process List*\".
3251 The return value is always nil.
3253 This function lists only processes that were launched by Emacs. To
3254 see other processes running on the system, use `list-system-processes'."
3255 (interactive)
3256 (or (fboundp 'process-list)
3257 (error "Asynchronous subprocesses are not supported on this system"))
3258 (unless (bufferp buffer)
3259 (setq buffer (get-buffer-create "*Process List*")))
3260 (with-current-buffer buffer
3261 (process-menu-mode)
3262 (setq process-menu-query-only query-only)
3263 (list-processes--refresh)
3264 (tabulated-list-print))
3265 (display-buffer buffer)
3266 nil)
3268 (defvar universal-argument-map
3269 (let ((map (make-sparse-keymap))
3270 (universal-argument-minus
3271 ;; For backward compatibility, minus with no modifiers is an ordinary
3272 ;; command if digits have already been entered.
3273 `(menu-item "" negative-argument
3274 :filter ,(lambda (cmd)
3275 (if (integerp prefix-arg) nil cmd)))))
3276 (define-key map [switch-frame]
3277 (lambda (e) (interactive "e")
3278 (handle-switch-frame e) (universal-argument--mode)))
3279 (define-key map [?\C-u] 'universal-argument-more)
3280 (define-key map [?-] universal-argument-minus)
3281 (define-key map [?0] 'digit-argument)
3282 (define-key map [?1] 'digit-argument)
3283 (define-key map [?2] 'digit-argument)
3284 (define-key map [?3] 'digit-argument)
3285 (define-key map [?4] 'digit-argument)
3286 (define-key map [?5] 'digit-argument)
3287 (define-key map [?6] 'digit-argument)
3288 (define-key map [?7] 'digit-argument)
3289 (define-key map [?8] 'digit-argument)
3290 (define-key map [?9] 'digit-argument)
3291 (define-key map [kp-0] 'digit-argument)
3292 (define-key map [kp-1] 'digit-argument)
3293 (define-key map [kp-2] 'digit-argument)
3294 (define-key map [kp-3] 'digit-argument)
3295 (define-key map [kp-4] 'digit-argument)
3296 (define-key map [kp-5] 'digit-argument)
3297 (define-key map [kp-6] 'digit-argument)
3298 (define-key map [kp-7] 'digit-argument)
3299 (define-key map [kp-8] 'digit-argument)
3300 (define-key map [kp-9] 'digit-argument)
3301 (define-key map [kp-subtract] universal-argument-minus)
3302 map)
3303 "Keymap used while processing \\[universal-argument].")
3305 (defun universal-argument--mode ()
3306 (set-temporary-overlay-map universal-argument-map))
3308 (defun universal-argument ()
3309 "Begin a numeric argument for the following command.
3310 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3311 \\[universal-argument] following the digits or minus sign ends the argument.
3312 \\[universal-argument] without digits or minus sign provides 4 as argument.
3313 Repeating \\[universal-argument] without digits or minus sign
3314 multiplies the argument by 4 each time.
3315 For some commands, just \\[universal-argument] by itself serves as a flag
3316 which is different in effect from any particular numeric argument.
3317 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3318 (interactive)
3319 (setq prefix-arg (list 4))
3320 (universal-argument--mode))
3322 (defun universal-argument-more (arg)
3323 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3324 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3325 (interactive "P")
3326 (setq prefix-arg (if (consp arg)
3327 (list (* 4 (car arg)))
3328 (if (eq arg '-)
3329 (list -4)
3330 arg)))
3331 (when (consp prefix-arg) (universal-argument--mode)))
3333 (defun negative-argument (arg)
3334 "Begin a negative numeric argument for the next command.
3335 \\[universal-argument] following digits or minus sign ends the argument."
3336 (interactive "P")
3337 (setq prefix-arg (cond ((integerp arg) (- arg))
3338 ((eq arg '-) nil)
3339 (t '-)))
3340 (universal-argument--mode))
3342 (defun digit-argument (arg)
3343 "Part of the numeric argument for the next command.
3344 \\[universal-argument] following digits or minus sign ends the argument."
3345 (interactive "P")
3346 (let* ((char (if (integerp last-command-event)
3347 last-command-event
3348 (get last-command-event 'ascii-character)))
3349 (digit (- (logand char ?\177) ?0)))
3350 (setq prefix-arg (cond ((integerp arg)
3351 (+ (* arg 10)
3352 (if (< arg 0) (- digit) digit)))
3353 ((eq arg '-)
3354 ;; Treat -0 as just -, so that -01 will work.
3355 (if (zerop digit) '- (- digit)))
3357 digit))))
3358 (universal-argument--mode))
3361 (defvar filter-buffer-substring-functions nil
3362 "This variable is a wrapper hook around `filter-buffer-substring'.")
3363 (make-obsolete-variable 'filter-buffer-substring-functions
3364 'filter-buffer-substring-function "24.4")
3366 (defvar filter-buffer-substring-function #'buffer-substring--filter
3367 "Function to perform the filtering in `filter-buffer-substring'.
3368 The function is called with 3 arguments:
3369 \(BEG END DELETE). The arguments BEG, END, and DELETE are the same
3370 as those of `filter-buffer-substring' in each case.
3371 It should return the buffer substring between BEG and END, after filtering.")
3373 (defvar buffer-substring-filters nil
3374 "List of filter functions for `filter-buffer-substring'.
3375 Each function must accept a single argument, a string, and return
3376 a string. The buffer substring is passed to the first function
3377 in the list, and the return value of each function is passed to
3378 the next.
3379 As a special convention, point is set to the start of the buffer text
3380 being operated on (i.e., the first argument of `filter-buffer-substring')
3381 before these functions are called.")
3382 (make-obsolete-variable 'buffer-substring-filters
3383 'filter-buffer-substring-function "24.1")
3385 (defun filter-buffer-substring (beg end &optional delete)
3386 "Return the buffer substring between BEG and END, after filtering.
3387 The hook `filter-buffer-substring-function' performs the actual filtering.
3388 By default, no filtering is done.
3390 If DELETE is non-nil, the text between BEG and END is deleted
3391 from the buffer.
3393 This function should be used instead of `buffer-substring',
3394 `buffer-substring-no-properties', or `delete-and-extract-region'
3395 when you want to allow filtering to take place. For example,
3396 major or minor modes can use `filter-buffer-substring-function' to
3397 extract characters that are special to a buffer, and should not
3398 be copied into other buffers."
3399 (funcall filter-buffer-substring-function beg end delete))
3401 ;; FIXME: `with-wrapper-hook' is obsolete
3402 (defun buffer-substring--filter (beg end &optional delete)
3403 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
3404 (cond
3405 ((or delete buffer-substring-filters)
3406 (save-excursion
3407 (goto-char beg)
3408 (let ((string (if delete (delete-and-extract-region beg end)
3409 (buffer-substring beg end))))
3410 (dolist (filter buffer-substring-filters)
3411 (setq string (funcall filter string)))
3412 string)))
3414 (buffer-substring beg end)))))
3417 ;;;; Window system cut and paste hooks.
3419 (defvar interprogram-cut-function nil
3420 "Function to call to make a killed region available to other programs.
3421 Most window systems provide a facility for cutting and pasting
3422 text between different programs, such as the clipboard on X and
3423 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3425 This variable holds a function that Emacs calls whenever text is
3426 put in the kill ring, to make the new kill available to other
3427 programs. The function takes one argument, TEXT, which is a
3428 string containing the text which should be made available.")
3430 (defvar interprogram-paste-function nil
3431 "Function to call to get text cut from other programs.
3432 Most window systems provide a facility for cutting and pasting
3433 text between different programs, such as the clipboard on X and
3434 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3436 This variable holds a function that Emacs calls to obtain text
3437 that other programs have provided for pasting. The function is
3438 called with no arguments. If no other program has provided text
3439 to paste, the function should return nil (in which case the
3440 caller, usually `current-kill', should use the top of the Emacs
3441 kill ring). If another program has provided text to paste, the
3442 function should return that text as a string (in which case the
3443 caller should put this string in the kill ring as the latest
3444 kill).
3446 The function may also return a list of strings if the window
3447 system supports multiple selections. The first string will be
3448 used as the pasted text, but the other will be placed in the kill
3449 ring for easy access via `yank-pop'.
3451 Note that the function should return a string only if a program
3452 other than Emacs has provided a string for pasting; if Emacs
3453 provided the most recent string, the function should return nil.
3454 If it is difficult to tell whether Emacs or some other program
3455 provided the current string, it is probably good enough to return
3456 nil if the string is equal (according to `string=') to the last
3457 text Emacs provided.")
3461 ;;;; The kill ring data structure.
3463 (defvar kill-ring nil
3464 "List of killed text sequences.
3465 Since the kill ring is supposed to interact nicely with cut-and-paste
3466 facilities offered by window systems, use of this variable should
3467 interact nicely with `interprogram-cut-function' and
3468 `interprogram-paste-function'. The functions `kill-new',
3469 `kill-append', and `current-kill' are supposed to implement this
3470 interaction; you may want to use them instead of manipulating the kill
3471 ring directly.")
3473 (defcustom kill-ring-max 60
3474 "Maximum length of kill ring before oldest elements are thrown away."
3475 :type 'integer
3476 :group 'killing)
3478 (defvar kill-ring-yank-pointer nil
3479 "The tail of the kill ring whose car is the last thing yanked.")
3481 (defcustom save-interprogram-paste-before-kill nil
3482 "Save clipboard strings into kill ring before replacing them.
3483 When one selects something in another program to paste it into Emacs,
3484 but kills something in Emacs before actually pasting it,
3485 this selection is gone unless this variable is non-nil,
3486 in which case the other program's selection is saved in the `kill-ring'
3487 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3488 :type 'boolean
3489 :group 'killing
3490 :version "23.2")
3492 (defcustom kill-do-not-save-duplicates nil
3493 "Do not add a new string to `kill-ring' if it duplicates the last one.
3494 The comparison is done using `equal-including-properties'."
3495 :type 'boolean
3496 :group 'killing
3497 :version "23.2")
3499 (defun kill-new (string &optional replace)
3500 "Make STRING the latest kill in the kill ring.
3501 Set `kill-ring-yank-pointer' to point to it.
3502 If `interprogram-cut-function' is non-nil, apply it to STRING.
3503 Optional second argument REPLACE non-nil means that STRING will replace
3504 the front of the kill ring, rather than being added to the list.
3506 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3507 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3508 STRING.
3510 When the yank handler has a non-nil PARAM element, the original STRING
3511 argument is not used by `insert-for-yank'. However, since Lisp code
3512 may access and use elements from the kill ring directly, the STRING
3513 argument should still be a \"useful\" string for such uses."
3514 (unless (and kill-do-not-save-duplicates
3515 ;; Due to text properties such as 'yank-handler that
3516 ;; can alter the contents to yank, comparison using
3517 ;; `equal' is unsafe.
3518 (equal-including-properties string (car kill-ring)))
3519 (if (fboundp 'menu-bar-update-yank-menu)
3520 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
3521 (when save-interprogram-paste-before-kill
3522 (let ((interprogram-paste (and interprogram-paste-function
3523 (funcall interprogram-paste-function))))
3524 (when interprogram-paste
3525 (dolist (s (if (listp interprogram-paste)
3526 (nreverse interprogram-paste)
3527 (list interprogram-paste)))
3528 (unless (and kill-do-not-save-duplicates
3529 (equal-including-properties s (car kill-ring)))
3530 (push s kill-ring))))))
3531 (unless (and kill-do-not-save-duplicates
3532 (equal-including-properties string (car kill-ring)))
3533 (if (and replace kill-ring)
3534 (setcar kill-ring string)
3535 (push string kill-ring)
3536 (if (> (length kill-ring) kill-ring-max)
3537 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
3538 (setq kill-ring-yank-pointer kill-ring)
3539 (if interprogram-cut-function
3540 (funcall interprogram-cut-function string)))
3542 (defun kill-append (string before-p)
3543 "Append STRING to the end of the latest kill in the kill ring.
3544 If BEFORE-P is non-nil, prepend STRING to the kill.
3545 If `interprogram-cut-function' is set, pass the resulting kill to it."
3546 (let* ((cur (car kill-ring)))
3547 (kill-new (if before-p (concat string cur) (concat cur string))
3548 (or (= (length cur) 0)
3549 (equal nil (get-text-property 0 'yank-handler cur))))))
3551 (defcustom yank-pop-change-selection nil
3552 "Whether rotating the kill ring changes the window system selection.
3553 If non-nil, whenever the kill ring is rotated (usually via the
3554 `yank-pop' command), Emacs also calls `interprogram-cut-function'
3555 to copy the new kill to the window system selection."
3556 :type 'boolean
3557 :group 'killing
3558 :version "23.1")
3560 (defun current-kill (n &optional do-not-move)
3561 "Rotate the yanking point by N places, and then return that kill.
3562 If N is zero and `interprogram-paste-function' is set to a
3563 function that returns a string or a list of strings, and if that
3564 function doesn't return nil, then that string (or list) is added
3565 to the front of the kill ring and the string (or first string in
3566 the list) is returned as the latest kill.
3568 If N is not zero, and if `yank-pop-change-selection' is
3569 non-nil, use `interprogram-cut-function' to transfer the
3570 kill at the new yank point into the window system selection.
3572 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3573 move the yanking point; just return the Nth kill forward."
3575 (let ((interprogram-paste (and (= n 0)
3576 interprogram-paste-function
3577 (funcall interprogram-paste-function))))
3578 (if interprogram-paste
3579 (progn
3580 ;; Disable the interprogram cut function when we add the new
3581 ;; text to the kill ring, so Emacs doesn't try to own the
3582 ;; selection, with identical text.
3583 (let ((interprogram-cut-function nil))
3584 (if (listp interprogram-paste)
3585 (mapc 'kill-new (nreverse interprogram-paste))
3586 (kill-new interprogram-paste)))
3587 (car kill-ring))
3588 (or kill-ring (error "Kill ring is empty"))
3589 (let ((ARGth-kill-element
3590 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3591 (length kill-ring))
3592 kill-ring)))
3593 (unless do-not-move
3594 (setq kill-ring-yank-pointer ARGth-kill-element)
3595 (when (and yank-pop-change-selection
3596 (> n 0)
3597 interprogram-cut-function)
3598 (funcall interprogram-cut-function (car ARGth-kill-element))))
3599 (car ARGth-kill-element)))))
3603 ;;;; Commands for manipulating the kill ring.
3605 (defcustom kill-read-only-ok nil
3606 "Non-nil means don't signal an error for killing read-only text."
3607 :type 'boolean
3608 :group 'killing)
3610 (defun kill-region (beg end &optional region)
3611 "Kill (\"cut\") text between point and mark.
3612 This deletes the text from the buffer and saves it in the kill ring.
3613 The command \\[yank] can retrieve it from there.
3614 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3616 If you want to append the killed region to the last killed text,
3617 use \\[append-next-kill] before \\[kill-region].
3619 If the buffer is read-only, Emacs will beep and refrain from deleting
3620 the text, but put the text in the kill ring anyway. This means that
3621 you can use the killing commands to copy text from a read-only buffer.
3623 Lisp programs should use this function for killing text.
3624 (To delete text, use `delete-region'.)
3625 Supply two arguments, character positions indicating the stretch of text
3626 to be killed.
3627 Any command that calls this function is a \"kill command\".
3628 If the previous command was also a kill command,
3629 the text killed this time appends to the text killed last time
3630 to make one entry in the kill ring.
3632 The optional argument REGION if non-nil, indicates that we're not just killing
3633 some text between BEG and END, but we're killing the region."
3634 ;; Pass point first, then mark, because the order matters
3635 ;; when calling kill-append.
3636 (interactive (list (point) (mark) 'region))
3637 (unless (and beg end)
3638 (error "The mark is not set now, so there is no region"))
3639 (condition-case nil
3640 (let ((string (if region
3641 (funcall region-extract-function 'delete)
3642 (filter-buffer-substring beg end 'delete))))
3643 (when string ;STRING is nil if BEG = END
3644 ;; Add that string to the kill ring, one way or another.
3645 (if (eq last-command 'kill-region)
3646 (kill-append string (< end beg))
3647 (kill-new string nil)))
3648 (when (or string (eq last-command 'kill-region))
3649 (setq this-command 'kill-region))
3650 (setq deactivate-mark t)
3651 nil)
3652 ((buffer-read-only text-read-only)
3653 ;; The code above failed because the buffer, or some of the characters
3654 ;; in the region, are read-only.
3655 ;; We should beep, in case the user just isn't aware of this.
3656 ;; However, there's no harm in putting
3657 ;; the region's text in the kill ring, anyway.
3658 (copy-region-as-kill beg end region)
3659 ;; Set this-command now, so it will be set even if we get an error.
3660 (setq this-command 'kill-region)
3661 ;; This should barf, if appropriate, and give us the correct error.
3662 (if kill-read-only-ok
3663 (progn (message "Read only text copied to kill ring") nil)
3664 ;; Signal an error if the buffer is read-only.
3665 (barf-if-buffer-read-only)
3666 ;; If the buffer isn't read-only, the text is.
3667 (signal 'text-read-only (list (current-buffer)))))))
3669 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3670 ;; to get two copies of the text when the user accidentally types M-w and
3671 ;; then corrects it with the intended C-w.
3672 (defun copy-region-as-kill (beg end &optional region)
3673 "Save the region as if killed, but don't kill it.
3674 In Transient Mark mode, deactivate the mark.
3675 If `interprogram-cut-function' is non-nil, also save the text for a window
3676 system cut and paste.
3678 The optional argument REGION if non-nil, indicates that we're not just copying
3679 some text between BEG and END, but we're copying the region.
3681 This command's old key binding has been given to `kill-ring-save'."
3682 (interactive "r\np")
3683 (let ((str (if region
3684 (funcall region-extract-function nil)
3685 (filter-buffer-substring beg end))))
3686 (if (eq last-command 'kill-region)
3687 (kill-append str (< end beg))
3688 (kill-new str)))
3689 (setq deactivate-mark t)
3690 nil)
3692 (defun kill-ring-save (beg end &optional region)
3693 "Save the region as if killed, but don't kill it.
3694 In Transient Mark mode, deactivate the mark.
3695 If `interprogram-cut-function' is non-nil, also save the text for a window
3696 system cut and paste.
3698 If you want to append the killed line to the last killed text,
3699 use \\[append-next-kill] before \\[kill-ring-save].
3701 The optional argument REGION if non-nil, indicates that we're not just copying
3702 some text between BEG and END, but we're copying the region.
3704 This command is similar to `copy-region-as-kill', except that it gives
3705 visual feedback indicating the extent of the region being copied."
3706 (interactive "r\np")
3707 (copy-region-as-kill beg end region)
3708 ;; This use of called-interactively-p is correct because the code it
3709 ;; controls just gives the user visual feedback.
3710 (if (called-interactively-p 'interactive)
3711 (indicate-copied-region)))
3713 (defun indicate-copied-region (&optional message-len)
3714 "Indicate that the region text has been copied interactively.
3715 If the mark is visible in the selected window, blink the cursor
3716 between point and mark if there is currently no active region
3717 highlighting.
3719 If the mark lies outside the selected window, display an
3720 informative message containing a sample of the copied text. The
3721 optional argument MESSAGE-LEN, if non-nil, specifies the length
3722 of this sample text; it defaults to 40."
3723 (let ((mark (mark t))
3724 (point (point))
3725 ;; Inhibit quitting so we can make a quit here
3726 ;; look like a C-g typed as a command.
3727 (inhibit-quit t))
3728 (if (pos-visible-in-window-p mark (selected-window))
3729 ;; Swap point-and-mark quickly so as to show the region that
3730 ;; was selected. Don't do it if the region is highlighted.
3731 (unless (and (region-active-p)
3732 (face-background 'region))
3733 ;; Swap point and mark.
3734 (set-marker (mark-marker) (point) (current-buffer))
3735 (goto-char mark)
3736 (sit-for blink-matching-delay)
3737 ;; Swap back.
3738 (set-marker (mark-marker) mark (current-buffer))
3739 (goto-char point)
3740 ;; If user quit, deactivate the mark
3741 ;; as C-g would as a command.
3742 (and quit-flag mark-active
3743 (deactivate-mark)))
3744 (let ((len (min (abs (- mark point))
3745 (or message-len 40))))
3746 (if (< point mark)
3747 ;; Don't say "killed"; that is misleading.
3748 (message "Saved text until \"%s\""
3749 (buffer-substring-no-properties (- mark len) mark))
3750 (message "Saved text from \"%s\""
3751 (buffer-substring-no-properties mark (+ mark len))))))))
3753 (defun append-next-kill (&optional interactive)
3754 "Cause following command, if it kills, to append to previous kill.
3755 The argument is used for internal purposes; do not supply one."
3756 (interactive "p")
3757 ;; We don't use (interactive-p), since that breaks kbd macros.
3758 (if interactive
3759 (progn
3760 (setq this-command 'kill-region)
3761 (message "If the next command is a kill, it will append"))
3762 (setq last-command 'kill-region)))
3764 ;; Yanking.
3766 (defcustom yank-handled-properties
3767 '((font-lock-face . yank-handle-font-lock-face-property)
3768 (category . yank-handle-category-property))
3769 "List of special text property handling conditions for yanking.
3770 Each element should have the form (PROP . FUN), where PROP is a
3771 property symbol and FUN is a function. When the `yank' command
3772 inserts text into the buffer, it scans the inserted text for
3773 stretches of text that have `eq' values of the text property
3774 PROP; for each such stretch of text, FUN is called with three
3775 arguments: the property's value in that text, and the start and
3776 end positions of the text.
3778 This is done prior to removing the properties specified by
3779 `yank-excluded-properties'."
3780 :group 'killing
3781 :version "24.3")
3783 ;; This is actually used in subr.el but defcustom does not work there.
3784 (defcustom yank-excluded-properties
3785 '(category field follow-link fontified font-lock-face help-echo
3786 intangible invisible keymap local-map mouse-face read-only
3787 yank-handler)
3788 "Text properties to discard when yanking.
3789 The value should be a list of text properties to discard or t,
3790 which means to discard all text properties.
3792 See also `yank-handled-properties'."
3793 :type '(choice (const :tag "All" t) (repeat symbol))
3794 :group 'killing
3795 :version "24.3")
3797 (defvar yank-window-start nil)
3798 (defvar yank-undo-function nil
3799 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3800 Function is called with two parameters, START and END corresponding to
3801 the value of the mark and point; it is guaranteed that START <= END.
3802 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3804 (defun yank-pop (&optional arg)
3805 "Replace just-yanked stretch of killed text with a different stretch.
3806 This command is allowed only immediately after a `yank' or a `yank-pop'.
3807 At such a time, the region contains a stretch of reinserted
3808 previously-killed text. `yank-pop' deletes that text and inserts in its
3809 place a different stretch of killed text.
3811 With no argument, the previous kill is inserted.
3812 With argument N, insert the Nth previous kill.
3813 If N is negative, this is a more recent kill.
3815 The sequence of kills wraps around, so that after the oldest one
3816 comes the newest one.
3818 When this command inserts killed text into the buffer, it honors
3819 `yank-excluded-properties' and `yank-handler' as described in the
3820 doc string for `insert-for-yank-1', which see."
3821 (interactive "*p")
3822 (if (not (eq last-command 'yank))
3823 (error "Previous command was not a yank"))
3824 (setq this-command 'yank)
3825 (unless arg (setq arg 1))
3826 (let ((inhibit-read-only t)
3827 (before (< (point) (mark t))))
3828 (if before
3829 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3830 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
3831 (setq yank-undo-function nil)
3832 (set-marker (mark-marker) (point) (current-buffer))
3833 (insert-for-yank (current-kill arg))
3834 ;; Set the window start back where it was in the yank command,
3835 ;; if possible.
3836 (set-window-start (selected-window) yank-window-start t)
3837 (if before
3838 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3839 ;; It is cleaner to avoid activation, even though the command
3840 ;; loop would deactivate the mark because we inserted text.
3841 (goto-char (prog1 (mark t)
3842 (set-marker (mark-marker) (point) (current-buffer))))))
3843 nil)
3845 (defun yank (&optional arg)
3846 "Reinsert (\"paste\") the last stretch of killed text.
3847 More precisely, reinsert the most recent kill, which is the
3848 stretch of killed text most recently killed OR yanked. Put point
3849 at the end, and set mark at the beginning without activating it.
3850 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
3851 With argument N, reinsert the Nth most recent kill.
3853 When this command inserts text into the buffer, it honors the
3854 `yank-handled-properties' and `yank-excluded-properties'
3855 variables, and the `yank-handler' text property. See
3856 `insert-for-yank-1' for details.
3858 See also the command `yank-pop' (\\[yank-pop])."
3859 (interactive "*P")
3860 (setq yank-window-start (window-start))
3861 ;; If we don't get all the way thru, make last-command indicate that
3862 ;; for the following command.
3863 (setq this-command t)
3864 (push-mark (point))
3865 (insert-for-yank (current-kill (cond
3866 ((listp arg) 0)
3867 ((eq arg '-) -2)
3868 (t (1- arg)))))
3869 (if (consp arg)
3870 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3871 ;; It is cleaner to avoid activation, even though the command
3872 ;; loop would deactivate the mark because we inserted text.
3873 (goto-char (prog1 (mark t)
3874 (set-marker (mark-marker) (point) (current-buffer)))))
3875 ;; If we do get all the way thru, make this-command indicate that.
3876 (if (eq this-command t)
3877 (setq this-command 'yank))
3878 nil)
3880 (defun rotate-yank-pointer (arg)
3881 "Rotate the yanking point in the kill ring.
3882 With ARG, rotate that many kills forward (or backward, if negative)."
3883 (interactive "p")
3884 (current-kill arg))
3886 ;; Some kill commands.
3888 ;; Internal subroutine of delete-char
3889 (defun kill-forward-chars (arg)
3890 (if (listp arg) (setq arg (car arg)))
3891 (if (eq arg '-) (setq arg -1))
3892 (kill-region (point) (+ (point) arg)))
3894 ;; Internal subroutine of backward-delete-char
3895 (defun kill-backward-chars (arg)
3896 (if (listp arg) (setq arg (car arg)))
3897 (if (eq arg '-) (setq arg -1))
3898 (kill-region (point) (- (point) arg)))
3900 (defcustom backward-delete-char-untabify-method 'untabify
3901 "The method for untabifying when deleting backward.
3902 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3903 `hungry' -- delete all whitespace, both tabs and spaces;
3904 `all' -- delete all whitespace, including tabs, spaces and newlines;
3905 nil -- just delete one character."
3906 :type '(choice (const untabify) (const hungry) (const all) (const nil))
3907 :version "20.3"
3908 :group 'killing)
3910 (defun backward-delete-char-untabify (arg &optional killp)
3911 "Delete characters backward, changing tabs into spaces.
3912 The exact behavior depends on `backward-delete-char-untabify-method'.
3913 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3914 Interactively, ARG is the prefix arg (default 1)
3915 and KILLP is t if a prefix arg was specified."
3916 (interactive "*p\nP")
3917 (when (eq backward-delete-char-untabify-method 'untabify)
3918 (let ((count arg))
3919 (save-excursion
3920 (while (and (> count 0) (not (bobp)))
3921 (if (= (preceding-char) ?\t)
3922 (let ((col (current-column)))
3923 (forward-char -1)
3924 (setq col (- col (current-column)))
3925 (insert-char ?\s col)
3926 (delete-char 1)))
3927 (forward-char -1)
3928 (setq count (1- count))))))
3929 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3930 ((eq backward-delete-char-untabify-method 'all)
3931 " \t\n\r")))
3932 (n (if skip
3933 (let* ((oldpt (point))
3934 (wh (- oldpt (save-excursion
3935 (skip-chars-backward skip)
3936 (constrain-to-field nil oldpt)))))
3937 (+ arg (if (zerop wh) 0 (1- wh))))
3938 arg)))
3939 ;; Avoid warning about delete-backward-char
3940 (with-no-warnings (delete-backward-char n killp))))
3942 (defun zap-to-char (arg char)
3943 "Kill up to and including ARGth occurrence of CHAR.
3944 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3945 Goes backward if ARG is negative; error if CHAR not found."
3946 (interactive (list (prefix-numeric-value current-prefix-arg)
3947 (read-char "Zap to char: " t)))
3948 ;; Avoid "obsolete" warnings for translation-table-for-input.
3949 (with-no-warnings
3950 (if (char-table-p translation-table-for-input)
3951 (setq char (or (aref translation-table-for-input char) char))))
3952 (kill-region (point) (progn
3953 (search-forward (char-to-string char) nil nil arg)
3954 (point))))
3956 ;; kill-line and its subroutines.
3958 (defcustom kill-whole-line nil
3959 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
3960 :type 'boolean
3961 :group 'killing)
3963 (defun kill-line (&optional arg)
3964 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3965 With prefix argument ARG, kill that many lines from point.
3966 Negative arguments kill lines backward.
3967 With zero argument, kills the text before point on the current line.
3969 When calling from a program, nil means \"no arg\",
3970 a number counts as a prefix arg.
3972 To kill a whole line, when point is not at the beginning, type \
3973 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3975 If `show-trailing-whitespace' is non-nil, this command will just
3976 kill the rest of the current line, even if there are only
3977 nonblanks there.
3979 If option `kill-whole-line' is non-nil, then this command kills the whole line
3980 including its terminating newline, when used at the beginning of a line
3981 with no argument. As a consequence, you can always kill a whole line
3982 by typing \\[move-beginning-of-line] \\[kill-line].
3984 If you want to append the killed line to the last killed text,
3985 use \\[append-next-kill] before \\[kill-line].
3987 If the buffer is read-only, Emacs will beep and refrain from deleting
3988 the line, but put the line in the kill ring anyway. This means that
3989 you can use this command to copy text from a read-only buffer.
3990 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3991 even beep.)"
3992 (interactive "P")
3993 (kill-region (point)
3994 ;; It is better to move point to the other end of the kill
3995 ;; before killing. That way, in a read-only buffer, point
3996 ;; moves across the text that is copied to the kill ring.
3997 ;; The choice has no effect on undo now that undo records
3998 ;; the value of point from before the command was run.
3999 (progn
4000 (if arg
4001 (forward-visible-line (prefix-numeric-value arg))
4002 (if (eobp)
4003 (signal 'end-of-buffer nil))
4004 (let ((end
4005 (save-excursion
4006 (end-of-visible-line) (point))))
4007 (if (or (save-excursion
4008 ;; If trailing whitespace is visible,
4009 ;; don't treat it as nothing.
4010 (unless show-trailing-whitespace
4011 (skip-chars-forward " \t" end))
4012 (= (point) end))
4013 (and kill-whole-line (bolp)))
4014 (forward-visible-line 1)
4015 (goto-char end))))
4016 (point))))
4018 (defun kill-whole-line (&optional arg)
4019 "Kill current line.
4020 With prefix ARG, kill that many lines starting from the current line.
4021 If ARG is negative, kill backward. Also kill the preceding newline.
4022 \(This is meant to make \\[repeat] work well with negative arguments.\)
4023 If ARG is zero, kill current line but exclude the trailing newline."
4024 (interactive "p")
4025 (or arg (setq arg 1))
4026 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4027 (signal 'end-of-buffer nil))
4028 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4029 (signal 'beginning-of-buffer nil))
4030 (unless (eq last-command 'kill-region)
4031 (kill-new "")
4032 (setq last-command 'kill-region))
4033 (cond ((zerop arg)
4034 ;; We need to kill in two steps, because the previous command
4035 ;; could have been a kill command, in which case the text
4036 ;; before point needs to be prepended to the current kill
4037 ;; ring entry and the text after point appended. Also, we
4038 ;; need to use save-excursion to avoid copying the same text
4039 ;; twice to the kill ring in read-only buffers.
4040 (save-excursion
4041 (kill-region (point) (progn (forward-visible-line 0) (point))))
4042 (kill-region (point) (progn (end-of-visible-line) (point))))
4043 ((< arg 0)
4044 (save-excursion
4045 (kill-region (point) (progn (end-of-visible-line) (point))))
4046 (kill-region (point)
4047 (progn (forward-visible-line (1+ arg))
4048 (unless (bobp) (backward-char))
4049 (point))))
4051 (save-excursion
4052 (kill-region (point) (progn (forward-visible-line 0) (point))))
4053 (kill-region (point)
4054 (progn (forward-visible-line arg) (point))))))
4056 (defun forward-visible-line (arg)
4057 "Move forward by ARG lines, ignoring currently invisible newlines only.
4058 If ARG is negative, move backward -ARG lines.
4059 If ARG is zero, move to the beginning of the current line."
4060 (condition-case nil
4061 (if (> arg 0)
4062 (progn
4063 (while (> arg 0)
4064 (or (zerop (forward-line 1))
4065 (signal 'end-of-buffer nil))
4066 ;; If the newline we just skipped is invisible,
4067 ;; don't count it.
4068 (let ((prop
4069 (get-char-property (1- (point)) 'invisible)))
4070 (if (if (eq buffer-invisibility-spec t)
4071 prop
4072 (or (memq prop buffer-invisibility-spec)
4073 (assq prop buffer-invisibility-spec)))
4074 (setq arg (1+ arg))))
4075 (setq arg (1- arg)))
4076 ;; If invisible text follows, and it is a number of complete lines,
4077 ;; skip it.
4078 (let ((opoint (point)))
4079 (while (and (not (eobp))
4080 (let ((prop
4081 (get-char-property (point) 'invisible)))
4082 (if (eq buffer-invisibility-spec t)
4083 prop
4084 (or (memq prop buffer-invisibility-spec)
4085 (assq prop buffer-invisibility-spec)))))
4086 (goto-char
4087 (if (get-text-property (point) 'invisible)
4088 (or (next-single-property-change (point) 'invisible)
4089 (point-max))
4090 (next-overlay-change (point)))))
4091 (unless (bolp)
4092 (goto-char opoint))))
4093 (let ((first t))
4094 (while (or first (<= arg 0))
4095 (if first
4096 (beginning-of-line)
4097 (or (zerop (forward-line -1))
4098 (signal 'beginning-of-buffer nil)))
4099 ;; If the newline we just moved to is invisible,
4100 ;; don't count it.
4101 (unless (bobp)
4102 (let ((prop
4103 (get-char-property (1- (point)) 'invisible)))
4104 (unless (if (eq buffer-invisibility-spec t)
4105 prop
4106 (or (memq prop buffer-invisibility-spec)
4107 (assq prop buffer-invisibility-spec)))
4108 (setq arg (1+ arg)))))
4109 (setq first nil))
4110 ;; If invisible text follows, and it is a number of complete lines,
4111 ;; skip it.
4112 (let ((opoint (point)))
4113 (while (and (not (bobp))
4114 (let ((prop
4115 (get-char-property (1- (point)) 'invisible)))
4116 (if (eq buffer-invisibility-spec t)
4117 prop
4118 (or (memq prop buffer-invisibility-spec)
4119 (assq prop buffer-invisibility-spec)))))
4120 (goto-char
4121 (if (get-text-property (1- (point)) 'invisible)
4122 (or (previous-single-property-change (point) 'invisible)
4123 (point-min))
4124 (previous-overlay-change (point)))))
4125 (unless (bolp)
4126 (goto-char opoint)))))
4127 ((beginning-of-buffer end-of-buffer)
4128 nil)))
4130 (defun end-of-visible-line ()
4131 "Move to end of current visible line."
4132 (end-of-line)
4133 ;; If the following character is currently invisible,
4134 ;; skip all characters with that same `invisible' property value,
4135 ;; then find the next newline.
4136 (while (and (not (eobp))
4137 (save-excursion
4138 (skip-chars-forward "^\n")
4139 (let ((prop
4140 (get-char-property (point) 'invisible)))
4141 (if (eq buffer-invisibility-spec t)
4142 prop
4143 (or (memq prop buffer-invisibility-spec)
4144 (assq prop buffer-invisibility-spec))))))
4145 (skip-chars-forward "^\n")
4146 (if (get-text-property (point) 'invisible)
4147 (goto-char (or (next-single-property-change (point) 'invisible)
4148 (point-max)))
4149 (goto-char (next-overlay-change (point))))
4150 (end-of-line)))
4152 (defun insert-buffer (buffer)
4153 "Insert after point the contents of BUFFER.
4154 Puts mark after the inserted text.
4155 BUFFER may be a buffer or a buffer name.
4157 This function is meant for the user to run interactively.
4158 Don't call it from programs: use `insert-buffer-substring' instead!"
4159 (interactive
4160 (list
4161 (progn
4162 (barf-if-buffer-read-only)
4163 (read-buffer "Insert buffer: "
4164 (if (eq (selected-window) (next-window))
4165 (other-buffer (current-buffer))
4166 (window-buffer (next-window)))
4167 t))))
4168 (push-mark
4169 (save-excursion
4170 (insert-buffer-substring (get-buffer buffer))
4171 (point)))
4172 nil)
4173 (put 'insert-buffer 'interactive-only 'insert-buffer-substring)
4175 (defun append-to-buffer (buffer start end)
4176 "Append to specified buffer the text of the region.
4177 It is inserted into that buffer before its point.
4179 When calling from a program, give three arguments:
4180 BUFFER (or buffer name), START and END.
4181 START and END specify the portion of the current buffer to be copied."
4182 (interactive
4183 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
4184 (region-beginning) (region-end)))
4185 (let* ((oldbuf (current-buffer))
4186 (append-to (get-buffer-create buffer))
4187 (windows (get-buffer-window-list append-to t t))
4188 point)
4189 (save-excursion
4190 (with-current-buffer append-to
4191 (setq point (point))
4192 (barf-if-buffer-read-only)
4193 (insert-buffer-substring oldbuf start end)
4194 (dolist (window windows)
4195 (when (= (window-point window) point)
4196 (set-window-point window (point))))))))
4198 (defun prepend-to-buffer (buffer start end)
4199 "Prepend to specified buffer the text of the region.
4200 It is inserted into that buffer after its point.
4202 When calling from a program, give three arguments:
4203 BUFFER (or buffer name), START and END.
4204 START and END specify the portion of the current buffer to be copied."
4205 (interactive "BPrepend to buffer: \nr")
4206 (let ((oldbuf (current-buffer)))
4207 (with-current-buffer (get-buffer-create buffer)
4208 (barf-if-buffer-read-only)
4209 (save-excursion
4210 (insert-buffer-substring oldbuf start end)))))
4212 (defun copy-to-buffer (buffer start end)
4213 "Copy to specified buffer the text of the region.
4214 It is inserted into that buffer, replacing existing text there.
4216 When calling from a program, give three arguments:
4217 BUFFER (or buffer name), START and END.
4218 START and END specify the portion of the current buffer to be copied."
4219 (interactive "BCopy to buffer: \nr")
4220 (let ((oldbuf (current-buffer)))
4221 (with-current-buffer (get-buffer-create buffer)
4222 (barf-if-buffer-read-only)
4223 (erase-buffer)
4224 (save-excursion
4225 (insert-buffer-substring oldbuf start end)))))
4227 (define-error 'mark-inactive (purecopy "The mark is not active now"))
4229 (defvar activate-mark-hook nil
4230 "Hook run when the mark becomes active.
4231 It is also run at the end of a command, if the mark is active and
4232 it is possible that the region may have changed.")
4234 (defvar deactivate-mark-hook nil
4235 "Hook run when the mark becomes inactive.")
4237 (defun mark (&optional force)
4238 "Return this buffer's mark value as integer, or nil if never set.
4240 In Transient Mark mode, this function signals an error if
4241 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
4242 or the argument FORCE is non-nil, it disregards whether the mark
4243 is active, and returns an integer or nil in the usual way.
4245 If you are using this in an editing command, you are most likely making
4246 a mistake; see the documentation of `set-mark'."
4247 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
4248 (marker-position (mark-marker))
4249 (signal 'mark-inactive nil)))
4251 ;; Behind display-selections-p.
4252 (declare-function x-selection-owner-p "xselect.c"
4253 (&optional selection terminal))
4254 (declare-function x-selection-exists-p "xselect.c"
4255 (&optional selection terminal))
4257 (defun deactivate-mark (&optional force)
4258 "Deactivate the mark.
4259 If Transient Mark mode is disabled, this function normally does
4260 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
4262 Deactivating the mark sets `mark-active' to nil, updates the
4263 primary selection according to `select-active-regions', and runs
4264 `deactivate-mark-hook'.
4266 If Transient Mark mode was temporarily enabled, reset the value
4267 of the variable `transient-mark-mode'; if this causes Transient
4268 Mark mode to be disabled, don't change `mark-active' to nil or
4269 run `deactivate-mark-hook'."
4270 (when (or transient-mark-mode force)
4271 (when (and (if (eq select-active-regions 'only)
4272 (eq (car-safe transient-mark-mode) 'only)
4273 select-active-regions)
4274 (region-active-p)
4275 (display-selections-p))
4276 ;; The var `saved-region-selection', if non-nil, is the text in
4277 ;; the region prior to the last command modifying the buffer.
4278 ;; Set the selection to that, or to the current region.
4279 (cond (saved-region-selection
4280 (x-set-selection 'PRIMARY saved-region-selection)
4281 (setq saved-region-selection nil))
4282 ;; If another program has acquired the selection, region
4283 ;; deactivation should not clobber it (Bug#11772).
4284 ((and (/= (region-beginning) (region-end))
4285 (or (x-selection-owner-p 'PRIMARY)
4286 (null (x-selection-exists-p 'PRIMARY))))
4287 (x-set-selection 'PRIMARY
4288 (funcall region-extract-function nil)))))
4289 (if (and (null force)
4290 (or (eq transient-mark-mode 'lambda)
4291 (and (eq (car-safe transient-mark-mode) 'only)
4292 (null (cdr transient-mark-mode)))))
4293 ;; When deactivating a temporary region, don't change
4294 ;; `mark-active' or run `deactivate-mark-hook'.
4295 (setq transient-mark-mode nil)
4296 (if (eq (car-safe transient-mark-mode) 'only)
4297 (setq transient-mark-mode (cdr transient-mark-mode)))
4298 (setq mark-active nil)
4299 (run-hooks 'deactivate-mark-hook))))
4301 (defun activate-mark ()
4302 "Activate the mark."
4303 (when (mark t)
4304 (setq mark-active t)
4305 (unless transient-mark-mode
4306 (setq transient-mark-mode 'lambda))
4307 (run-hooks 'activate-mark-hook)))
4309 (defun set-mark (pos)
4310 "Set this buffer's mark to POS. Don't use this function!
4311 That is to say, don't use this function unless you want
4312 the user to see that the mark has moved, and you want the previous
4313 mark position to be lost.
4315 Normally, when a new mark is set, the old one should go on the stack.
4316 This is why most applications should use `push-mark', not `set-mark'.
4318 Novice Emacs Lisp programmers often try to use the mark for the wrong
4319 purposes. The mark saves a location for the user's convenience.
4320 Most editing commands should not alter the mark.
4321 To remember a location for internal use in the Lisp program,
4322 store it in a Lisp variable. Example:
4324 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
4326 (if pos
4327 (progn
4328 (setq mark-active t)
4329 (run-hooks 'activate-mark-hook)
4330 (set-marker (mark-marker) pos (current-buffer)))
4331 ;; Normally we never clear mark-active except in Transient Mark mode.
4332 ;; But when we actually clear out the mark value too, we must
4333 ;; clear mark-active in any mode.
4334 (deactivate-mark t)
4335 (set-marker (mark-marker) nil)))
4337 (defcustom use-empty-active-region nil
4338 "Whether \"region-aware\" commands should act on empty regions.
4339 If nil, region-aware commands treat empty regions as inactive.
4340 If non-nil, region-aware commands treat the region as active as
4341 long as the mark is active, even if the region is empty.
4343 Region-aware commands are those that act on the region if it is
4344 active and Transient Mark mode is enabled, and on the text near
4345 point otherwise."
4346 :type 'boolean
4347 :version "23.1"
4348 :group 'editing-basics)
4350 (defun use-region-p ()
4351 "Return t if the region is active and it is appropriate to act on it.
4352 This is used by commands that act specially on the region under
4353 Transient Mark mode.
4355 The return value is t if Transient Mark mode is enabled and the
4356 mark is active; furthermore, if `use-empty-active-region' is nil,
4357 the region must not be empty. Otherwise, the return value is nil.
4359 For some commands, it may be appropriate to ignore the value of
4360 `use-empty-active-region'; in that case, use `region-active-p'."
4361 (and (region-active-p)
4362 (or use-empty-active-region (> (region-end) (region-beginning)))))
4364 (defun region-active-p ()
4365 "Return t if Transient Mark mode is enabled and the mark is active.
4367 Some commands act specially on the region when Transient Mark
4368 mode is enabled. Usually, such commands should use
4369 `use-region-p' instead of this function, because `use-region-p'
4370 also checks the value of `use-empty-active-region'."
4371 (and transient-mark-mode mark-active))
4374 (defvar redisplay-unhighlight-region-function
4375 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
4377 (defvar redisplay-highlight-region-function
4378 (lambda (start end window rol)
4379 (if (not (overlayp rol))
4380 (let ((nrol (make-overlay start end)))
4381 (funcall redisplay-unhighlight-region-function rol)
4382 (overlay-put nrol 'window window)
4383 (overlay-put nrol 'face 'region)
4384 nrol)
4385 (unless (and (eq (overlay-buffer rol) (current-buffer))
4386 (eq (overlay-start rol) start)
4387 (eq (overlay-end rol) end))
4388 (move-overlay rol start end (current-buffer)))
4389 rol)))
4391 (defun redisplay--update-region-highlight (window)
4392 (with-current-buffer (window-buffer window)
4393 (let ((rol (window-parameter window 'internal-region-overlay)))
4394 (if (not (region-active-p))
4395 (funcall redisplay-unhighlight-region-function rol)
4396 (let* ((pt (window-point window))
4397 (mark (mark))
4398 (start (min pt mark))
4399 (end (max pt mark))
4400 (new
4401 (funcall redisplay-highlight-region-function
4402 start end window rol)))
4403 (unless (equal new rol)
4404 (set-window-parameter window 'internal-region-overlay
4405 new)))))))
4407 (defun redisplay--update-region-highlights (windows)
4408 (with-demoted-errors "redisplay--update-region-highlights: %S"
4409 (if (null windows)
4410 (redisplay--update-region-highlight (selected-window))
4411 (unless (listp windows) (setq windows (window-list-1 nil nil t)))
4412 (if highlight-nonselected-windows
4413 (mapc #'redisplay--update-region-highlight windows)
4414 (let ((msw (and (window-minibuffer-p) (minibuffer-selected-window))))
4415 (dolist (w windows)
4416 (if (or (eq w (selected-window)) (eq w msw))
4417 (redisplay--update-region-highlight w)
4418 (funcall redisplay-unhighlight-region-function
4419 (window-parameter w 'internal-region-overlay)))))))))
4421 (add-function :before pre-redisplay-function
4422 #'redisplay--update-region-highlights)
4425 (defvar-local mark-ring nil
4426 "The list of former marks of the current buffer, most recent first.")
4427 (put 'mark-ring 'permanent-local t)
4429 (defcustom mark-ring-max 16
4430 "Maximum size of mark ring. Start discarding off end if gets this big."
4431 :type 'integer
4432 :group 'editing-basics)
4434 (defvar global-mark-ring nil
4435 "The list of saved global marks, most recent first.")
4437 (defcustom global-mark-ring-max 16
4438 "Maximum size of global mark ring. \
4439 Start discarding off end if gets this big."
4440 :type 'integer
4441 :group 'editing-basics)
4443 (defun pop-to-mark-command ()
4444 "Jump to mark, and pop a new position for mark off the ring.
4445 \(Does not affect global mark ring\)."
4446 (interactive)
4447 (if (null (mark t))
4448 (error "No mark set in this buffer")
4449 (if (= (point) (mark t))
4450 (message "Mark popped"))
4451 (goto-char (mark t))
4452 (pop-mark)))
4454 (defun push-mark-command (arg &optional nomsg)
4455 "Set mark at where point is.
4456 If no prefix ARG and mark is already set there, just activate it.
4457 Display `Mark set' unless the optional second arg NOMSG is non-nil."
4458 (interactive "P")
4459 (let ((mark (marker-position (mark-marker))))
4460 (if (or arg (null mark) (/= mark (point)))
4461 (push-mark nil nomsg t)
4462 (setq mark-active t)
4463 (run-hooks 'activate-mark-hook)
4464 (unless nomsg
4465 (message "Mark activated")))))
4467 (defcustom set-mark-command-repeat-pop nil
4468 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
4469 That means that C-u \\[set-mark-command] \\[set-mark-command]
4470 will pop the mark twice, and
4471 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
4472 will pop the mark three times.
4474 A value of nil means \\[set-mark-command]'s behavior does not change
4475 after C-u \\[set-mark-command]."
4476 :type 'boolean
4477 :group 'editing-basics)
4479 (defun set-mark-command (arg)
4480 "Set the mark where point is, or jump to the mark.
4481 Setting the mark also alters the region, which is the text
4482 between point and mark; this is the closest equivalent in
4483 Emacs to what some editors call the \"selection\".
4485 With no prefix argument, set the mark at point, and push the
4486 old mark position on local mark ring. Also push the old mark on
4487 global mark ring, if the previous mark was set in another buffer.
4489 When Transient Mark Mode is off, immediately repeating this
4490 command activates `transient-mark-mode' temporarily.
4492 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
4493 jump to the mark, and set the mark from
4494 position popped off the local mark ring \(this does not affect the global
4495 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
4496 mark ring \(see `pop-global-mark'\).
4498 If `set-mark-command-repeat-pop' is non-nil, repeating
4499 the \\[set-mark-command] command with no prefix argument pops the next position
4500 off the local (or global) mark ring and jumps there.
4502 With \\[universal-argument] \\[universal-argument] as prefix
4503 argument, unconditionally set mark where point is, even if
4504 `set-mark-command-repeat-pop' is non-nil.
4506 Novice Emacs Lisp programmers often try to use the mark for the wrong
4507 purposes. See the documentation of `set-mark' for more information."
4508 (interactive "P")
4509 (cond ((eq transient-mark-mode 'lambda)
4510 (setq transient-mark-mode nil))
4511 ((eq (car-safe transient-mark-mode) 'only)
4512 (deactivate-mark)))
4513 (cond
4514 ((and (consp arg) (> (prefix-numeric-value arg) 4))
4515 (push-mark-command nil))
4516 ((not (eq this-command 'set-mark-command))
4517 (if arg
4518 (pop-to-mark-command)
4519 (push-mark-command t)))
4520 ((and set-mark-command-repeat-pop
4521 (eq last-command 'pop-to-mark-command))
4522 (setq this-command 'pop-to-mark-command)
4523 (pop-to-mark-command))
4524 ((and set-mark-command-repeat-pop
4525 (eq last-command 'pop-global-mark)
4526 (not arg))
4527 (setq this-command 'pop-global-mark)
4528 (pop-global-mark))
4529 (arg
4530 (setq this-command 'pop-to-mark-command)
4531 (pop-to-mark-command))
4532 ((eq last-command 'set-mark-command)
4533 (if (region-active-p)
4534 (progn
4535 (deactivate-mark)
4536 (message "Mark deactivated"))
4537 (activate-mark)
4538 (message "Mark activated")))
4540 (push-mark-command nil))))
4542 (defun push-mark (&optional location nomsg activate)
4543 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
4544 If the last global mark pushed was not in the current buffer,
4545 also push LOCATION on the global mark ring.
4546 Display `Mark set' unless the optional second arg NOMSG is non-nil.
4548 Novice Emacs Lisp programmers often try to use the mark for the wrong
4549 purposes. See the documentation of `set-mark' for more information.
4551 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
4552 (unless (null (mark t))
4553 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
4554 (when (> (length mark-ring) mark-ring-max)
4555 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
4556 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
4557 (set-marker (mark-marker) (or location (point)) (current-buffer))
4558 ;; Now push the mark on the global mark ring.
4559 (if (and global-mark-ring
4560 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
4561 ;; The last global mark pushed was in this same buffer.
4562 ;; Don't push another one.
4564 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
4565 (when (> (length global-mark-ring) global-mark-ring-max)
4566 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
4567 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
4568 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
4569 (message "Mark set"))
4570 (if (or activate (not transient-mark-mode))
4571 (set-mark (mark t)))
4572 nil)
4574 (defun pop-mark ()
4575 "Pop off mark ring into the buffer's actual mark.
4576 Does not set point. Does nothing if mark ring is empty."
4577 (when mark-ring
4578 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
4579 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
4580 (move-marker (car mark-ring) nil)
4581 (if (null (mark t)) (ding))
4582 (setq mark-ring (cdr mark-ring)))
4583 (deactivate-mark))
4585 (define-obsolete-function-alias
4586 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
4587 (defun exchange-point-and-mark (&optional arg)
4588 "Put the mark where point is now, and point where the mark is now.
4589 This command works even when the mark is not active,
4590 and it reactivates the mark.
4592 If Transient Mark mode is on, a prefix ARG deactivates the mark
4593 if it is active, and otherwise avoids reactivating it. If
4594 Transient Mark mode is off, a prefix ARG enables Transient Mark
4595 mode temporarily."
4596 (interactive "P")
4597 (let ((omark (mark t))
4598 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
4599 (if (null omark)
4600 (error "No mark set in this buffer"))
4601 (set-mark (point))
4602 (goto-char omark)
4603 (cond (temp-highlight
4604 (setq transient-mark-mode (cons 'only transient-mark-mode)))
4605 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
4606 (not (or arg (region-active-p))))
4607 (deactivate-mark))
4608 (t (activate-mark)))
4609 nil))
4611 (defcustom shift-select-mode t
4612 "When non-nil, shifted motion keys activate the mark momentarily.
4614 While the mark is activated in this way, any shift-translated point
4615 motion key extends the region, and if Transient Mark mode was off, it
4616 is temporarily turned on. Furthermore, the mark will be deactivated
4617 by any subsequent point motion key that was not shift-translated, or
4618 by any action that normally deactivates the mark in Transient Mark mode.
4620 See `this-command-keys-shift-translated' for the meaning of
4621 shift-translation."
4622 :type 'boolean
4623 :group 'editing-basics)
4625 (defun handle-shift-selection ()
4626 "Activate/deactivate mark depending on invocation thru shift translation.
4627 This function is called by `call-interactively' when a command
4628 with a `^' character in its `interactive' spec is invoked, before
4629 running the command itself.
4631 If `shift-select-mode' is enabled and the command was invoked
4632 through shift translation, set the mark and activate the region
4633 temporarily, unless it was already set in this way. See
4634 `this-command-keys-shift-translated' for the meaning of shift
4635 translation.
4637 Otherwise, if the region has been activated temporarily,
4638 deactivate it, and restore the variable `transient-mark-mode' to
4639 its earlier value."
4640 (cond ((and shift-select-mode this-command-keys-shift-translated)
4641 (unless (and mark-active
4642 (eq (car-safe transient-mark-mode) 'only))
4643 (setq transient-mark-mode
4644 (cons 'only
4645 (unless (eq transient-mark-mode 'lambda)
4646 transient-mark-mode)))
4647 (push-mark nil nil t)))
4648 ((eq (car-safe transient-mark-mode) 'only)
4649 (setq transient-mark-mode (cdr transient-mark-mode))
4650 (deactivate-mark))))
4652 (define-minor-mode transient-mark-mode
4653 "Toggle Transient Mark mode.
4654 With a prefix argument ARG, enable Transient Mark mode if ARG is
4655 positive, and disable it otherwise. If called from Lisp, enable
4656 Transient Mark mode if ARG is omitted or nil.
4658 Transient Mark mode is a global minor mode. When enabled, the
4659 region is highlighted whenever the mark is active. The mark is
4660 \"deactivated\" by changing the buffer, and after certain other
4661 operations that set the mark but whose main purpose is something
4662 else--for example, incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4664 You can also deactivate the mark by typing \\[keyboard-quit] or
4665 \\[keyboard-escape-quit].
4667 Many commands change their behavior when Transient Mark mode is
4668 in effect and the mark is active, by acting on the region instead
4669 of their usual default part of the buffer's text. Examples of
4670 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
4671 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4672 To see the documentation of commands which are sensitive to the
4673 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
4674 or \"mark.*active\" at the prompt."
4675 :global t
4676 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4677 :variable transient-mark-mode)
4679 (defvar widen-automatically t
4680 "Non-nil means it is ok for commands to call `widen' when they want to.
4681 Some commands will do this in order to go to positions outside
4682 the current accessible part of the buffer.
4684 If `widen-automatically' is nil, these commands will do something else
4685 as a fallback, and won't change the buffer bounds.")
4687 (defvar non-essential nil
4688 "Whether the currently executing code is performing an essential task.
4689 This variable should be non-nil only when running code which should not
4690 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4691 user for a password when we are simply scanning a set of files in the
4692 background or displaying possible completions before the user even asked
4693 for it.")
4695 (defun pop-global-mark ()
4696 "Pop off global mark ring and jump to the top location."
4697 (interactive)
4698 ;; Pop entries which refer to non-existent buffers.
4699 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4700 (setq global-mark-ring (cdr global-mark-ring)))
4701 (or global-mark-ring
4702 (error "No global mark set"))
4703 (let* ((marker (car global-mark-ring))
4704 (buffer (marker-buffer marker))
4705 (position (marker-position marker)))
4706 (setq global-mark-ring (nconc (cdr global-mark-ring)
4707 (list (car global-mark-ring))))
4708 (set-buffer buffer)
4709 (or (and (>= position (point-min))
4710 (<= position (point-max)))
4711 (if widen-automatically
4712 (widen)
4713 (error "Global mark position is outside accessible part of buffer")))
4714 (goto-char position)
4715 (switch-to-buffer buffer)))
4717 (defcustom next-line-add-newlines nil
4718 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4719 :type 'boolean
4720 :version "21.1"
4721 :group 'editing-basics)
4723 (defun next-line (&optional arg try-vscroll)
4724 "Move cursor vertically down ARG lines.
4725 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4726 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4727 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4728 function will not vscroll.
4730 ARG defaults to 1.
4732 If there is no character in the target line exactly under the current column,
4733 the cursor is positioned after the character in that line which spans this
4734 column, or at the end of the line if it is not long enough.
4735 If there is no line in the buffer after this one, behavior depends on the
4736 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4737 to create a line, and moves the cursor to that line. Otherwise it moves the
4738 cursor to the end of the buffer.
4740 If the variable `line-move-visual' is non-nil, this command moves
4741 by display lines. Otherwise, it moves by buffer lines, without
4742 taking variable-width characters or continued lines into account.
4744 The command \\[set-goal-column] can be used to create
4745 a semipermanent goal column for this command.
4746 Then instead of trying to move exactly vertically (or as close as possible),
4747 this command moves to the specified goal column (or as close as possible).
4748 The goal column is stored in the variable `goal-column', which is nil
4749 when there is no goal column. Note that setting `goal-column'
4750 overrides `line-move-visual' and causes this command to move by buffer
4751 lines rather than by display lines.
4753 If you are thinking of using this in a Lisp program, consider
4754 using `forward-line' instead. It is usually easier to use
4755 and more reliable (no dependence on goal column, etc.)."
4756 (interactive "^p\np")
4757 (or arg (setq arg 1))
4758 (if (and next-line-add-newlines (= arg 1))
4759 (if (save-excursion (end-of-line) (eobp))
4760 ;; When adding a newline, don't expand an abbrev.
4761 (let ((abbrev-mode nil))
4762 (end-of-line)
4763 (insert (if use-hard-newlines hard-newline "\n")))
4764 (line-move arg nil nil try-vscroll))
4765 (if (called-interactively-p 'interactive)
4766 (condition-case err
4767 (line-move arg nil nil try-vscroll)
4768 ((beginning-of-buffer end-of-buffer)
4769 (signal (car err) (cdr err))))
4770 (line-move arg nil nil try-vscroll)))
4771 nil)
4772 (put 'next-line 'interactive-only 'forward-line)
4774 (defun previous-line (&optional arg try-vscroll)
4775 "Move cursor vertically up ARG lines.
4776 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4777 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4778 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4779 function will not vscroll.
4781 ARG defaults to 1.
4783 If there is no character in the target line exactly over the current column,
4784 the cursor is positioned after the character in that line which spans this
4785 column, or at the end of the line if it is not long enough.
4787 If the variable `line-move-visual' is non-nil, this command moves
4788 by display lines. Otherwise, it moves by buffer lines, without
4789 taking variable-width characters or continued lines into account.
4791 The command \\[set-goal-column] can be used to create
4792 a semipermanent goal column for this command.
4793 Then instead of trying to move exactly vertically (or as close as possible),
4794 this command moves to the specified goal column (or as close as possible).
4795 The goal column is stored in the variable `goal-column', which is nil
4796 when there is no goal column. Note that setting `goal-column'
4797 overrides `line-move-visual' and causes this command to move by buffer
4798 lines rather than by display lines.
4800 If you are thinking of using this in a Lisp program, consider using
4801 `forward-line' with a negative argument instead. It is usually easier
4802 to use and more reliable (no dependence on goal column, etc.)."
4803 (interactive "^p\np")
4804 (or arg (setq arg 1))
4805 (if (called-interactively-p 'interactive)
4806 (condition-case err
4807 (line-move (- arg) nil nil try-vscroll)
4808 ((beginning-of-buffer end-of-buffer)
4809 (signal (car err) (cdr err))))
4810 (line-move (- arg) nil nil try-vscroll))
4811 nil)
4812 (put 'previous-line 'interactive-only
4813 "use `forward-line' with negative argument instead.")
4815 (defcustom track-eol nil
4816 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4817 This means moving to the end of each line moved onto.
4818 The beginning of a blank line does not count as the end of a line.
4819 This has no effect when the variable `line-move-visual' is non-nil."
4820 :type 'boolean
4821 :group 'editing-basics)
4823 (defcustom goal-column nil
4824 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
4825 A non-nil setting overrides the variable `line-move-visual', which see."
4826 :type '(choice integer
4827 (const :tag "None" nil))
4828 :group 'editing-basics)
4829 (make-variable-buffer-local 'goal-column)
4831 (defvar temporary-goal-column 0
4832 "Current goal column for vertical motion.
4833 It is the column where point was at the start of the current run
4834 of vertical motion commands.
4836 When moving by visual lines via the function `line-move-visual', it is a cons
4837 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4838 divided by the default column width, and HSCROLL is the number of
4839 columns by which window is scrolled from left margin.
4841 When the `track-eol' feature is doing its job, the value is
4842 `most-positive-fixnum'.")
4844 (defcustom line-move-ignore-invisible t
4845 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
4846 Outline mode sets this."
4847 :type 'boolean
4848 :group 'editing-basics)
4850 (defcustom line-move-visual t
4851 "When non-nil, `line-move' moves point by visual lines.
4852 This movement is based on where the cursor is displayed on the
4853 screen, instead of relying on buffer contents alone. It takes
4854 into account variable-width characters and line continuation.
4855 If nil, `line-move' moves point by logical lines.
4856 A non-nil setting of `goal-column' overrides the value of this variable
4857 and forces movement by logical lines.
4858 A window that is horizontally scrolled also forces movement by logical
4859 lines."
4860 :type 'boolean
4861 :group 'editing-basics
4862 :version "23.1")
4864 ;; Only used if display-graphic-p.
4865 (declare-function font-info "font.c" (name &optional frame))
4867 (defun default-font-height ()
4868 "Return the height in pixels of the current buffer's default face font."
4869 (let ((default-font (face-font 'default)))
4870 (cond
4871 ((and (display-multi-font-p)
4872 ;; Avoid calling font-info if the frame's default font was
4873 ;; not changed since the frame was created. That's because
4874 ;; font-info is expensive for some fonts, see bug #14838.
4875 (not (string= (frame-parameter nil 'font) default-font)))
4876 (aref (font-info default-font) 3))
4877 (t (frame-char-height)))))
4879 (defun default-line-height ()
4880 "Return the pixel height of current buffer's default-face text line.
4882 The value includes `line-spacing', if any, defined for the buffer
4883 or the frame."
4884 (let ((dfh (default-font-height))
4885 (lsp (if (display-graphic-p)
4886 (or line-spacing
4887 (default-value 'line-spacing)
4888 (frame-parameter nil 'line-spacing)
4890 0)))
4891 (if (floatp lsp)
4892 (setq lsp (* dfh lsp)))
4893 (+ dfh lsp)))
4895 (defun window-screen-lines ()
4896 "Return the number of screen lines in the text area of the selected window.
4898 This is different from `window-text-height' in that this function counts
4899 lines in units of the height of the font used by the default face displayed
4900 in the window, not in units of the frame's default font, and also accounts
4901 for `line-spacing', if any, defined for the window's buffer or frame.
4903 The value is a floating-point number."
4904 (let ((canonical (window-text-height))
4905 (fch (frame-char-height))
4906 (dlh (default-line-height)))
4907 (/ (* (float canonical) fch) dlh)))
4909 ;; Returns non-nil if partial move was done.
4910 (defun line-move-partial (arg noerror to-end)
4911 (if (< arg 0)
4912 ;; Move backward (up).
4913 ;; If already vscrolled, reduce vscroll
4914 (let ((vs (window-vscroll nil t))
4915 (dlh (default-line-height)))
4916 (when (> vs dlh)
4917 (set-window-vscroll nil (- vs dlh) t)))
4919 ;; Move forward (down).
4920 (let* ((lh (window-line-height -1))
4921 (rowh (car lh))
4922 (vpos (nth 1 lh))
4923 (ypos (nth 2 lh))
4924 (rbot (nth 3 lh))
4925 (this-lh (window-line-height))
4926 (this-height (car this-lh))
4927 (this-ypos (nth 2 this-lh))
4928 (dlh (default-line-height))
4929 (wslines (window-screen-lines))
4930 (edges (window-inside-pixel-edges))
4931 (winh (- (nth 3 edges) (nth 1 edges) 1))
4932 py vs last-line)
4933 (if (> (mod wslines 1.0) 0.0)
4934 (setq wslines (round (+ wslines 0.5))))
4935 (when (or (null lh)
4936 (>= rbot dlh)
4937 (<= ypos (- dlh))
4938 (null this-lh)
4939 (<= this-ypos (- dlh)))
4940 (unless lh
4941 (let ((wend (pos-visible-in-window-p t nil t)))
4942 (setq rbot (nth 3 wend)
4943 rowh (nth 4 wend)
4944 vpos (nth 5 wend))))
4945 (unless this-lh
4946 (let ((wstart (pos-visible-in-window-p nil nil t)))
4947 (setq this-ypos (nth 2 wstart)
4948 this-height (nth 4 wstart))))
4949 (setq py
4950 (or (nth 1 this-lh)
4951 (let ((ppos (posn-at-point))
4952 col-row)
4953 (setq col-row (posn-actual-col-row ppos))
4954 (if col-row
4955 (- (cdr col-row) (window-vscroll))
4956 (cdr (posn-col-row ppos))))))
4957 ;; VPOS > 0 means the last line is only partially visible.
4958 ;; But if the part that is visible is at least as tall as the
4959 ;; default font, that means the line is actually fully
4960 ;; readable, and something like line-spacing is hidden. So in
4961 ;; that case we accept the last line in the window as still
4962 ;; visible, and consider the margin as starting one line
4963 ;; later.
4964 (if (and vpos (> vpos 0))
4965 (if (and rowh
4966 (>= rowh (default-font-height))
4967 (< rowh dlh))
4968 (setq last-line (min (- wslines scroll-margin) vpos))
4969 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
4970 (cond
4971 ;; If last line of window is fully visible, and vscrolling
4972 ;; more would make this line invisible, move forward.
4973 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
4974 (null this-height)
4975 (<= this-height dlh))
4976 (or (null rbot) (= rbot 0)))
4977 nil)
4978 ;; If cursor is not in the bottom scroll margin, and the
4979 ;; current line is is not too tall, move forward.
4980 ((and (or (null this-height) (<= this-height winh))
4981 vpos
4982 (> vpos 0)
4983 (< py last-line))
4984 nil)
4985 ;; When already vscrolled, we vscroll some more if we can,
4986 ;; or clear vscroll and move forward at end of tall image.
4987 ((> vs 0)
4988 (when (or (and rbot (> rbot 0))
4989 (and this-height (> this-height dlh)))
4990 (set-window-vscroll nil (+ vs dlh) t)))
4991 ;; If cursor just entered the bottom scroll margin, move forward,
4992 ;; but also optionally vscroll one line so redisplay won't recenter.
4993 ((and vpos
4994 (> vpos 0)
4995 (= py last-line))
4996 ;; Don't vscroll if the partially-visible line at window
4997 ;; bottom is not too tall (a.k.a. "just one more text
4998 ;; line"): in that case, we do want redisplay to behave
4999 ;; normally, i.e. recenter or whatever.
5001 ;; Note: ROWH + RBOT from the value returned by
5002 ;; pos-visible-in-window-p give the total height of the
5003 ;; partially-visible glyph row at the end of the window. As
5004 ;; we are dealing with floats, we disregard sub-pixel
5005 ;; discrepancies between that and DLH.
5006 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5007 (set-window-vscroll nil dlh t))
5008 (line-move-1 arg noerror to-end)
5010 ;; If there are lines above the last line, scroll-up one line.
5011 ((and vpos (> vpos 0))
5012 (scroll-up 1)
5014 ;; Finally, start vscroll.
5016 (set-window-vscroll nil dlh t)))))))
5019 ;; This is like line-move-1 except that it also performs
5020 ;; vertical scrolling of tall images if appropriate.
5021 ;; That is not really a clean thing to do, since it mixes
5022 ;; scrolling with cursor motion. But so far we don't have
5023 ;; a cleaner solution to the problem of making C-n do something
5024 ;; useful given a tall image.
5025 (defun line-move (arg &optional noerror to-end try-vscroll)
5026 (if noninteractive
5027 (forward-line arg)
5028 (unless (and auto-window-vscroll try-vscroll
5029 ;; Only vscroll for single line moves
5030 (= (abs arg) 1)
5031 ;; Under scroll-conservatively, the display engine
5032 ;; does this better.
5033 (zerop scroll-conservatively)
5034 ;; But don't vscroll in a keyboard macro.
5035 (not defining-kbd-macro)
5036 (not executing-kbd-macro)
5037 (line-move-partial arg noerror to-end))
5038 (set-window-vscroll nil 0 t)
5039 (if (and line-move-visual
5040 ;; Display-based column are incompatible with goal-column.
5041 (not goal-column)
5042 ;; When the text in the window is scrolled to the left,
5043 ;; display-based motion doesn't make sense (because each
5044 ;; logical line occupies exactly one screen line).
5045 (not (> (window-hscroll) 0))
5046 ;; Likewise when the text _was_ scrolled to the left
5047 ;; when the current run of vertical motion commands
5048 ;; started.
5049 (not (and (memq last-command
5050 `(next-line previous-line ,this-command))
5051 auto-hscroll-mode
5052 (numberp temporary-goal-column)
5053 (>= temporary-goal-column
5054 (- (window-width) hscroll-margin)))))
5055 (prog1 (line-move-visual arg noerror)
5056 ;; If we moved into a tall line, set vscroll to make
5057 ;; scrolling through tall images more smooth.
5058 (let ((lh (line-pixel-height))
5059 (edges (window-inside-pixel-edges))
5060 (dlh (default-line-height))
5061 winh)
5062 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5063 (if (and (< arg 0)
5064 (< (point) (window-start))
5065 (> lh winh))
5066 (set-window-vscroll
5068 (- lh dlh) t))))
5069 (line-move-1 arg noerror to-end)))))
5071 ;; Display-based alternative to line-move-1.
5072 ;; Arg says how many lines to move. The value is t if we can move the
5073 ;; specified number of lines.
5074 (defun line-move-visual (arg &optional noerror)
5075 (let ((opoint (point))
5076 (hscroll (window-hscroll))
5077 target-hscroll)
5078 ;; Check if the previous command was a line-motion command, or if
5079 ;; we were called from some other command.
5080 (if (and (consp temporary-goal-column)
5081 (memq last-command `(next-line previous-line ,this-command)))
5082 ;; If so, there's no need to reset `temporary-goal-column',
5083 ;; but we may need to hscroll.
5084 (if (or (/= (cdr temporary-goal-column) hscroll)
5085 (> (cdr temporary-goal-column) 0))
5086 (setq target-hscroll (cdr temporary-goal-column)))
5087 ;; Otherwise, we should reset `temporary-goal-column'.
5088 (let ((posn (posn-at-point)))
5089 (cond
5090 ;; Handle the `overflow-newline-into-fringe' case:
5091 ((eq (nth 1 posn) 'right-fringe)
5092 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
5093 ((car (posn-x-y posn))
5094 (setq temporary-goal-column
5095 (cons (/ (float (car (posn-x-y posn)))
5096 (frame-char-width)) hscroll))))))
5097 (if target-hscroll
5098 (set-window-hscroll (selected-window) target-hscroll))
5099 ;; vertical-motion can move more than it was asked to if it moves
5100 ;; across display strings with newlines. We don't want to ring
5101 ;; the bell and announce beginning/end of buffer in that case.
5102 (or (and (or (and (>= arg 0)
5103 (>= (vertical-motion
5104 (cons (or goal-column
5105 (if (consp temporary-goal-column)
5106 (car temporary-goal-column)
5107 temporary-goal-column))
5108 arg))
5109 arg))
5110 (and (< arg 0)
5111 (<= (vertical-motion
5112 (cons (or goal-column
5113 (if (consp temporary-goal-column)
5114 (car temporary-goal-column)
5115 temporary-goal-column))
5116 arg))
5117 arg)))
5118 (or (>= arg 0)
5119 (/= (point) opoint)
5120 ;; If the goal column lies on a display string,
5121 ;; `vertical-motion' advances the cursor to the end
5122 ;; of the string. For arg < 0, this can cause the
5123 ;; cursor to get stuck. (Bug#3020).
5124 (= (vertical-motion arg) arg)))
5125 (unless noerror
5126 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
5127 nil)))))
5129 ;; This is the guts of next-line and previous-line.
5130 ;; Arg says how many lines to move.
5131 ;; The value is t if we can move the specified number of lines.
5132 (defun line-move-1 (arg &optional noerror _to-end)
5133 ;; Don't run any point-motion hooks, and disregard intangibility,
5134 ;; for intermediate positions.
5135 (let ((inhibit-point-motion-hooks t)
5136 (opoint (point))
5137 (orig-arg arg))
5138 (if (consp temporary-goal-column)
5139 (setq temporary-goal-column (+ (car temporary-goal-column)
5140 (cdr temporary-goal-column))))
5141 (unwind-protect
5142 (progn
5143 (if (not (memq last-command '(next-line previous-line)))
5144 (setq temporary-goal-column
5145 (if (and track-eol (eolp)
5146 ;; Don't count beg of empty line as end of line
5147 ;; unless we just did explicit end-of-line.
5148 (or (not (bolp)) (eq last-command 'move-end-of-line)))
5149 most-positive-fixnum
5150 (current-column))))
5152 (if (not (or (integerp selective-display)
5153 line-move-ignore-invisible))
5154 ;; Use just newline characters.
5155 ;; Set ARG to 0 if we move as many lines as requested.
5156 (or (if (> arg 0)
5157 (progn (if (> arg 1) (forward-line (1- arg)))
5158 ;; This way of moving forward ARG lines
5159 ;; verifies that we have a newline after the last one.
5160 ;; It doesn't get confused by intangible text.
5161 (end-of-line)
5162 (if (zerop (forward-line 1))
5163 (setq arg 0)))
5164 (and (zerop (forward-line arg))
5165 (bolp)
5166 (setq arg 0)))
5167 (unless noerror
5168 (signal (if (< arg 0)
5169 'beginning-of-buffer
5170 'end-of-buffer)
5171 nil)))
5172 ;; Move by arg lines, but ignore invisible ones.
5173 (let (done)
5174 (while (and (> arg 0) (not done))
5175 ;; If the following character is currently invisible,
5176 ;; skip all characters with that same `invisible' property value.
5177 (while (and (not (eobp)) (invisible-p (point)))
5178 (goto-char (next-char-property-change (point))))
5179 ;; Move a line.
5180 ;; We don't use `end-of-line', since we want to escape
5181 ;; from field boundaries occurring exactly at point.
5182 (goto-char (constrain-to-field
5183 (let ((inhibit-field-text-motion t))
5184 (line-end-position))
5185 (point) t t
5186 'inhibit-line-move-field-capture))
5187 ;; If there's no invisibility here, move over the newline.
5188 (cond
5189 ((eobp)
5190 (if (not noerror)
5191 (signal 'end-of-buffer nil)
5192 (setq done t)))
5193 ((and (> arg 1) ;; Use vertical-motion for last move
5194 (not (integerp selective-display))
5195 (not (invisible-p (point))))
5196 ;; We avoid vertical-motion when possible
5197 ;; because that has to fontify.
5198 (forward-line 1))
5199 ;; Otherwise move a more sophisticated way.
5200 ((zerop (vertical-motion 1))
5201 (if (not noerror)
5202 (signal 'end-of-buffer nil)
5203 (setq done t))))
5204 (unless done
5205 (setq arg (1- arg))))
5206 ;; The logic of this is the same as the loop above,
5207 ;; it just goes in the other direction.
5208 (while (and (< arg 0) (not done))
5209 ;; For completely consistency with the forward-motion
5210 ;; case, we should call beginning-of-line here.
5211 ;; However, if point is inside a field and on a
5212 ;; continued line, the call to (vertical-motion -1)
5213 ;; below won't move us back far enough; then we return
5214 ;; to the same column in line-move-finish, and point
5215 ;; gets stuck -- cyd
5216 (forward-line 0)
5217 (cond
5218 ((bobp)
5219 (if (not noerror)
5220 (signal 'beginning-of-buffer nil)
5221 (setq done t)))
5222 ((and (< arg -1) ;; Use vertical-motion for last move
5223 (not (integerp selective-display))
5224 (not (invisible-p (1- (point)))))
5225 (forward-line -1))
5226 ((zerop (vertical-motion -1))
5227 (if (not noerror)
5228 (signal 'beginning-of-buffer nil)
5229 (setq done t))))
5230 (unless done
5231 (setq arg (1+ arg))
5232 (while (and ;; Don't move over previous invis lines
5233 ;; if our target is the middle of this line.
5234 (or (zerop (or goal-column temporary-goal-column))
5235 (< arg 0))
5236 (not (bobp)) (invisible-p (1- (point))))
5237 (goto-char (previous-char-property-change (point))))))))
5238 ;; This is the value the function returns.
5239 (= arg 0))
5241 (cond ((> arg 0)
5242 ;; If we did not move down as far as desired, at least go
5243 ;; to end of line. Be sure to call point-entered and
5244 ;; point-left-hooks.
5245 (let* ((npoint (prog1 (line-end-position)
5246 (goto-char opoint)))
5247 (inhibit-point-motion-hooks nil))
5248 (goto-char npoint)))
5249 ((< arg 0)
5250 ;; If we did not move up as far as desired,
5251 ;; at least go to beginning of line.
5252 (let* ((npoint (prog1 (line-beginning-position)
5253 (goto-char opoint)))
5254 (inhibit-point-motion-hooks nil))
5255 (goto-char npoint)))
5257 (line-move-finish (or goal-column temporary-goal-column)
5258 opoint (> orig-arg 0)))))))
5260 (defun line-move-finish (column opoint forward)
5261 (let ((repeat t))
5262 (while repeat
5263 ;; Set REPEAT to t to repeat the whole thing.
5264 (setq repeat nil)
5266 (let (new
5267 (old (point))
5268 (line-beg (line-beginning-position))
5269 (line-end
5270 ;; Compute the end of the line
5271 ;; ignoring effectively invisible newlines.
5272 (save-excursion
5273 ;; Like end-of-line but ignores fields.
5274 (skip-chars-forward "^\n")
5275 (while (and (not (eobp)) (invisible-p (point)))
5276 (goto-char (next-char-property-change (point)))
5277 (skip-chars-forward "^\n"))
5278 (point))))
5280 ;; Move to the desired column.
5281 (line-move-to-column (truncate column))
5283 ;; Corner case: suppose we start out in a field boundary in
5284 ;; the middle of a continued line. When we get to
5285 ;; line-move-finish, point is at the start of a new *screen*
5286 ;; line but the same text line; then line-move-to-column would
5287 ;; move us backwards. Test using C-n with point on the "x" in
5288 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
5289 (and forward
5290 (< (point) old)
5291 (goto-char old))
5293 (setq new (point))
5295 ;; Process intangibility within a line.
5296 ;; With inhibit-point-motion-hooks bound to nil, a call to
5297 ;; goto-char moves point past intangible text.
5299 ;; However, inhibit-point-motion-hooks controls both the
5300 ;; intangibility and the point-entered/point-left hooks. The
5301 ;; following hack avoids calling the point-* hooks
5302 ;; unnecessarily. Note that we move *forward* past intangible
5303 ;; text when the initial and final points are the same.
5304 (goto-char new)
5305 (let ((inhibit-point-motion-hooks nil))
5306 (goto-char new)
5308 ;; If intangibility moves us to a different (later) place
5309 ;; in the same line, use that as the destination.
5310 (if (<= (point) line-end)
5311 (setq new (point))
5312 ;; If that position is "too late",
5313 ;; try the previous allowable position.
5314 ;; See if it is ok.
5315 (backward-char)
5316 (if (if forward
5317 ;; If going forward, don't accept the previous
5318 ;; allowable position if it is before the target line.
5319 (< line-beg (point))
5320 ;; If going backward, don't accept the previous
5321 ;; allowable position if it is still after the target line.
5322 (<= (point) line-end))
5323 (setq new (point))
5324 ;; As a last resort, use the end of the line.
5325 (setq new line-end))))
5327 ;; Now move to the updated destination, processing fields
5328 ;; as well as intangibility.
5329 (goto-char opoint)
5330 (let ((inhibit-point-motion-hooks nil))
5331 (goto-char
5332 ;; Ignore field boundaries if the initial and final
5333 ;; positions have the same `field' property, even if the
5334 ;; fields are non-contiguous. This seems to be "nicer"
5335 ;; behavior in many situations.
5336 (if (eq (get-char-property new 'field)
5337 (get-char-property opoint 'field))
5339 (constrain-to-field new opoint t t
5340 'inhibit-line-move-field-capture))))
5342 ;; If all this moved us to a different line,
5343 ;; retry everything within that new line.
5344 (when (or (< (point) line-beg) (> (point) line-end))
5345 ;; Repeat the intangibility and field processing.
5346 (setq repeat t))))))
5348 (defun line-move-to-column (col)
5349 "Try to find column COL, considering invisibility.
5350 This function works only in certain cases,
5351 because what we really need is for `move-to-column'
5352 and `current-column' to be able to ignore invisible text."
5353 (if (zerop col)
5354 (beginning-of-line)
5355 (move-to-column col))
5357 (when (and line-move-ignore-invisible
5358 (not (bolp)) (invisible-p (1- (point))))
5359 (let ((normal-location (point))
5360 (normal-column (current-column)))
5361 ;; If the following character is currently invisible,
5362 ;; skip all characters with that same `invisible' property value.
5363 (while (and (not (eobp))
5364 (invisible-p (point)))
5365 (goto-char (next-char-property-change (point))))
5366 ;; Have we advanced to a larger column position?
5367 (if (> (current-column) normal-column)
5368 ;; We have made some progress towards the desired column.
5369 ;; See if we can make any further progress.
5370 (line-move-to-column (+ (current-column) (- col normal-column)))
5371 ;; Otherwise, go to the place we originally found
5372 ;; and move back over invisible text.
5373 ;; that will get us to the same place on the screen
5374 ;; but with a more reasonable buffer position.
5375 (goto-char normal-location)
5376 (let ((line-beg (line-beginning-position)))
5377 (while (and (not (bolp)) (invisible-p (1- (point))))
5378 (goto-char (previous-char-property-change (point) line-beg))))))))
5380 (defun move-end-of-line (arg)
5381 "Move point to end of current line as displayed.
5382 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5383 If point reaches the beginning or end of buffer, it stops there.
5385 To ignore the effects of the `intangible' text or overlay
5386 property, bind `inhibit-point-motion-hooks' to t.
5387 If there is an image in the current line, this function
5388 disregards newlines that are part of the text on which the image
5389 rests."
5390 (interactive "^p")
5391 (or arg (setq arg 1))
5392 (let (done)
5393 (while (not done)
5394 (let ((newpos
5395 (save-excursion
5396 (let ((goal-column 0)
5397 (line-move-visual nil))
5398 (and (line-move arg t)
5399 ;; With bidi reordering, we may not be at bol,
5400 ;; so make sure we are.
5401 (skip-chars-backward "^\n")
5402 (not (bobp))
5403 (progn
5404 (while (and (not (bobp)) (invisible-p (1- (point))))
5405 (goto-char (previous-single-char-property-change
5406 (point) 'invisible)))
5407 (backward-char 1)))
5408 (point)))))
5409 (goto-char newpos)
5410 (if (and (> (point) newpos)
5411 (eq (preceding-char) ?\n))
5412 (backward-char 1)
5413 (if (and (> (point) newpos) (not (eobp))
5414 (not (eq (following-char) ?\n)))
5415 ;; If we skipped something intangible and now we're not
5416 ;; really at eol, keep going.
5417 (setq arg 1)
5418 (setq done t)))))))
5420 (defun move-beginning-of-line (arg)
5421 "Move point to beginning of current line as displayed.
5422 \(If there's an image in the line, this disregards newlines
5423 which are part of the text that the image rests on.)
5425 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5426 If point reaches the beginning or end of buffer, it stops there.
5427 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5428 (interactive "^p")
5429 (or arg (setq arg 1))
5431 (let ((orig (point))
5432 first-vis first-vis-field-value)
5434 ;; Move by lines, if ARG is not 1 (the default).
5435 (if (/= arg 1)
5436 (let ((line-move-visual nil))
5437 (line-move (1- arg) t)))
5439 ;; Move to beginning-of-line, ignoring fields and invisible text.
5440 (skip-chars-backward "^\n")
5441 (while (and (not (bobp)) (invisible-p (1- (point))))
5442 (goto-char (previous-char-property-change (point)))
5443 (skip-chars-backward "^\n"))
5445 ;; Now find first visible char in the line
5446 (while (and (not (eobp)) (invisible-p (point)))
5447 (goto-char (next-char-property-change (point))))
5448 (setq first-vis (point))
5450 ;; See if fields would stop us from reaching FIRST-VIS.
5451 (setq first-vis-field-value
5452 (constrain-to-field first-vis orig (/= arg 1) t nil))
5454 (goto-char (if (/= first-vis-field-value first-vis)
5455 ;; If yes, obey them.
5456 first-vis-field-value
5457 ;; Otherwise, move to START with attention to fields.
5458 ;; (It is possible that fields never matter in this case.)
5459 (constrain-to-field (point) orig
5460 (/= arg 1) t nil)))))
5463 ;; Many people have said they rarely use this feature, and often type
5464 ;; it by accident. Maybe it shouldn't even be on a key.
5465 (put 'set-goal-column 'disabled t)
5467 (defun set-goal-column (arg)
5468 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
5469 Those commands will move to this position in the line moved to
5470 rather than trying to keep the same horizontal position.
5471 With a non-nil argument ARG, clears out the goal column
5472 so that \\[next-line] and \\[previous-line] resume vertical motion.
5473 The goal column is stored in the variable `goal-column'."
5474 (interactive "P")
5475 (if arg
5476 (progn
5477 (setq goal-column nil)
5478 (message "No goal column"))
5479 (setq goal-column (current-column))
5480 ;; The older method below can be erroneous if `set-goal-column' is bound
5481 ;; to a sequence containing %
5482 ;;(message (substitute-command-keys
5483 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
5484 ;;goal-column)
5485 (message "%s"
5486 (concat
5487 (format "Goal column %d " goal-column)
5488 (substitute-command-keys
5489 "(use \\[set-goal-column] with an arg to unset it)")))
5492 nil)
5494 ;;; Editing based on visual lines, as opposed to logical lines.
5496 (defun end-of-visual-line (&optional n)
5497 "Move point to end of current visual line.
5498 With argument N not nil or 1, move forward N - 1 visual lines first.
5499 If point reaches the beginning or end of buffer, it stops there.
5500 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5501 (interactive "^p")
5502 (or n (setq n 1))
5503 (if (/= n 1)
5504 (let ((line-move-visual t))
5505 (line-move (1- n) t)))
5506 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
5507 ;; constrain to field boundaries, so we don't either.
5508 (vertical-motion (cons (window-width) 0)))
5510 (defun beginning-of-visual-line (&optional n)
5511 "Move point to beginning of current visual line.
5512 With argument N not nil or 1, move forward N - 1 visual lines first.
5513 If point reaches the beginning or end of buffer, it stops there.
5514 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5515 (interactive "^p")
5516 (or n (setq n 1))
5517 (let ((opoint (point)))
5518 (if (/= n 1)
5519 (let ((line-move-visual t))
5520 (line-move (1- n) t)))
5521 (vertical-motion 0)
5522 ;; Constrain to field boundaries, like `move-beginning-of-line'.
5523 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
5525 (defun kill-visual-line (&optional arg)
5526 "Kill the rest of the visual line.
5527 With prefix argument ARG, kill that many visual lines from point.
5528 If ARG is negative, kill visual lines backward.
5529 If ARG is zero, kill the text before point on the current visual
5530 line.
5532 If you want to append the killed line to the last killed text,
5533 use \\[append-next-kill] before \\[kill-line].
5535 If the buffer is read-only, Emacs will beep and refrain from deleting
5536 the line, but put the line in the kill ring anyway. This means that
5537 you can use this command to copy text from a read-only buffer.
5538 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5539 even beep.)"
5540 (interactive "P")
5541 ;; Like in `kill-line', it's better to move point to the other end
5542 ;; of the kill before killing.
5543 (let ((opoint (point))
5544 (kill-whole-line (and kill-whole-line (bolp))))
5545 (if arg
5546 (vertical-motion (prefix-numeric-value arg))
5547 (end-of-visual-line 1)
5548 (if (= (point) opoint)
5549 (vertical-motion 1)
5550 ;; Skip any trailing whitespace at the end of the visual line.
5551 ;; We used to do this only if `show-trailing-whitespace' is
5552 ;; nil, but that's wrong; the correct thing would be to check
5553 ;; whether the trailing whitespace is highlighted. But, it's
5554 ;; OK to just do this unconditionally.
5555 (skip-chars-forward " \t")))
5556 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
5557 (1+ (point))
5558 (point)))))
5560 (defun next-logical-line (&optional arg try-vscroll)
5561 "Move cursor vertically down ARG lines.
5562 This is identical to `next-line', except that it always moves
5563 by logical lines instead of visual lines, ignoring the value of
5564 the variable `line-move-visual'."
5565 (interactive "^p\np")
5566 (let ((line-move-visual nil))
5567 (with-no-warnings
5568 (next-line arg try-vscroll))))
5570 (defun previous-logical-line (&optional arg try-vscroll)
5571 "Move cursor vertically up ARG lines.
5572 This is identical to `previous-line', except that it always moves
5573 by logical lines instead of visual lines, ignoring the value of
5574 the variable `line-move-visual'."
5575 (interactive "^p\np")
5576 (let ((line-move-visual nil))
5577 (with-no-warnings
5578 (previous-line arg try-vscroll))))
5580 (defgroup visual-line nil
5581 "Editing based on visual lines."
5582 :group 'convenience
5583 :version "23.1")
5585 (defvar visual-line-mode-map
5586 (let ((map (make-sparse-keymap)))
5587 (define-key map [remap kill-line] 'kill-visual-line)
5588 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
5589 (define-key map [remap move-end-of-line] 'end-of-visual-line)
5590 ;; These keybindings interfere with xterm function keys. Are
5591 ;; there any other suitable bindings?
5592 ;; (define-key map "\M-[" 'previous-logical-line)
5593 ;; (define-key map "\M-]" 'next-logical-line)
5594 map))
5596 (defcustom visual-line-fringe-indicators '(nil nil)
5597 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
5598 The value should be a list of the form (LEFT RIGHT), where LEFT
5599 and RIGHT are symbols representing the bitmaps to display, to
5600 indicate wrapped lines, in the left and right fringes respectively.
5601 See also `fringe-indicator-alist'.
5602 The default is not to display fringe indicators for wrapped lines.
5603 This variable does not affect fringe indicators displayed for
5604 other purposes."
5605 :type '(list (choice (const :tag "Hide left indicator" nil)
5606 (const :tag "Left curly arrow" left-curly-arrow)
5607 (symbol :tag "Other bitmap"))
5608 (choice (const :tag "Hide right indicator" nil)
5609 (const :tag "Right curly arrow" right-curly-arrow)
5610 (symbol :tag "Other bitmap")))
5611 :set (lambda (symbol value)
5612 (dolist (buf (buffer-list))
5613 (with-current-buffer buf
5614 (when (and (boundp 'visual-line-mode)
5615 (symbol-value 'visual-line-mode))
5616 (setq fringe-indicator-alist
5617 (cons (cons 'continuation value)
5618 (assq-delete-all
5619 'continuation
5620 (copy-tree fringe-indicator-alist)))))))
5621 (set-default symbol value)))
5623 (defvar visual-line--saved-state nil)
5625 (define-minor-mode visual-line-mode
5626 "Toggle visual line based editing (Visual Line mode).
5627 With a prefix argument ARG, enable Visual Line mode if ARG is
5628 positive, and disable it otherwise. If called from Lisp, enable
5629 the mode if ARG is omitted or nil.
5631 When Visual Line mode is enabled, `word-wrap' is turned on in
5632 this buffer, and simple editing commands are redefined to act on
5633 visual lines, not logical lines. See Info node `Visual Line
5634 Mode' for details."
5635 :keymap visual-line-mode-map
5636 :group 'visual-line
5637 :lighter " Wrap"
5638 (if visual-line-mode
5639 (progn
5640 (set (make-local-variable 'visual-line--saved-state) nil)
5641 ;; Save the local values of some variables, to be restored if
5642 ;; visual-line-mode is turned off.
5643 (dolist (var '(line-move-visual truncate-lines
5644 truncate-partial-width-windows
5645 word-wrap fringe-indicator-alist))
5646 (if (local-variable-p var)
5647 (push (cons var (symbol-value var))
5648 visual-line--saved-state)))
5649 (set (make-local-variable 'line-move-visual) t)
5650 (set (make-local-variable 'truncate-partial-width-windows) nil)
5651 (setq truncate-lines nil
5652 word-wrap t
5653 fringe-indicator-alist
5654 (cons (cons 'continuation visual-line-fringe-indicators)
5655 fringe-indicator-alist)))
5656 (kill-local-variable 'line-move-visual)
5657 (kill-local-variable 'word-wrap)
5658 (kill-local-variable 'truncate-lines)
5659 (kill-local-variable 'truncate-partial-width-windows)
5660 (kill-local-variable 'fringe-indicator-alist)
5661 (dolist (saved visual-line--saved-state)
5662 (set (make-local-variable (car saved)) (cdr saved)))
5663 (kill-local-variable 'visual-line--saved-state)))
5665 (defun turn-on-visual-line-mode ()
5666 (visual-line-mode 1))
5668 (define-globalized-minor-mode global-visual-line-mode
5669 visual-line-mode turn-on-visual-line-mode)
5672 (defun transpose-chars (arg)
5673 "Interchange characters around point, moving forward one character.
5674 With prefix arg ARG, effect is to take character before point
5675 and drag it forward past ARG other characters (backward if ARG negative).
5676 If no argument and at end of line, the previous two chars are exchanged."
5677 (interactive "*P")
5678 (and (null arg) (eolp) (forward-char -1))
5679 (transpose-subr 'forward-char (prefix-numeric-value arg)))
5681 (defun transpose-words (arg)
5682 "Interchange words around point, leaving point at end of them.
5683 With prefix arg ARG, effect is to take word before or around point
5684 and drag it forward past ARG other words (backward if ARG negative).
5685 If ARG is zero, the words around or after point and around or after mark
5686 are interchanged."
5687 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
5688 (interactive "*p")
5689 (transpose-subr 'forward-word arg))
5691 (defun transpose-sexps (arg)
5692 "Like \\[transpose-words] but applies to sexps.
5693 Does not work on a sexp that point is in the middle of
5694 if it is a list or string."
5695 (interactive "*p")
5696 (transpose-subr
5697 (lambda (arg)
5698 ;; Here we should try to simulate the behavior of
5699 ;; (cons (progn (forward-sexp x) (point))
5700 ;; (progn (forward-sexp (- x)) (point)))
5701 ;; Except that we don't want to rely on the second forward-sexp
5702 ;; putting us back to where we want to be, since forward-sexp-function
5703 ;; might do funny things like infix-precedence.
5704 (if (if (> arg 0)
5705 (looking-at "\\sw\\|\\s_")
5706 (and (not (bobp))
5707 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
5708 ;; Jumping over a symbol. We might be inside it, mind you.
5709 (progn (funcall (if (> arg 0)
5710 'skip-syntax-backward 'skip-syntax-forward)
5711 "w_")
5712 (cons (save-excursion (forward-sexp arg) (point)) (point)))
5713 ;; Otherwise, we're between sexps. Take a step back before jumping
5714 ;; to make sure we'll obey the same precedence no matter which direction
5715 ;; we're going.
5716 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
5717 (cons (save-excursion (forward-sexp arg) (point))
5718 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
5719 (not (zerop (funcall (if (> arg 0)
5720 'skip-syntax-forward
5721 'skip-syntax-backward)
5722 ".")))))
5723 (point)))))
5724 arg 'special))
5726 (defun transpose-lines (arg)
5727 "Exchange current line and previous line, leaving point after both.
5728 With argument ARG, takes previous line and moves it past ARG lines.
5729 With argument 0, interchanges line point is in with line mark is in."
5730 (interactive "*p")
5731 (transpose-subr (function
5732 (lambda (arg)
5733 (if (> arg 0)
5734 (progn
5735 ;; Move forward over ARG lines,
5736 ;; but create newlines if necessary.
5737 (setq arg (forward-line arg))
5738 (if (/= (preceding-char) ?\n)
5739 (setq arg (1+ arg)))
5740 (if (> arg 0)
5741 (newline arg)))
5742 (forward-line arg))))
5743 arg))
5745 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
5746 ;; which seems inconsistent with the ARG /= 0 case.
5747 ;; FIXME document SPECIAL.
5748 (defun transpose-subr (mover arg &optional special)
5749 "Subroutine to do the work of transposing objects.
5750 Works for lines, sentences, paragraphs, etc. MOVER is a function that
5751 moves forward by units of the given object (e.g. forward-sentence,
5752 forward-paragraph). If ARG is zero, exchanges the current object
5753 with the one containing mark. If ARG is an integer, moves the
5754 current object past ARG following (if ARG is positive) or
5755 preceding (if ARG is negative) objects, leaving point after the
5756 current object."
5757 (let ((aux (if special mover
5758 (lambda (x)
5759 (cons (progn (funcall mover x) (point))
5760 (progn (funcall mover (- x)) (point))))))
5761 pos1 pos2)
5762 (cond
5763 ((= arg 0)
5764 (save-excursion
5765 (setq pos1 (funcall aux 1))
5766 (goto-char (or (mark) (error "No mark set in this buffer")))
5767 (setq pos2 (funcall aux 1))
5768 (transpose-subr-1 pos1 pos2))
5769 (exchange-point-and-mark))
5770 ((> arg 0)
5771 (setq pos1 (funcall aux -1))
5772 (setq pos2 (funcall aux arg))
5773 (transpose-subr-1 pos1 pos2)
5774 (goto-char (car pos2)))
5776 (setq pos1 (funcall aux -1))
5777 (goto-char (car pos1))
5778 (setq pos2 (funcall aux arg))
5779 (transpose-subr-1 pos1 pos2)))))
5781 (defun transpose-subr-1 (pos1 pos2)
5782 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
5783 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
5784 (when (> (car pos1) (car pos2))
5785 (let ((swap pos1))
5786 (setq pos1 pos2 pos2 swap)))
5787 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
5788 (atomic-change-group
5789 ;; This sequence of insertions attempts to preserve marker
5790 ;; positions at the start and end of the transposed objects.
5791 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
5792 (len1 (- (cdr pos1) (car pos1)))
5793 (len2 (length word))
5794 (boundary (make-marker)))
5795 (set-marker boundary (car pos2))
5796 (goto-char (cdr pos1))
5797 (insert-before-markers word)
5798 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
5799 (goto-char boundary)
5800 (insert word)
5801 (goto-char (+ boundary len1))
5802 (delete-region (point) (+ (point) len2))
5803 (set-marker boundary nil))))
5805 (defun backward-word (&optional arg)
5806 "Move backward until encountering the beginning of a word.
5807 With argument ARG, do this that many times.
5808 If ARG is omitted or nil, move point backward one word."
5809 (interactive "^p")
5810 (forward-word (- (or arg 1))))
5812 (defun mark-word (&optional arg allow-extend)
5813 "Set mark ARG words away from point.
5814 The place mark goes is the same place \\[forward-word] would
5815 move to with the same argument.
5816 Interactively, if this command is repeated
5817 or (in Transient Mark mode) if the mark is active,
5818 it marks the next ARG words after the ones already marked."
5819 (interactive "P\np")
5820 (cond ((and allow-extend
5821 (or (and (eq last-command this-command) (mark t))
5822 (region-active-p)))
5823 (setq arg (if arg (prefix-numeric-value arg)
5824 (if (< (mark) (point)) -1 1)))
5825 (set-mark
5826 (save-excursion
5827 (goto-char (mark))
5828 (forward-word arg)
5829 (point))))
5831 (push-mark
5832 (save-excursion
5833 (forward-word (prefix-numeric-value arg))
5834 (point))
5835 nil t))))
5837 (defun kill-word (arg)
5838 "Kill characters forward until encountering the end of a word.
5839 With argument ARG, do this that many times."
5840 (interactive "p")
5841 (kill-region (point) (progn (forward-word arg) (point))))
5843 (defun backward-kill-word (arg)
5844 "Kill characters backward until encountering the beginning of a word.
5845 With argument ARG, do this that many times."
5846 (interactive "p")
5847 (kill-word (- arg)))
5849 (defun current-word (&optional strict really-word)
5850 "Return the symbol or word that point is on (or a nearby one) as a string.
5851 The return value includes no text properties.
5852 If optional arg STRICT is non-nil, return nil unless point is within
5853 or adjacent to a symbol or word. In all cases the value can be nil
5854 if there is no word nearby.
5855 The function, belying its name, normally finds a symbol.
5856 If optional arg REALLY-WORD is non-nil, it finds just a word."
5857 (save-excursion
5858 (let* ((oldpoint (point)) (start (point)) (end (point))
5859 (syntaxes (if really-word "w" "w_"))
5860 (not-syntaxes (concat "^" syntaxes)))
5861 (skip-syntax-backward syntaxes) (setq start (point))
5862 (goto-char oldpoint)
5863 (skip-syntax-forward syntaxes) (setq end (point))
5864 (when (and (eq start oldpoint) (eq end oldpoint)
5865 ;; Point is neither within nor adjacent to a word.
5866 (not strict))
5867 ;; Look for preceding word in same line.
5868 (skip-syntax-backward not-syntaxes (line-beginning-position))
5869 (if (bolp)
5870 ;; No preceding word in same line.
5871 ;; Look for following word in same line.
5872 (progn
5873 (skip-syntax-forward not-syntaxes (line-end-position))
5874 (setq start (point))
5875 (skip-syntax-forward syntaxes)
5876 (setq end (point)))
5877 (setq end (point))
5878 (skip-syntax-backward syntaxes)
5879 (setq start (point))))
5880 ;; If we found something nonempty, return it as a string.
5881 (unless (= start end)
5882 (buffer-substring-no-properties start end)))))
5884 (defcustom fill-prefix nil
5885 "String for filling to insert at front of new line, or nil for none."
5886 :type '(choice (const :tag "None" nil)
5887 string)
5888 :group 'fill)
5889 (make-variable-buffer-local 'fill-prefix)
5890 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
5892 (defcustom auto-fill-inhibit-regexp nil
5893 "Regexp to match lines which should not be auto-filled."
5894 :type '(choice (const :tag "None" nil)
5895 regexp)
5896 :group 'fill)
5898 (defun do-auto-fill ()
5899 "The default value for `normal-auto-fill-function'.
5900 This is the default auto-fill function, some major modes use a different one.
5901 Returns t if it really did any work."
5902 (let (fc justify give-up
5903 (fill-prefix fill-prefix))
5904 (if (or (not (setq justify (current-justification)))
5905 (null (setq fc (current-fill-column)))
5906 (and (eq justify 'left)
5907 (<= (current-column) fc))
5908 (and auto-fill-inhibit-regexp
5909 (save-excursion (beginning-of-line)
5910 (looking-at auto-fill-inhibit-regexp))))
5911 nil ;; Auto-filling not required
5912 (if (memq justify '(full center right))
5913 (save-excursion (unjustify-current-line)))
5915 ;; Choose a fill-prefix automatically.
5916 (when (and adaptive-fill-mode
5917 (or (null fill-prefix) (string= fill-prefix "")))
5918 (let ((prefix
5919 (fill-context-prefix
5920 (save-excursion (fill-forward-paragraph -1) (point))
5921 (save-excursion (fill-forward-paragraph 1) (point)))))
5922 (and prefix (not (equal prefix ""))
5923 ;; Use auto-indentation rather than a guessed empty prefix.
5924 (not (and fill-indent-according-to-mode
5925 (string-match "\\`[ \t]*\\'" prefix)))
5926 (setq fill-prefix prefix))))
5928 (while (and (not give-up) (> (current-column) fc))
5929 ;; Determine where to split the line.
5930 (let* (after-prefix
5931 (fill-point
5932 (save-excursion
5933 (beginning-of-line)
5934 (setq after-prefix (point))
5935 (and fill-prefix
5936 (looking-at (regexp-quote fill-prefix))
5937 (setq after-prefix (match-end 0)))
5938 (move-to-column (1+ fc))
5939 (fill-move-to-break-point after-prefix)
5940 (point))))
5942 ;; See whether the place we found is any good.
5943 (if (save-excursion
5944 (goto-char fill-point)
5945 (or (bolp)
5946 ;; There is no use breaking at end of line.
5947 (save-excursion (skip-chars-forward " ") (eolp))
5948 ;; It is futile to split at the end of the prefix
5949 ;; since we would just insert the prefix again.
5950 (and after-prefix (<= (point) after-prefix))
5951 ;; Don't split right after a comment starter
5952 ;; since we would just make another comment starter.
5953 (and comment-start-skip
5954 (let ((limit (point)))
5955 (beginning-of-line)
5956 (and (re-search-forward comment-start-skip
5957 limit t)
5958 (eq (point) limit))))))
5959 ;; No good place to break => stop trying.
5960 (setq give-up t)
5961 ;; Ok, we have a useful place to break the line. Do it.
5962 (let ((prev-column (current-column)))
5963 ;; If point is at the fill-point, do not `save-excursion'.
5964 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5965 ;; point will end up before it rather than after it.
5966 (if (save-excursion
5967 (skip-chars-backward " \t")
5968 (= (point) fill-point))
5969 (default-indent-new-line t)
5970 (save-excursion
5971 (goto-char fill-point)
5972 (default-indent-new-line t)))
5973 ;; Now do justification, if required
5974 (if (not (eq justify 'left))
5975 (save-excursion
5976 (end-of-line 0)
5977 (justify-current-line justify nil t)))
5978 ;; If making the new line didn't reduce the hpos of
5979 ;; the end of the line, then give up now;
5980 ;; trying again will not help.
5981 (if (>= (current-column) prev-column)
5982 (setq give-up t))))))
5983 ;; Justify last line.
5984 (justify-current-line justify t t)
5985 t)))
5987 (defvar comment-line-break-function 'comment-indent-new-line
5988 "Mode-specific function which line breaks and continues a comment.
5989 This function is called during auto-filling when a comment syntax
5990 is defined.
5991 The function should take a single optional argument, which is a flag
5992 indicating whether it should use soft newlines.")
5994 (defun default-indent-new-line (&optional soft)
5995 "Break line at point and indent.
5996 If a comment syntax is defined, call `comment-indent-new-line'.
5998 The inserted newline is marked hard if variable `use-hard-newlines' is true,
5999 unless optional argument SOFT is non-nil."
6000 (interactive)
6001 (if comment-start
6002 (funcall comment-line-break-function soft)
6003 ;; Insert the newline before removing empty space so that markers
6004 ;; get preserved better.
6005 (if soft (insert-and-inherit ?\n) (newline 1))
6006 (save-excursion (forward-char -1) (delete-horizontal-space))
6007 (delete-horizontal-space)
6009 (if (and fill-prefix (not adaptive-fill-mode))
6010 ;; Blindly trust a non-adaptive fill-prefix.
6011 (progn
6012 (indent-to-left-margin)
6013 (insert-before-markers-and-inherit fill-prefix))
6015 (cond
6016 ;; If there's an adaptive prefix, use it unless we're inside
6017 ;; a comment and the prefix is not a comment starter.
6018 (fill-prefix
6019 (indent-to-left-margin)
6020 (insert-and-inherit fill-prefix))
6021 ;; If we're not inside a comment, just try to indent.
6022 (t (indent-according-to-mode))))))
6024 (defvar normal-auto-fill-function 'do-auto-fill
6025 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6026 Some major modes set this.")
6028 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6029 ;; `functions' and `hooks' are usually unsafe to set, but setting
6030 ;; auto-fill-function to nil in a file-local setting is safe and
6031 ;; can be useful to prevent auto-filling.
6032 (put 'auto-fill-function 'safe-local-variable 'null)
6034 (define-minor-mode auto-fill-mode
6035 "Toggle automatic line breaking (Auto Fill mode).
6036 With a prefix argument ARG, enable Auto Fill mode if ARG is
6037 positive, and disable it otherwise. If called from Lisp, enable
6038 the mode if ARG is omitted or nil.
6040 When Auto Fill mode is enabled, inserting a space at a column
6041 beyond `current-fill-column' automatically breaks the line at a
6042 previous space.
6044 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6045 non-`nil'.
6047 The value of `normal-auto-fill-function' specifies the function to use
6048 for `auto-fill-function' when turning Auto Fill mode on."
6049 :variable (auto-fill-function
6050 . (lambda (v) (setq auto-fill-function
6051 (if v normal-auto-fill-function)))))
6053 ;; This holds a document string used to document auto-fill-mode.
6054 (defun auto-fill-function ()
6055 "Automatically break line at a previous space, in insertion of text."
6056 nil)
6058 (defun turn-on-auto-fill ()
6059 "Unconditionally turn on Auto Fill mode."
6060 (auto-fill-mode 1))
6062 (defun turn-off-auto-fill ()
6063 "Unconditionally turn off Auto Fill mode."
6064 (auto-fill-mode -1))
6066 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
6068 (defun set-fill-column (arg)
6069 "Set `fill-column' to specified argument.
6070 Use \\[universal-argument] followed by a number to specify a column.
6071 Just \\[universal-argument] as argument means to use the current column."
6072 (interactive
6073 (list (or current-prefix-arg
6074 ;; We used to use current-column silently, but C-x f is too easily
6075 ;; typed as a typo for C-x C-f, so we turned it into an error and
6076 ;; now an interactive prompt.
6077 (read-number "Set fill-column to: " (current-column)))))
6078 (if (consp arg)
6079 (setq arg (current-column)))
6080 (if (not (integerp arg))
6081 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6082 (error "set-fill-column requires an explicit argument")
6083 (message "Fill column set to %d (was %d)" arg fill-column)
6084 (setq fill-column arg)))
6086 (defun set-selective-display (arg)
6087 "Set `selective-display' to ARG; clear it if no arg.
6088 When the value of `selective-display' is a number > 0,
6089 lines whose indentation is >= that value are not displayed.
6090 The variable `selective-display' has a separate value for each buffer."
6091 (interactive "P")
6092 (if (eq selective-display t)
6093 (error "selective-display already in use for marked lines"))
6094 (let ((current-vpos
6095 (save-restriction
6096 (narrow-to-region (point-min) (point))
6097 (goto-char (window-start))
6098 (vertical-motion (window-height)))))
6099 (setq selective-display
6100 (and arg (prefix-numeric-value arg)))
6101 (recenter current-vpos))
6102 (set-window-start (selected-window) (window-start))
6103 (princ "selective-display set to " t)
6104 (prin1 selective-display t)
6105 (princ "." t))
6107 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
6109 (defun toggle-truncate-lines (&optional arg)
6110 "Toggle truncating of long lines for the current buffer.
6111 When truncating is off, long lines are folded.
6112 With prefix argument ARG, truncate long lines if ARG is positive,
6113 otherwise fold them. Note that in side-by-side windows, this
6114 command has no effect if `truncate-partial-width-windows' is
6115 non-nil."
6116 (interactive "P")
6117 (setq truncate-lines
6118 (if (null arg)
6119 (not truncate-lines)
6120 (> (prefix-numeric-value arg) 0)))
6121 (force-mode-line-update)
6122 (unless truncate-lines
6123 (let ((buffer (current-buffer)))
6124 (walk-windows (lambda (window)
6125 (if (eq buffer (window-buffer window))
6126 (set-window-hscroll window 0)))
6127 nil t)))
6128 (message "Truncate long lines %s"
6129 (if truncate-lines "enabled" "disabled")))
6131 (defun toggle-word-wrap (&optional arg)
6132 "Toggle whether to use word-wrapping for continuation lines.
6133 With prefix argument ARG, wrap continuation lines at word boundaries
6134 if ARG is positive, otherwise wrap them at the right screen edge.
6135 This command toggles the value of `word-wrap'. It has no effect
6136 if long lines are truncated."
6137 (interactive "P")
6138 (setq word-wrap
6139 (if (null arg)
6140 (not word-wrap)
6141 (> (prefix-numeric-value arg) 0)))
6142 (force-mode-line-update)
6143 (message "Word wrapping %s"
6144 (if word-wrap "enabled" "disabled")))
6146 (defvar overwrite-mode-textual (purecopy " Ovwrt")
6147 "The string displayed in the mode line when in overwrite mode.")
6148 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
6149 "The string displayed in the mode line when in binary overwrite mode.")
6151 (define-minor-mode overwrite-mode
6152 "Toggle Overwrite mode.
6153 With a prefix argument ARG, enable Overwrite mode if ARG is
6154 positive, and disable it otherwise. If called from Lisp, enable
6155 the mode if ARG is omitted or nil.
6157 When Overwrite mode is enabled, printing characters typed in
6158 replace existing text on a one-for-one basis, rather than pushing
6159 it to the right. At the end of a line, such characters extend
6160 the line. Before a tab, such characters insert until the tab is
6161 filled in. \\[quoted-insert] still inserts characters in
6162 overwrite mode; this is supposed to make it easier to insert
6163 characters when necessary."
6164 :variable (overwrite-mode
6165 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
6167 (define-minor-mode binary-overwrite-mode
6168 "Toggle Binary Overwrite mode.
6169 With a prefix argument ARG, enable Binary Overwrite mode if ARG
6170 is positive, and disable it otherwise. If called from Lisp,
6171 enable the mode if ARG is omitted or nil.
6173 When Binary Overwrite mode is enabled, printing characters typed
6174 in replace existing text. Newlines are not treated specially, so
6175 typing at the end of a line joins the line to the next, with the
6176 typed character between them. Typing before a tab character
6177 simply replaces the tab with the character typed.
6178 \\[quoted-insert] replaces the text at the cursor, just as
6179 ordinary typing characters do.
6181 Note that Binary Overwrite mode is not its own minor mode; it is
6182 a specialization of overwrite mode, entered by setting the
6183 `overwrite-mode' variable to `overwrite-mode-binary'."
6184 :variable (overwrite-mode
6185 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
6187 (define-minor-mode line-number-mode
6188 "Toggle line number display in the mode line (Line Number mode).
6189 With a prefix argument ARG, enable Line Number mode if ARG is
6190 positive, and disable it otherwise. If called from Lisp, enable
6191 the mode if ARG is omitted or nil.
6193 Line numbers do not appear for very large buffers and buffers
6194 with very long lines; see variables `line-number-display-limit'
6195 and `line-number-display-limit-width'."
6196 :init-value t :global t :group 'mode-line)
6198 (define-minor-mode column-number-mode
6199 "Toggle column number display in the mode line (Column Number mode).
6200 With a prefix argument ARG, enable Column Number mode if ARG is
6201 positive, and disable it otherwise.
6203 If called from Lisp, enable the mode if ARG is omitted or nil."
6204 :global t :group 'mode-line)
6206 (define-minor-mode size-indication-mode
6207 "Toggle buffer size display in the mode line (Size Indication mode).
6208 With a prefix argument ARG, enable Size Indication mode if ARG is
6209 positive, and disable it otherwise.
6211 If called from Lisp, enable the mode if ARG is omitted or nil."
6212 :global t :group 'mode-line)
6214 (define-minor-mode auto-save-mode
6215 "Toggle auto-saving in the current buffer (Auto Save mode).
6216 With a prefix argument ARG, enable Auto Save mode if ARG is
6217 positive, and disable it otherwise.
6219 If called from Lisp, enable the mode if ARG is omitted or nil."
6220 :variable ((and buffer-auto-save-file-name
6221 ;; If auto-save is off because buffer has shrunk,
6222 ;; then toggling should turn it on.
6223 (>= buffer-saved-size 0))
6224 . (lambda (val)
6225 (setq buffer-auto-save-file-name
6226 (cond
6227 ((null val) nil)
6228 ((and buffer-file-name auto-save-visited-file-name
6229 (not buffer-read-only))
6230 buffer-file-name)
6231 (t (make-auto-save-file-name))))))
6232 ;; If -1 was stored here, to temporarily turn off saving,
6233 ;; turn it back on.
6234 (and (< buffer-saved-size 0)
6235 (setq buffer-saved-size 0)))
6237 (defgroup paren-blinking nil
6238 "Blinking matching of parens and expressions."
6239 :prefix "blink-matching-"
6240 :group 'paren-matching)
6242 (defcustom blink-matching-paren t
6243 "Non-nil means show matching open-paren when close-paren is inserted."
6244 :type 'boolean
6245 :group 'paren-blinking)
6247 (defcustom blink-matching-paren-on-screen t
6248 "Non-nil means show matching open-paren when it is on screen.
6249 If nil, don't show it (but the open-paren can still be shown
6250 when it is off screen).
6252 This variable has no effect if `blink-matching-paren' is nil.
6253 \(In that case, the open-paren is never shown.)
6254 It is also ignored if `show-paren-mode' is enabled."
6255 :type 'boolean
6256 :group 'paren-blinking)
6258 (defcustom blink-matching-paren-distance (* 100 1024)
6259 "If non-nil, maximum distance to search backwards for matching open-paren.
6260 If nil, search stops at the beginning of the accessible portion of the buffer."
6261 :version "23.2" ; 25->100k
6262 :type '(choice (const nil) integer)
6263 :group 'paren-blinking)
6265 (defcustom blink-matching-delay 1
6266 "Time in seconds to delay after showing a matching paren."
6267 :type 'number
6268 :group 'paren-blinking)
6270 (defcustom blink-matching-paren-dont-ignore-comments nil
6271 "If nil, `blink-matching-paren' ignores comments.
6272 More precisely, when looking for the matching parenthesis,
6273 it skips the contents of comments that end before point."
6274 :type 'boolean
6275 :group 'paren-blinking)
6277 (defun blink-matching-check-mismatch (start end)
6278 "Return whether or not START...END are matching parens.
6279 END is the current point and START is the blink position.
6280 START might be nil if no matching starter was found.
6281 Returns non-nil if we find there is a mismatch."
6282 (let* ((end-syntax (syntax-after (1- end)))
6283 (matching-paren (and (consp end-syntax)
6284 (eq (syntax-class end-syntax) 5)
6285 (cdr end-syntax))))
6286 ;; For self-matched chars like " and $, we can't know when they're
6287 ;; mismatched or unmatched, so we can only do it for parens.
6288 (when matching-paren
6289 (not (and start
6291 (eq (char-after start) matching-paren)
6292 ;; The cdr might hold a new paren-class info rather than
6293 ;; a matching-char info, in which case the two CDRs
6294 ;; should match.
6295 (eq matching-paren (cdr-safe (syntax-after start)))))))))
6297 (defvar blink-matching-check-function #'blink-matching-check-mismatch
6298 "Function to check parentheses mismatches.
6299 The function takes two arguments (START and END) where START is the
6300 position just before the opening token and END is the position right after.
6301 START can be nil, if it was not found.
6302 The function should return non-nil if the two tokens do not match.")
6304 (defun blink-matching-open ()
6305 "Move cursor momentarily to the beginning of the sexp before point."
6306 (interactive)
6307 (when (and (not (bobp))
6308 blink-matching-paren)
6309 (let* ((oldpos (point))
6310 (message-log-max nil) ; Don't log messages about paren matching.
6311 (blinkpos
6312 (save-excursion
6313 (save-restriction
6314 (if blink-matching-paren-distance
6315 (narrow-to-region
6316 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
6317 (- (point) blink-matching-paren-distance))
6318 oldpos))
6319 (let ((parse-sexp-ignore-comments
6320 (and parse-sexp-ignore-comments
6321 (not blink-matching-paren-dont-ignore-comments))))
6322 (condition-case ()
6323 (progn
6324 (forward-sexp -1)
6325 ;; backward-sexp skips backward over prefix chars,
6326 ;; so move back to the matching paren.
6327 (while (and (< (point) (1- oldpos))
6328 (let ((code (syntax-after (point))))
6329 (or (eq (syntax-class code) 6)
6330 (eq (logand 1048576 (car code))
6331 1048576))))
6332 (forward-char 1))
6333 (point))
6334 (error nil))))))
6335 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
6336 (cond
6337 (mismatch
6338 (if blinkpos
6339 (if (minibufferp)
6340 (minibuffer-message "Mismatched parentheses")
6341 (message "Mismatched parentheses"))
6342 (if (minibufferp)
6343 (minibuffer-message "No matching parenthesis found")
6344 (message "No matching parenthesis found"))))
6345 ((not blinkpos) nil)
6346 ((pos-visible-in-window-p blinkpos)
6347 ;; Matching open within window, temporarily move to blinkpos but only
6348 ;; if `blink-matching-paren-on-screen' is non-nil.
6349 (and blink-matching-paren-on-screen
6350 (not show-paren-mode)
6351 (save-excursion
6352 (goto-char blinkpos)
6353 (sit-for blink-matching-delay))))
6355 (save-excursion
6356 (goto-char blinkpos)
6357 (let ((open-paren-line-string
6358 ;; Show what precedes the open in its line, if anything.
6359 (cond
6360 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
6361 (buffer-substring (line-beginning-position)
6362 (1+ blinkpos)))
6363 ;; Show what follows the open in its line, if anything.
6364 ((save-excursion
6365 (forward-char 1)
6366 (skip-chars-forward " \t")
6367 (not (eolp)))
6368 (buffer-substring blinkpos
6369 (line-end-position)))
6370 ;; Otherwise show the previous nonblank line,
6371 ;; if there is one.
6372 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
6373 (concat
6374 (buffer-substring (progn
6375 (skip-chars-backward "\n \t")
6376 (line-beginning-position))
6377 (progn (end-of-line)
6378 (skip-chars-backward " \t")
6379 (point)))
6380 ;; Replace the newline and other whitespace with `...'.
6381 "..."
6382 (buffer-substring blinkpos (1+ blinkpos))))
6383 ;; There is nothing to show except the char itself.
6384 (t (buffer-substring blinkpos (1+ blinkpos))))))
6385 (message "Matches %s"
6386 (substring-no-properties open-paren-line-string)))))))))
6388 (defvar blink-paren-function 'blink-matching-open
6389 "Function called, if non-nil, whenever a close parenthesis is inserted.
6390 More precisely, a char with closeparen syntax is self-inserted.")
6392 (defun blink-paren-post-self-insert-function ()
6393 (when (and (eq (char-before) last-command-event) ; Sanity check.
6394 (memq (char-syntax last-command-event) '(?\) ?\$))
6395 blink-paren-function
6396 (not executing-kbd-macro)
6397 (not noninteractive)
6398 ;; Verify an even number of quoting characters precede the close.
6399 (= 1 (logand 1 (- (point)
6400 (save-excursion
6401 (forward-char -1)
6402 (skip-syntax-backward "/\\")
6403 (point))))))
6404 (funcall blink-paren-function)))
6406 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
6407 ;; Most likely, this hook is nil, so this arg doesn't matter,
6408 ;; but I use it as a reminder that this function usually
6409 ;; likes to be run after others since it does `sit-for'.
6410 'append)
6412 ;; This executes C-g typed while Emacs is waiting for a command.
6413 ;; Quitting out of a program does not go through here;
6414 ;; that happens in the QUIT macro at the C code level.
6415 (defun keyboard-quit ()
6416 "Signal a `quit' condition.
6417 During execution of Lisp code, this character causes a quit directly.
6418 At top-level, as an editor command, this simply beeps."
6419 (interactive)
6420 ;; Avoid adding the region to the window selection.
6421 (setq saved-region-selection nil)
6422 (let (select-active-regions)
6423 (deactivate-mark))
6424 (if (fboundp 'kmacro-keyboard-quit)
6425 (kmacro-keyboard-quit))
6426 (setq defining-kbd-macro nil)
6427 (let ((debug-on-quit nil))
6428 (signal 'quit nil)))
6430 (defvar buffer-quit-function nil
6431 "Function to call to \"quit\" the current buffer, or nil if none.
6432 \\[keyboard-escape-quit] calls this function when its more local actions
6433 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
6435 (defun keyboard-escape-quit ()
6436 "Exit the current \"mode\" (in a generalized sense of the word).
6437 This command can exit an interactive command such as `query-replace',
6438 can clear out a prefix argument or a region,
6439 can get out of the minibuffer or other recursive edit,
6440 cancel the use of the current buffer (for special-purpose buffers),
6441 or go back to just one window (by deleting all but the selected window)."
6442 (interactive)
6443 (cond ((eq last-command 'mode-exited) nil)
6444 ((region-active-p)
6445 (deactivate-mark))
6446 ((> (minibuffer-depth) 0)
6447 (abort-recursive-edit))
6448 (current-prefix-arg
6449 nil)
6450 ((> (recursion-depth) 0)
6451 (exit-recursive-edit))
6452 (buffer-quit-function
6453 (funcall buffer-quit-function))
6454 ((not (one-window-p t))
6455 (delete-other-windows))
6456 ((string-match "^ \\*" (buffer-name (current-buffer)))
6457 (bury-buffer))))
6459 (defun play-sound-file (file &optional volume device)
6460 "Play sound stored in FILE.
6461 VOLUME and DEVICE correspond to the keywords of the sound
6462 specification for `play-sound'."
6463 (interactive "fPlay sound file: ")
6464 (let ((sound (list :file file)))
6465 (if volume
6466 (plist-put sound :volume volume))
6467 (if device
6468 (plist-put sound :device device))
6469 (push 'sound sound)
6470 (play-sound sound)))
6473 (defcustom read-mail-command 'rmail
6474 "Your preference for a mail reading package.
6475 This is used by some keybindings which support reading mail.
6476 See also `mail-user-agent' concerning sending mail."
6477 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
6478 (function-item :tag "Gnus" :format "%t\n" gnus)
6479 (function-item :tag "Emacs interface to MH"
6480 :format "%t\n" mh-rmail)
6481 (function :tag "Other"))
6482 :version "21.1"
6483 :group 'mail)
6485 (defcustom mail-user-agent 'message-user-agent
6486 "Your preference for a mail composition package.
6487 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
6488 outgoing email message. This variable lets you specify which
6489 mail-sending package you prefer.
6491 Valid values include:
6493 `message-user-agent' -- use the Message package.
6494 See Info node `(message)'.
6495 `sendmail-user-agent' -- use the Mail package.
6496 See Info node `(emacs)Sending Mail'.
6497 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
6498 See Info node `(mh-e)'.
6499 `gnus-user-agent' -- like `message-user-agent', but with Gnus
6500 paraphernalia if Gnus is running, particularly
6501 the Gcc: header for archiving.
6503 Additional valid symbols may be available; check with the author of
6504 your package for details. The function should return non-nil if it
6505 succeeds.
6507 See also `read-mail-command' concerning reading mail."
6508 :type '(radio (function-item :tag "Message package"
6509 :format "%t\n"
6510 message-user-agent)
6511 (function-item :tag "Mail package"
6512 :format "%t\n"
6513 sendmail-user-agent)
6514 (function-item :tag "Emacs interface to MH"
6515 :format "%t\n"
6516 mh-e-user-agent)
6517 (function-item :tag "Message with full Gnus features"
6518 :format "%t\n"
6519 gnus-user-agent)
6520 (function :tag "Other"))
6521 :version "23.2" ; sendmail->message
6522 :group 'mail)
6524 (defcustom compose-mail-user-agent-warnings t
6525 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
6526 If the value of `mail-user-agent' is the default, and the user
6527 appears to have customizations applying to the old default,
6528 `compose-mail' issues a warning."
6529 :type 'boolean
6530 :version "23.2"
6531 :group 'mail)
6533 (defun rfc822-goto-eoh ()
6534 "If the buffer starts with a mail header, move point to the header's end.
6535 Otherwise, moves to `point-min'.
6536 The end of the header is the start of the next line, if there is one,
6537 else the end of the last line. This function obeys RFC822."
6538 (goto-char (point-min))
6539 (when (re-search-forward
6540 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
6541 (goto-char (match-beginning 0))))
6543 ;; Used by Rmail (e.g., rmail-forward).
6544 (defvar mail-encode-mml nil
6545 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
6546 the outgoing message before sending it.")
6548 (defun compose-mail (&optional to subject other-headers continue
6549 switch-function yank-action send-actions
6550 return-action)
6551 "Start composing a mail message to send.
6552 This uses the user's chosen mail composition package
6553 as selected with the variable `mail-user-agent'.
6554 The optional arguments TO and SUBJECT specify recipients
6555 and the initial Subject field, respectively.
6557 OTHER-HEADERS is an alist specifying additional
6558 header fields. Elements look like (HEADER . VALUE) where both
6559 HEADER and VALUE are strings.
6561 CONTINUE, if non-nil, says to continue editing a message already
6562 being composed. Interactively, CONTINUE is the prefix argument.
6564 SWITCH-FUNCTION, if non-nil, is a function to use to
6565 switch to and display the buffer used for mail composition.
6567 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
6568 to insert the raw text of the message being replied to.
6569 It has the form (FUNCTION . ARGS). The user agent will apply
6570 FUNCTION to ARGS, to insert the raw text of the original message.
6571 \(The user agent will also run `mail-citation-hook', *after* the
6572 original text has been inserted in this way.)
6574 SEND-ACTIONS is a list of actions to call when the message is sent.
6575 Each action has the form (FUNCTION . ARGS).
6577 RETURN-ACTION, if non-nil, is an action for returning to the
6578 caller. It has the form (FUNCTION . ARGS). The function is
6579 called after the mail has been sent or put aside, and the mail
6580 buffer buried."
6581 (interactive
6582 (list nil nil nil current-prefix-arg))
6584 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
6585 ;; from sendmail-user-agent to message-user-agent. Some users may
6586 ;; encounter incompatibilities. This hack tries to detect problems
6587 ;; and warn about them.
6588 (and compose-mail-user-agent-warnings
6589 (eq mail-user-agent 'message-user-agent)
6590 (let (warn-vars)
6591 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
6592 mail-yank-hooks mail-archive-file-name
6593 mail-default-reply-to mail-mailing-lists
6594 mail-self-blind))
6595 (and (boundp var)
6596 (symbol-value var)
6597 (push var warn-vars)))
6598 (when warn-vars
6599 (display-warning 'mail
6600 (format "\
6601 The default mail mode is now Message mode.
6602 You have the following Mail mode variable%s customized:
6603 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
6604 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
6605 (if (> (length warn-vars) 1) "s" "")
6606 (mapconcat 'symbol-name
6607 warn-vars " "))))))
6609 (let ((function (get mail-user-agent 'composefunc)))
6610 (funcall function to subject other-headers continue switch-function
6611 yank-action send-actions return-action)))
6613 (defun compose-mail-other-window (&optional to subject other-headers continue
6614 yank-action send-actions
6615 return-action)
6616 "Like \\[compose-mail], but edit the outgoing message in another window."
6617 (interactive (list nil nil nil current-prefix-arg))
6618 (compose-mail to subject other-headers continue
6619 'switch-to-buffer-other-window yank-action send-actions
6620 return-action))
6622 (defun compose-mail-other-frame (&optional to subject other-headers continue
6623 yank-action send-actions
6624 return-action)
6625 "Like \\[compose-mail], but edit the outgoing message in another frame."
6626 (interactive (list nil nil nil current-prefix-arg))
6627 (compose-mail to subject other-headers continue
6628 'switch-to-buffer-other-frame yank-action send-actions
6629 return-action))
6632 (defvar set-variable-value-history nil
6633 "History of values entered with `set-variable'.
6635 Maximum length of the history list is determined by the value
6636 of `history-length', which see.")
6638 (defun set-variable (variable value &optional make-local)
6639 "Set VARIABLE to VALUE. VALUE is a Lisp object.
6640 VARIABLE should be a user option variable name, a Lisp variable
6641 meant to be customized by users. You should enter VALUE in Lisp syntax,
6642 so if you want VALUE to be a string, you must surround it with doublequotes.
6643 VALUE is used literally, not evaluated.
6645 If VARIABLE has a `variable-interactive' property, that is used as if
6646 it were the arg to `interactive' (which see) to interactively read VALUE.
6648 If VARIABLE has been defined with `defcustom', then the type information
6649 in the definition is used to check that VALUE is valid.
6651 With a prefix argument, set VARIABLE to VALUE buffer-locally."
6652 (interactive
6653 (let* ((default-var (variable-at-point))
6654 (var (if (custom-variable-p default-var)
6655 (read-variable (format "Set variable (default %s): " default-var)
6656 default-var)
6657 (read-variable "Set variable: ")))
6658 (minibuffer-help-form '(describe-variable var))
6659 (prop (get var 'variable-interactive))
6660 (obsolete (car (get var 'byte-obsolete-variable)))
6661 (prompt (format "Set %s %s to value: " var
6662 (cond ((local-variable-p var)
6663 "(buffer-local)")
6664 ((or current-prefix-arg
6665 (local-variable-if-set-p var))
6666 "buffer-locally")
6667 (t "globally"))))
6668 (val (progn
6669 (when obsolete
6670 (message (concat "`%S' is obsolete; "
6671 (if (symbolp obsolete) "use `%S' instead" "%s"))
6672 var obsolete)
6673 (sit-for 3))
6674 (if prop
6675 ;; Use VAR's `variable-interactive' property
6676 ;; as an interactive spec for prompting.
6677 (call-interactively `(lambda (arg)
6678 (interactive ,prop)
6679 arg))
6680 (read-from-minibuffer prompt nil
6681 read-expression-map t
6682 'set-variable-value-history
6683 (format "%S" (symbol-value var)))))))
6684 (list var val current-prefix-arg)))
6686 (and (custom-variable-p variable)
6687 (not (get variable 'custom-type))
6688 (custom-load-symbol variable))
6689 (let ((type (get variable 'custom-type)))
6690 (when type
6691 ;; Match with custom type.
6692 (require 'cus-edit)
6693 (setq type (widget-convert type))
6694 (unless (widget-apply type :match value)
6695 (error "Value `%S' does not match type %S of %S"
6696 value (car type) variable))))
6698 (if make-local
6699 (make-local-variable variable))
6701 (set variable value)
6703 ;; Force a thorough redisplay for the case that the variable
6704 ;; has an effect on the display, like `tab-width' has.
6705 (force-mode-line-update))
6707 ;; Define the major mode for lists of completions.
6709 (defvar completion-list-mode-map
6710 (let ((map (make-sparse-keymap)))
6711 (define-key map [mouse-2] 'mouse-choose-completion)
6712 (define-key map [follow-link] 'mouse-face)
6713 (define-key map [down-mouse-2] nil)
6714 (define-key map "\C-m" 'choose-completion)
6715 (define-key map "\e\e\e" 'delete-completion-window)
6716 (define-key map [left] 'previous-completion)
6717 (define-key map [right] 'next-completion)
6718 (define-key map "q" 'quit-window)
6719 (define-key map "z" 'kill-this-buffer)
6720 map)
6721 "Local map for completion list buffers.")
6723 ;; Completion mode is suitable only for specially formatted data.
6724 (put 'completion-list-mode 'mode-class 'special)
6726 (defvar completion-reference-buffer nil
6727 "Record the buffer that was current when the completion list was requested.
6728 This is a local variable in the completion list buffer.
6729 Initial value is nil to avoid some compiler warnings.")
6731 (defvar completion-no-auto-exit nil
6732 "Non-nil means `choose-completion-string' should never exit the minibuffer.
6733 This also applies to other functions such as `choose-completion'.")
6735 (defvar completion-base-position nil
6736 "Position of the base of the text corresponding to the shown completions.
6737 This variable is used in the *Completions* buffers.
6738 Its value is a list of the form (START END) where START is the place
6739 where the completion should be inserted and END (if non-nil) is the end
6740 of the text to replace. If END is nil, point is used instead.")
6742 (defvar completion-list-insert-choice-function #'completion--replace
6743 "Function to use to insert the text chosen in *Completions*.
6744 Called with three arguments (BEG END TEXT), it should replace the text
6745 between BEG and END with TEXT. Expected to be set buffer-locally
6746 in the *Completions* buffer.")
6748 (defvar completion-base-size nil
6749 "Number of chars before point not involved in completion.
6750 This is a local variable in the completion list buffer.
6751 It refers to the chars in the minibuffer if completing in the
6752 minibuffer, or in `completion-reference-buffer' otherwise.
6753 Only characters in the field at point are included.
6755 If nil, Emacs determines which part of the tail end of the
6756 buffer's text is involved in completion by comparing the text
6757 directly.")
6758 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
6760 (defun delete-completion-window ()
6761 "Delete the completion list window.
6762 Go to the window from which completion was requested."
6763 (interactive)
6764 (let ((buf completion-reference-buffer))
6765 (if (one-window-p t)
6766 (if (window-dedicated-p) (delete-frame))
6767 (delete-window (selected-window))
6768 (if (get-buffer-window buf)
6769 (select-window (get-buffer-window buf))))))
6771 (defun previous-completion (n)
6772 "Move to the previous item in the completion list."
6773 (interactive "p")
6774 (next-completion (- n)))
6776 (defun next-completion (n)
6777 "Move to the next item in the completion list.
6778 With prefix argument N, move N items (negative N means move backward)."
6779 (interactive "p")
6780 (let ((beg (point-min)) (end (point-max)))
6781 (while (and (> n 0) (not (eobp)))
6782 ;; If in a completion, move to the end of it.
6783 (when (get-text-property (point) 'mouse-face)
6784 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6785 ;; Move to start of next one.
6786 (unless (get-text-property (point) 'mouse-face)
6787 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6788 (setq n (1- n)))
6789 (while (and (< n 0) (not (bobp)))
6790 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
6791 ;; If in a completion, move to the start of it.
6792 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
6793 (goto-char (previous-single-property-change
6794 (point) 'mouse-face nil beg)))
6795 ;; Move to end of the previous completion.
6796 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
6797 (goto-char (previous-single-property-change
6798 (point) 'mouse-face nil beg)))
6799 ;; Move to the start of that one.
6800 (goto-char (previous-single-property-change
6801 (point) 'mouse-face nil beg))
6802 (setq n (1+ n))))))
6804 (defun choose-completion (&optional event)
6805 "Choose the completion at point."
6806 (interactive (list last-nonmenu-event))
6807 ;; In case this is run via the mouse, give temporary modes such as
6808 ;; isearch a chance to turn off.
6809 (run-hooks 'mouse-leave-buffer-hook)
6810 (with-current-buffer (window-buffer (posn-window (event-start event)))
6811 (let ((buffer completion-reference-buffer)
6812 (base-size completion-base-size)
6813 (base-position completion-base-position)
6814 (insert-function completion-list-insert-choice-function)
6815 (choice
6816 (save-excursion
6817 (goto-char (posn-point (event-start event)))
6818 (let (beg end)
6819 (cond
6820 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
6821 (setq end (point) beg (1+ (point))))
6822 ((and (not (bobp))
6823 (get-text-property (1- (point)) 'mouse-face))
6824 (setq end (1- (point)) beg (point)))
6825 (t (error "No completion here")))
6826 (setq beg (previous-single-property-change beg 'mouse-face))
6827 (setq end (or (next-single-property-change end 'mouse-face)
6828 (point-max)))
6829 (buffer-substring-no-properties beg end)))))
6831 (unless (buffer-live-p buffer)
6832 (error "Destination buffer is dead"))
6833 (quit-window nil (posn-window (event-start event)))
6835 (with-current-buffer buffer
6836 (choose-completion-string
6837 choice buffer
6838 (or base-position
6839 (when base-size
6840 ;; Someone's using old completion code that doesn't know
6841 ;; about base-position yet.
6842 (list (+ base-size (field-beginning))))
6843 ;; If all else fails, just guess.
6844 (list (choose-completion-guess-base-position choice)))
6845 insert-function)))))
6847 ;; Delete the longest partial match for STRING
6848 ;; that can be found before POINT.
6849 (defun choose-completion-guess-base-position (string)
6850 (save-excursion
6851 (let ((opoint (point))
6852 len)
6853 ;; Try moving back by the length of the string.
6854 (goto-char (max (- (point) (length string))
6855 (minibuffer-prompt-end)))
6856 ;; See how far back we were actually able to move. That is the
6857 ;; upper bound on how much we can match and delete.
6858 (setq len (- opoint (point)))
6859 (if completion-ignore-case
6860 (setq string (downcase string)))
6861 (while (and (> len 0)
6862 (let ((tail (buffer-substring (point) opoint)))
6863 (if completion-ignore-case
6864 (setq tail (downcase tail)))
6865 (not (string= tail (substring string 0 len)))))
6866 (setq len (1- len))
6867 (forward-char 1))
6868 (point))))
6870 (defun choose-completion-delete-max-match (string)
6871 (declare (obsolete choose-completion-guess-base-position "23.2"))
6872 (delete-region (choose-completion-guess-base-position string) (point)))
6874 (defvar choose-completion-string-functions nil
6875 "Functions that may override the normal insertion of a completion choice.
6876 These functions are called in order with four arguments:
6877 CHOICE - the string to insert in the buffer,
6878 BUFFER - the buffer in which the choice should be inserted,
6879 MINI-P - non-nil if BUFFER is a minibuffer, and
6880 BASE-SIZE - the number of characters in BUFFER before
6881 the string being completed.
6883 If a function in the list returns non-nil, that function is supposed
6884 to have inserted the CHOICE in the BUFFER, and possibly exited
6885 the minibuffer; no further functions will be called.
6887 If all functions in the list return nil, that means to use
6888 the default method of inserting the completion in BUFFER.")
6890 (defun choose-completion-string (choice &optional
6891 buffer base-position insert-function)
6892 "Switch to BUFFER and insert the completion choice CHOICE.
6893 BASE-POSITION says where to insert the completion.
6894 INSERT-FUNCTION says how to insert the completion and falls
6895 back on `completion-list-insert-choice-function' when nil."
6897 ;; If BUFFER is the minibuffer, exit the minibuffer
6898 ;; unless it is reading a file name and CHOICE is a directory,
6899 ;; or completion-no-auto-exit is non-nil.
6901 ;; Some older code may call us passing `base-size' instead of
6902 ;; `base-position'. It's difficult to make any use of `base-size',
6903 ;; so we just ignore it.
6904 (unless (consp base-position)
6905 (message "Obsolete `base-size' passed to choose-completion-string")
6906 (setq base-position nil))
6908 (let* ((buffer (or buffer completion-reference-buffer))
6909 (mini-p (minibufferp buffer)))
6910 ;; If BUFFER is a minibuffer, barf unless it's the currently
6911 ;; active minibuffer.
6912 (if (and mini-p
6913 (not (and (active-minibuffer-window)
6914 (equal buffer
6915 (window-buffer (active-minibuffer-window))))))
6916 (error "Minibuffer is not active for completion")
6917 ;; Set buffer so buffer-local choose-completion-string-functions works.
6918 (set-buffer buffer)
6919 (unless (run-hook-with-args-until-success
6920 'choose-completion-string-functions
6921 ;; The fourth arg used to be `mini-p' but was useless
6922 ;; (since minibufferp can be used on the `buffer' arg)
6923 ;; and indeed unused. The last used to be `base-size', so we
6924 ;; keep it to try and avoid breaking old code.
6925 choice buffer base-position nil)
6926 ;; This remove-text-properties should be unnecessary since `choice'
6927 ;; comes from buffer-substring-no-properties.
6928 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
6929 ;; Insert the completion into the buffer where it was requested.
6930 (funcall (or insert-function completion-list-insert-choice-function)
6931 (or (car base-position) (point))
6932 (or (cadr base-position) (point))
6933 choice)
6934 ;; Update point in the window that BUFFER is showing in.
6935 (let ((window (get-buffer-window buffer t)))
6936 (set-window-point window (point)))
6937 ;; If completing for the minibuffer, exit it with this choice.
6938 (and (not completion-no-auto-exit)
6939 (minibufferp buffer)
6940 minibuffer-completion-table
6941 ;; If this is reading a file name, and the file name chosen
6942 ;; is a directory, don't exit the minibuffer.
6943 (let* ((result (buffer-substring (field-beginning) (point)))
6944 (bounds
6945 (completion-boundaries result minibuffer-completion-table
6946 minibuffer-completion-predicate
6947 "")))
6948 (if (eq (car bounds) (length result))
6949 ;; The completion chosen leads to a new set of completions
6950 ;; (e.g. it's a directory): don't exit the minibuffer yet.
6951 (let ((mini (active-minibuffer-window)))
6952 (select-window mini)
6953 (when minibuffer-auto-raise
6954 (raise-frame (window-frame mini))))
6955 (exit-minibuffer))))))))
6957 (define-derived-mode completion-list-mode nil "Completion List"
6958 "Major mode for buffers showing lists of possible completions.
6959 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
6960 to select the completion near point.
6961 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
6962 with the mouse.
6964 \\{completion-list-mode-map}"
6965 (set (make-local-variable 'completion-base-size) nil))
6967 (defun completion-list-mode-finish ()
6968 "Finish setup of the completions buffer.
6969 Called from `temp-buffer-show-hook'."
6970 (when (eq major-mode 'completion-list-mode)
6971 (setq buffer-read-only t)))
6973 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
6976 ;; Variables and faces used in `completion-setup-function'.
6978 (defcustom completion-show-help t
6979 "Non-nil means show help message in *Completions* buffer."
6980 :type 'boolean
6981 :version "22.1"
6982 :group 'completion)
6984 ;; This function goes in completion-setup-hook, so that it is called
6985 ;; after the text of the completion list buffer is written.
6986 (defun completion-setup-function ()
6987 (let* ((mainbuf (current-buffer))
6988 (base-dir
6989 ;; FIXME: This is a bad hack. We try to set the default-directory
6990 ;; in the *Completions* buffer so that the relative file names
6991 ;; displayed there can be treated as valid file names, independently
6992 ;; from the completion context. But this suffers from many problems:
6993 ;; - It's not clear when the completions are file names. With some
6994 ;; completion tables (e.g. bzr revision specs), the listed
6995 ;; completions can mix file names and other things.
6996 ;; - It doesn't pay attention to possible quoting.
6997 ;; - With fancy completion styles, the code below will not always
6998 ;; find the right base directory.
6999 (if minibuffer-completing-file-name
7000 (file-name-as-directory
7001 (expand-file-name
7002 (buffer-substring (minibuffer-prompt-end)
7003 (- (point) (or completion-base-size 0))))))))
7004 (with-current-buffer standard-output
7005 (let ((base-size completion-base-size) ;Read before killing localvars.
7006 (base-position completion-base-position)
7007 (insert-fun completion-list-insert-choice-function))
7008 (completion-list-mode)
7009 (set (make-local-variable 'completion-base-size) base-size)
7010 (set (make-local-variable 'completion-base-position) base-position)
7011 (set (make-local-variable 'completion-list-insert-choice-function)
7012 insert-fun))
7013 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7014 (if base-dir (setq default-directory base-dir))
7015 ;; Maybe insert help string.
7016 (when completion-show-help
7017 (goto-char (point-min))
7018 (if (display-mouse-p)
7019 (insert (substitute-command-keys
7020 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
7021 (insert (substitute-command-keys
7022 "In this buffer, type \\[choose-completion] to \
7023 select the completion near point.\n\n"))))))
7025 (add-hook 'completion-setup-hook 'completion-setup-function)
7027 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7028 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7030 (defun switch-to-completions ()
7031 "Select the completion list window."
7032 (interactive)
7033 (let ((window (or (get-buffer-window "*Completions*" 0)
7034 ;; Make sure we have a completions window.
7035 (progn (minibuffer-completion-help)
7036 (get-buffer-window "*Completions*" 0)))))
7037 (when window
7038 (select-window window)
7039 ;; In the new buffer, go to the first completion.
7040 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
7041 (when (bobp)
7042 (next-completion 1)))))
7044 ;;; Support keyboard commands to turn on various modifiers.
7046 ;; These functions -- which are not commands -- each add one modifier
7047 ;; to the following event.
7049 (defun event-apply-alt-modifier (_ignore-prompt)
7050 "\\<function-key-map>Add the Alt modifier to the following event.
7051 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
7052 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
7053 (defun event-apply-super-modifier (_ignore-prompt)
7054 "\\<function-key-map>Add the Super modifier to the following event.
7055 For example, type \\[event-apply-super-modifier] & to enter Super-&."
7056 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
7057 (defun event-apply-hyper-modifier (_ignore-prompt)
7058 "\\<function-key-map>Add the Hyper modifier to the following event.
7059 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
7060 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
7061 (defun event-apply-shift-modifier (_ignore-prompt)
7062 "\\<function-key-map>Add the Shift modifier to the following event.
7063 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
7064 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
7065 (defun event-apply-control-modifier (_ignore-prompt)
7066 "\\<function-key-map>Add the Ctrl modifier to the following event.
7067 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
7068 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
7069 (defun event-apply-meta-modifier (_ignore-prompt)
7070 "\\<function-key-map>Add the Meta modifier to the following event.
7071 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
7072 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
7074 (defun event-apply-modifier (event symbol lshiftby prefix)
7075 "Apply a modifier flag to event EVENT.
7076 SYMBOL is the name of this modifier, as a symbol.
7077 LSHIFTBY is the numeric value of this modifier, in keyboard events.
7078 PREFIX is the string that represents this modifier in an event type symbol."
7079 (if (numberp event)
7080 (cond ((eq symbol 'control)
7081 (if (and (<= (downcase event) ?z)
7082 (>= (downcase event) ?a))
7083 (- (downcase event) ?a -1)
7084 (if (and (<= (downcase event) ?Z)
7085 (>= (downcase event) ?A))
7086 (- (downcase event) ?A -1)
7087 (logior (lsh 1 lshiftby) event))))
7088 ((eq symbol 'shift)
7089 (if (and (<= (downcase event) ?z)
7090 (>= (downcase event) ?a))
7091 (upcase event)
7092 (logior (lsh 1 lshiftby) event)))
7094 (logior (lsh 1 lshiftby) event)))
7095 (if (memq symbol (event-modifiers event))
7096 event
7097 (let ((event-type (if (symbolp event) event (car event))))
7098 (setq event-type (intern (concat prefix (symbol-name event-type))))
7099 (if (symbolp event)
7100 event-type
7101 (cons event-type (cdr event)))))))
7103 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
7104 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
7105 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
7106 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
7107 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
7108 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
7110 ;;;; Keypad support.
7112 ;; Make the keypad keys act like ordinary typing keys. If people add
7113 ;; bindings for the function key symbols, then those bindings will
7114 ;; override these, so this shouldn't interfere with any existing
7115 ;; bindings.
7117 ;; Also tell read-char how to handle these keys.
7118 (mapc
7119 (lambda (keypad-normal)
7120 (let ((keypad (nth 0 keypad-normal))
7121 (normal (nth 1 keypad-normal)))
7122 (put keypad 'ascii-character normal)
7123 (define-key function-key-map (vector keypad) (vector normal))))
7124 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
7125 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
7126 (kp-space ?\s)
7127 (kp-tab ?\t)
7128 (kp-enter ?\r)
7129 (kp-multiply ?*)
7130 (kp-add ?+)
7131 (kp-separator ?,)
7132 (kp-subtract ?-)
7133 (kp-decimal ?.)
7134 (kp-divide ?/)
7135 (kp-equal ?=)
7136 ;; Do the same for various keys that are represented as symbols under
7137 ;; GUIs but naturally correspond to characters.
7138 (backspace 127)
7139 (delete 127)
7140 (tab ?\t)
7141 (linefeed ?\n)
7142 (clear ?\C-l)
7143 (return ?\C-m)
7144 (escape ?\e)
7147 ;;;;
7148 ;;;; forking a twin copy of a buffer.
7149 ;;;;
7151 (defvar clone-buffer-hook nil
7152 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
7154 (defvar clone-indirect-buffer-hook nil
7155 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
7157 (defun clone-process (process &optional newname)
7158 "Create a twin copy of PROCESS.
7159 If NEWNAME is nil, it defaults to PROCESS' name;
7160 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
7161 If PROCESS is associated with a buffer, the new process will be associated
7162 with the current buffer instead.
7163 Returns nil if PROCESS has already terminated."
7164 (setq newname (or newname (process-name process)))
7165 (if (string-match "<[0-9]+>\\'" newname)
7166 (setq newname (substring newname 0 (match-beginning 0))))
7167 (when (memq (process-status process) '(run stop open))
7168 (let* ((process-connection-type (process-tty-name process))
7169 (new-process
7170 (if (memq (process-status process) '(open))
7171 (let ((args (process-contact process t)))
7172 (setq args (plist-put args :name newname))
7173 (setq args (plist-put args :buffer
7174 (if (process-buffer process)
7175 (current-buffer))))
7176 (apply 'make-network-process args))
7177 (apply 'start-process newname
7178 (if (process-buffer process) (current-buffer))
7179 (process-command process)))))
7180 (set-process-query-on-exit-flag
7181 new-process (process-query-on-exit-flag process))
7182 (set-process-inherit-coding-system-flag
7183 new-process (process-inherit-coding-system-flag process))
7184 (set-process-filter new-process (process-filter process))
7185 (set-process-sentinel new-process (process-sentinel process))
7186 (set-process-plist new-process (copy-sequence (process-plist process)))
7187 new-process)))
7189 ;; things to maybe add (currently partly covered by `funcall mode'):
7190 ;; - syntax-table
7191 ;; - overlays
7192 (defun clone-buffer (&optional newname display-flag)
7193 "Create and return a twin copy of the current buffer.
7194 Unlike an indirect buffer, the new buffer can be edited
7195 independently of the old one (if it is not read-only).
7196 NEWNAME is the name of the new buffer. It may be modified by
7197 adding or incrementing <N> at the end as necessary to create a
7198 unique buffer name. If nil, it defaults to the name of the
7199 current buffer, with the proper suffix. If DISPLAY-FLAG is
7200 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
7201 clone a file-visiting buffer, or a buffer whose major mode symbol
7202 has a non-nil `no-clone' property, results in an error.
7204 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
7205 current buffer with appropriate suffix. However, if a prefix
7206 argument is given, then the command prompts for NEWNAME in the
7207 minibuffer.
7209 This runs the normal hook `clone-buffer-hook' in the new buffer
7210 after it has been set up properly in other respects."
7211 (interactive
7212 (progn
7213 (if buffer-file-name
7214 (error "Cannot clone a file-visiting buffer"))
7215 (if (get major-mode 'no-clone)
7216 (error "Cannot clone a buffer in %s mode" mode-name))
7217 (list (if current-prefix-arg
7218 (read-buffer "Name of new cloned buffer: " (current-buffer)))
7219 t)))
7220 (if buffer-file-name
7221 (error "Cannot clone a file-visiting buffer"))
7222 (if (get major-mode 'no-clone)
7223 (error "Cannot clone a buffer in %s mode" mode-name))
7224 (setq newname (or newname (buffer-name)))
7225 (if (string-match "<[0-9]+>\\'" newname)
7226 (setq newname (substring newname 0 (match-beginning 0))))
7227 (let ((buf (current-buffer))
7228 (ptmin (point-min))
7229 (ptmax (point-max))
7230 (pt (point))
7231 (mk (if mark-active (mark t)))
7232 (modified (buffer-modified-p))
7233 (mode major-mode)
7234 (lvars (buffer-local-variables))
7235 (process (get-buffer-process (current-buffer)))
7236 (new (generate-new-buffer (or newname (buffer-name)))))
7237 (save-restriction
7238 (widen)
7239 (with-current-buffer new
7240 (insert-buffer-substring buf)))
7241 (with-current-buffer new
7242 (narrow-to-region ptmin ptmax)
7243 (goto-char pt)
7244 (if mk (set-mark mk))
7245 (set-buffer-modified-p modified)
7247 ;; Clone the old buffer's process, if any.
7248 (when process (clone-process process))
7250 ;; Now set up the major mode.
7251 (funcall mode)
7253 ;; Set up other local variables.
7254 (mapc (lambda (v)
7255 (condition-case () ;in case var is read-only
7256 (if (symbolp v)
7257 (makunbound v)
7258 (set (make-local-variable (car v)) (cdr v)))
7259 (error nil)))
7260 lvars)
7262 ;; Run any hooks (typically set up by the major mode
7263 ;; for cloning to work properly).
7264 (run-hooks 'clone-buffer-hook))
7265 (if display-flag
7266 ;; Presumably the current buffer is shown in the selected frame, so
7267 ;; we want to display the clone elsewhere.
7268 (let ((same-window-regexps nil)
7269 (same-window-buffer-names))
7270 (pop-to-buffer new)))
7271 new))
7274 (defun clone-indirect-buffer (newname display-flag &optional norecord)
7275 "Create an indirect buffer that is a twin copy of the current buffer.
7277 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
7278 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
7279 or if not called with a prefix arg, NEWNAME defaults to the current
7280 buffer's name. The name is modified by adding a `<N>' suffix to it
7281 or by incrementing the N in an existing suffix. Trying to clone a
7282 buffer whose major mode symbol has a non-nil `no-clone-indirect'
7283 property results in an error.
7285 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7286 This is always done when called interactively.
7288 Optional third arg NORECORD non-nil means do not put this buffer at the
7289 front of the list of recently selected ones."
7290 (interactive
7291 (progn
7292 (if (get major-mode 'no-clone-indirect)
7293 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7294 (list (if current-prefix-arg
7295 (read-buffer "Name of indirect buffer: " (current-buffer)))
7296 t)))
7297 (if (get major-mode 'no-clone-indirect)
7298 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7299 (setq newname (or newname (buffer-name)))
7300 (if (string-match "<[0-9]+>\\'" newname)
7301 (setq newname (substring newname 0 (match-beginning 0))))
7302 (let* ((name (generate-new-buffer-name newname))
7303 (buffer (make-indirect-buffer (current-buffer) name t)))
7304 (with-current-buffer buffer
7305 (run-hooks 'clone-indirect-buffer-hook))
7306 (when display-flag
7307 (pop-to-buffer buffer norecord))
7308 buffer))
7311 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
7312 "Like `clone-indirect-buffer' but display in another window."
7313 (interactive
7314 (progn
7315 (if (get major-mode 'no-clone-indirect)
7316 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7317 (list (if current-prefix-arg
7318 (read-buffer "Name of indirect buffer: " (current-buffer)))
7319 t)))
7320 (let ((pop-up-windows t))
7321 (clone-indirect-buffer newname display-flag norecord)))
7324 ;;; Handling of Backspace and Delete keys.
7326 (defcustom normal-erase-is-backspace 'maybe
7327 "Set the default behavior of the Delete and Backspace keys.
7329 If set to t, Delete key deletes forward and Backspace key deletes
7330 backward.
7332 If set to nil, both Delete and Backspace keys delete backward.
7334 If set to 'maybe (which is the default), Emacs automatically
7335 selects a behavior. On window systems, the behavior depends on
7336 the keyboard used. If the keyboard has both a Backspace key and
7337 a Delete key, and both are mapped to their usual meanings, the
7338 option's default value is set to t, so that Backspace can be used
7339 to delete backward, and Delete can be used to delete forward.
7341 If not running under a window system, customizing this option
7342 accomplishes a similar effect by mapping C-h, which is usually
7343 generated by the Backspace key, to DEL, and by mapping DEL to C-d
7344 via `keyboard-translate'. The former functionality of C-h is
7345 available on the F1 key. You should probably not use this
7346 setting if you don't have both Backspace, Delete and F1 keys.
7348 Setting this variable with setq doesn't take effect. Programmatically,
7349 call `normal-erase-is-backspace-mode' (which see) instead."
7350 :type '(choice (const :tag "Off" nil)
7351 (const :tag "Maybe" maybe)
7352 (other :tag "On" t))
7353 :group 'editing-basics
7354 :version "21.1"
7355 :set (lambda (symbol value)
7356 ;; The fboundp is because of a problem with :set when
7357 ;; dumping Emacs. It doesn't really matter.
7358 (if (fboundp 'normal-erase-is-backspace-mode)
7359 (normal-erase-is-backspace-mode (or value 0))
7360 (set-default symbol value))))
7362 (defun normal-erase-is-backspace-setup-frame (&optional frame)
7363 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
7364 (unless frame (setq frame (selected-frame)))
7365 (with-selected-frame frame
7366 (unless (terminal-parameter nil 'normal-erase-is-backspace)
7367 (normal-erase-is-backspace-mode
7368 (if (if (eq normal-erase-is-backspace 'maybe)
7369 (and (not noninteractive)
7370 (or (memq system-type '(ms-dos windows-nt))
7371 (memq window-system '(w32 ns))
7372 (and (memq window-system '(x))
7373 (fboundp 'x-backspace-delete-keys-p)
7374 (x-backspace-delete-keys-p))
7375 ;; If the terminal Emacs is running on has erase char
7376 ;; set to ^H, use the Backspace key for deleting
7377 ;; backward, and the Delete key for deleting forward.
7378 (and (null window-system)
7379 (eq tty-erase-char ?\^H))))
7380 normal-erase-is-backspace)
7381 1 0)))))
7383 (define-minor-mode normal-erase-is-backspace-mode
7384 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
7385 With a prefix argument ARG, enable this feature if ARG is
7386 positive, and disable it otherwise. If called from Lisp, enable
7387 the mode if ARG is omitted or nil.
7389 On window systems, when this mode is on, Delete is mapped to C-d
7390 and Backspace is mapped to DEL; when this mode is off, both
7391 Delete and Backspace are mapped to DEL. (The remapping goes via
7392 `local-function-key-map', so binding Delete or Backspace in the
7393 global or local keymap will override that.)
7395 In addition, on window systems, the bindings of C-Delete, M-Delete,
7396 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
7397 the global keymap in accordance with the functionality of Delete and
7398 Backspace. For example, if Delete is remapped to C-d, which deletes
7399 forward, C-Delete is bound to `kill-word', but if Delete is remapped
7400 to DEL, which deletes backward, C-Delete is bound to
7401 `backward-kill-word'.
7403 If not running on a window system, a similar effect is accomplished by
7404 remapping C-h (normally produced by the Backspace key) and DEL via
7405 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
7406 to C-d; if it's off, the keys are not remapped.
7408 When not running on a window system, and this mode is turned on, the
7409 former functionality of C-h is available on the F1 key. You should
7410 probably not turn on this mode on a text-only terminal if you don't
7411 have both Backspace, Delete and F1 keys.
7413 See also `normal-erase-is-backspace'."
7414 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
7415 . (lambda (v)
7416 (setf (terminal-parameter nil 'normal-erase-is-backspace)
7417 (if v 1 0))))
7418 (let ((enabled (eq 1 (terminal-parameter
7419 nil 'normal-erase-is-backspace))))
7421 (cond ((or (memq window-system '(x w32 ns pc))
7422 (memq system-type '(ms-dos windows-nt)))
7423 (let ((bindings
7424 `(([M-delete] [M-backspace])
7425 ([C-M-delete] [C-M-backspace])
7426 ([?\e C-delete] [?\e C-backspace]))))
7428 (if enabled
7429 (progn
7430 (define-key local-function-key-map [delete] [deletechar])
7431 (define-key local-function-key-map [kp-delete] [?\C-d])
7432 (define-key local-function-key-map [backspace] [?\C-?])
7433 (dolist (b bindings)
7434 ;; Not sure if input-decode-map is really right, but
7435 ;; keyboard-translate-table (used below) only works
7436 ;; for integer events, and key-translation-table is
7437 ;; global (like the global-map, used earlier).
7438 (define-key input-decode-map (car b) nil)
7439 (define-key input-decode-map (cadr b) nil)))
7440 (define-key local-function-key-map [delete] [?\C-?])
7441 (define-key local-function-key-map [kp-delete] [?\C-?])
7442 (define-key local-function-key-map [backspace] [?\C-?])
7443 (dolist (b bindings)
7444 (define-key input-decode-map (car b) (cadr b))
7445 (define-key input-decode-map (cadr b) (car b))))))
7447 (if enabled
7448 (progn
7449 (keyboard-translate ?\C-h ?\C-?)
7450 (keyboard-translate ?\C-? ?\C-d))
7451 (keyboard-translate ?\C-h ?\C-h)
7452 (keyboard-translate ?\C-? ?\C-?))))
7454 (if (called-interactively-p 'interactive)
7455 (message "Delete key deletes %s"
7456 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
7457 "forward" "backward")))))
7459 (defvar vis-mode-saved-buffer-invisibility-spec nil
7460 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7462 (define-minor-mode read-only-mode
7463 "Change whether the current buffer is read-only.
7464 With prefix argument ARG, make the buffer read-only if ARG is
7465 positive, otherwise make it writable. If buffer is read-only
7466 and `view-read-only' is non-nil, enter view mode.
7468 Do not call this from a Lisp program unless you really intend to
7469 do the same thing as the \\[read-only-mode] command, including
7470 possibly enabling or disabling View mode. Also, note that this
7471 command works by setting the variable `buffer-read-only', which
7472 does not affect read-only regions caused by text properties. To
7473 ignore read-only status in a Lisp program (whether due to text
7474 properties or buffer state), bind `inhibit-read-only' temporarily
7475 to a non-nil value."
7476 :variable buffer-read-only
7477 (cond
7478 ((and (not buffer-read-only) view-mode)
7479 (View-exit-and-edit)
7480 (make-local-variable 'view-read-only)
7481 (setq view-read-only t)) ; Must leave view mode.
7482 ((and buffer-read-only view-read-only
7483 ;; If view-mode is already active, `view-mode-enter' is a nop.
7484 (not view-mode)
7485 (not (eq (get major-mode 'mode-class) 'special)))
7486 (view-mode-enter))))
7488 (define-minor-mode visible-mode
7489 "Toggle making all invisible text temporarily visible (Visible mode).
7490 With a prefix argument ARG, enable Visible mode if ARG is
7491 positive, and disable it otherwise. If called from Lisp, enable
7492 the mode if ARG is omitted or nil.
7494 This mode works by saving the value of `buffer-invisibility-spec'
7495 and setting it to nil."
7496 :lighter " Vis"
7497 :group 'editing-basics
7498 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
7499 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
7500 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
7501 (when visible-mode
7502 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
7503 buffer-invisibility-spec)
7504 (setq buffer-invisibility-spec nil)))
7506 (defvar messages-buffer-mode-map
7507 (let ((map (make-sparse-keymap)))
7508 (set-keymap-parent map special-mode-map)
7509 (define-key map "g" nil) ; nothing to revert
7510 map))
7512 (define-derived-mode messages-buffer-mode special-mode "Messages"
7513 "Major mode used in the \"*Messages*\" buffer.")
7515 (defun messages-buffer ()
7516 "Return the \"*Messages*\" buffer.
7517 If it does not exist, create and it switch it to `messages-buffer-mode'."
7518 (or (get-buffer "*Messages*")
7519 (with-current-buffer (get-buffer-create "*Messages*")
7520 (messages-buffer-mode)
7521 (current-buffer))))
7524 ;; Minibuffer prompt stuff.
7526 ;;(defun minibuffer-prompt-modification (start end)
7527 ;; (error "You cannot modify the prompt"))
7530 ;;(defun minibuffer-prompt-insertion (start end)
7531 ;; (let ((inhibit-modification-hooks t))
7532 ;; (delete-region start end)
7533 ;; ;; Discard undo information for the text insertion itself
7534 ;; ;; and for the text deletion.above.
7535 ;; (when (consp buffer-undo-list)
7536 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
7537 ;; (message "You cannot modify the prompt")))
7540 ;;(setq minibuffer-prompt-properties
7541 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
7542 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
7545 ;;;; Problematic external packages.
7547 ;; rms says this should be done by specifying symbols that define
7548 ;; versions together with bad values. This is therefore not as
7549 ;; flexible as it could be. See the thread:
7550 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
7551 (defconst bad-packages-alist
7552 ;; Not sure exactly which semantic versions have problems.
7553 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
7554 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
7555 "The version of `semantic' loaded does not work in Emacs 22.
7556 It can cause constant high CPU load.
7557 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
7558 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
7559 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
7560 ;; provided the `CUA-mode' feature. Since this is no longer true,
7561 ;; we can warn the user if the `CUA-mode' feature is ever provided.
7562 (CUA-mode t nil
7563 "CUA-mode is now part of the standard GNU Emacs distribution,
7564 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
7566 You have loaded an older version of CUA-mode which does not work
7567 correctly with this version of Emacs. You should remove the old
7568 version and use the one distributed with Emacs."))
7569 "Alist of packages known to cause problems in this version of Emacs.
7570 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
7571 PACKAGE is either a regular expression to match file names, or a
7572 symbol (a feature name), like for `with-eval-after-load'.
7573 SYMBOL is either the name of a string variable, or `t'. Upon
7574 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
7575 warning using STRING as the message.")
7577 (defun bad-package-check (package)
7578 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
7579 (condition-case nil
7580 (let* ((list (assoc package bad-packages-alist))
7581 (symbol (nth 1 list)))
7582 (and list
7583 (boundp symbol)
7584 (or (eq symbol t)
7585 (and (stringp (setq symbol (eval symbol)))
7586 (string-match-p (nth 2 list) symbol)))
7587 (display-warning package (nth 3 list) :warning)))
7588 (error nil)))
7590 (dolist (elem bad-packages-alist)
7591 (let ((pkg (car elem)))
7592 (with-eval-after-load pkg
7593 (bad-package-check pkg))))
7596 ;;; Generic dispatcher commands
7598 ;; Macro `define-alternatives' is used to create generic commands.
7599 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
7600 ;; that can have different alternative implementations where choosing
7601 ;; among them is exclusively a matter of user preference.
7603 ;; (define-alternatives COMMAND) creates a new interactive command
7604 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
7605 ;; Typically, the user will not need to customize this variable; packages
7606 ;; wanting to add alternative implementations should use
7608 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
7610 (defmacro define-alternatives (command &rest customizations)
7611 "Define new command `COMMAND'.
7612 The variable `COMMAND-alternatives' will contain alternative
7613 implementations of COMMAND, so that running `C-u M-x COMMAND'
7614 will allow the user to chose among them.
7615 CUSTOMIZATIONS, if non-nil, should be composed of alternating
7616 `defcustom' keywords and values to add to the declaration of
7617 `COMMAND-alternatives' (typically :group and :version)."
7618 (let* ((command-name (symbol-name command))
7619 (varalt-name (concat command-name "-alternatives"))
7620 (varalt-sym (intern varalt-name))
7621 (varimp-sym (intern (concat command-name "--implementation"))))
7622 `(progn
7624 (defcustom ,varalt-sym nil
7625 ,(format "Alist of alternative implementations for the `%s' command.
7627 Each entry must be a pair (ALTNAME . ALTFUN), where:
7628 ALTNAME - The name shown at user to describe the alternative implementation.
7629 ALTFUN - The function called to implement this alternative."
7630 command-name)
7631 :type '(alist :key-type string :value-type function)
7632 ,@customizations)
7634 (defvar ,varimp-sym nil "Internal use only.")
7636 (defun ,command (&optional arg)
7637 ,(format "Run generic command `%s'.
7638 If used for the first time, or with interactive ARG, ask the user which
7639 implementation to use for `%s'. The variable `%s'
7640 contains the list of implementations currently supported for this command."
7641 command-name command-name varalt-name)
7642 (interactive "P")
7643 (when (or arg (null ,varimp-sym))
7644 (let ((val (completing-read
7645 ,(format "Select implementation for command `%s': " command-name)
7646 ,varalt-sym nil t)))
7647 (unless (string-equal val "")
7648 (customize-save-variable ',varimp-sym
7649 (cdr (assoc-string val ,varalt-sym))))))
7650 (if ,varimp-sym
7651 (funcall ,varimp-sym)
7652 (message ,(format "No implementation selected for command `%s'"
7653 command-name)))))))
7655 (provide 'simple)
7657 ;;; simple.el ends here