1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2013 Free Software Foundation, Inc.
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/>.
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
31 (declare-function widget-convert
"wid-edit" (type &rest args
))
32 (declare-function shell-mode
"shell" ())
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."
47 "Killing and yanking commands."
50 (defgroup paren-matching nil
51 "Highlight (un)matching of parens and expressions."
54 ;;; next-error support framework
56 (defgroup next-error nil
57 "`next-error' support framework."
62 '((t (:inherit region
)))
63 "Face used to highlight next error locus."
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
))
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
))
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
))
106 (defcustom next-error-hook nil
107 "List of hook functions run by `next-error' after visiting source file."
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
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
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
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
189 (delq nil
(mapcar (lambda (w)
190 (if (next-error-buffer-p
193 extra-test-inclusive extra-test-exclusive
)
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
)
207 ;; 4. Look for any acceptable buffer.
208 (let ((buffers (buffer-list)))
210 (not (next-error-buffer-p
211 (car buffers
) avoid-current
212 extra-test-inclusive extra-test-exclusive
)))
213 (setq buffers
(cdr buffers
)))
215 ;; 5. Use the current buffer as a last resort if it qualifies,
216 ;; even despite AVOID-CURRENT.
218 (next-error-buffer-p (current-buffer) nil
219 extra-test-inclusive extra-test-exclusive
)
221 (message "This is the only buffer with error message locations")
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'."
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."
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."
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."
304 (let ((next-error-highlight next-error-highlight-no-select
))
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."
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
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))
339 (let ((compilation-context-lines nil
))
340 (setq compilation-current-error
(point))
341 (next-error-no-select 0))
347 (defun fundamental-mode ()
348 "Major mode not specialized for anything in particular.
349 Other major modes are defined by comparison with this one."
351 (kill-all-local-variables)
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
)
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
)))
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
))
398 ;; Do the rest in post-self-insert-hook, because we want to do it
399 ;; *before* other functions on that hook.
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.
408 (goto-char beforepos
)
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
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
)))
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
))))
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
)))))
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."
449 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
450 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
452 ;; Don't expand an abbrev before point.
458 (if do-left-margin
(indent-to (current-left-margin)))
459 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
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."
472 (skip-chars-forward " \t")
473 (let* ((col (current-column))
475 ;; What prefix should we check for (nil means don't).
476 (prefix (cond ((stringp arg
) arg
)
479 ;; Does this line start with it?
480 (have-prfx (and prefix
483 (looking-at (regexp-quote prefix
))))))
485 (if have-prfx
(insert-and-inherit prefix
))
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."
495 (if arg
(forward-line 1))
496 (if (eq (preceding-char) ?
\n)
498 (delete-region (point) (1- (point)))
499 ;; If the second line started with the fill prefix,
500 ;; delete the prefix.
502 (<= (+ (point) (length fill-prefix
)) (point-max))
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."
516 (let (thisblank singleblank
)
519 (setq thisblank
(looking-at "[ \t]*$"))
520 ;; Set singleblank if there is just one blank line here.
523 (not (looking-at "[ \t]*\n[ \t]*$"))
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.
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))
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
))
542 (delete-region (point)
543 (if (re-search-forward "[^ \t\n]" nil t
)
544 (progn (beginning-of-line) (point))
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)."
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."
574 (barf-if-buffer-read-only)
576 (list (region-beginning) (region-end))
580 (let ((end-marker (copy-marker (or end
(point-max))))
581 (start (or start
(point-min))))
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
)
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'.
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'."
608 (delete-horizontal-space t
)
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'."
621 ;; Be careful to insert the newline before indenting the line.
622 ;; Otherwise, the indentation might be wrong.
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
631 (setq pos
(copy-marker pos t
))
632 (indent-according-to-mode)
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 (defun quoted-insert (arg)
640 "Read next input character and insert it.
641 This is useful for inserting control characters.
642 With argument, insert ARG copies of the character.
644 If the first character you type after this command is an octal digit,
645 you should type a sequence of octal digits which specify a character code.
646 Any nondigit terminates the sequence. If the terminator is a RET,
647 it is discarded; any other terminator is used itself as input.
648 The variable `read-quoted-char-radix' specifies the radix for this feature;
649 set it to 10 or 16 to use decimal or hex instead of octal.
651 In overwrite mode, this function inserts the character anyway, and
652 does not handle octal digits specially. This means that if you use
653 overwrite as your normal editing mode, you can use this function to
654 insert characters when necessary.
656 In binary overwrite mode, this function does overwrite, and octal
657 digits are interpreted as a character code. This is intended to be
658 useful for editing binary files."
661 ;; Avoid "obsolete" warnings for translation-table-for-input.
663 (let (translation-table-for-input input-method-function
)
664 (if (or (not overwrite-mode
)
665 (eq overwrite-mode
'overwrite-mode-binary
))
668 ;; This used to assume character codes 0240 - 0377 stand for
669 ;; characters in some single-byte character set, and converted them
670 ;; to Emacs characters. But in 23.1 this feature is deprecated
671 ;; in favor of inserting the corresponding Unicode characters.
672 ;; (if (and enable-multibyte-characters
675 ;; (setq char (unibyte-char-to-multibyte char)))
677 (if (eq overwrite-mode
'overwrite-mode-binary
)
680 (insert-and-inherit char
)
681 (setq arg
(1- arg
)))))
683 (defun forward-to-indentation (&optional arg
)
684 "Move forward ARG lines and position at first nonblank character."
686 (forward-line (or arg
1))
687 (skip-chars-forward " \t"))
689 (defun backward-to-indentation (&optional arg
)
690 "Move backward ARG lines and position at first nonblank character."
692 (forward-line (- (or arg
1)))
693 (skip-chars-forward " \t"))
695 (defun back-to-indentation ()
696 "Move point to the first non-whitespace character on this line."
698 (beginning-of-line 1)
699 (skip-syntax-forward " " (line-end-position))
700 ;; Move back over chars that have whitespace syntax but have the p flag.
701 (backward-prefix-chars))
703 (defun fixup-whitespace ()
704 "Fixup white space between objects around point.
705 Leave one space or none, according to the context."
708 (delete-horizontal-space)
709 (if (or (looking-at "^\\|\\s)")
710 (save-excursion (forward-char -
1)
711 (looking-at "$\\|\\s(\\|\\s'")))
715 (defun delete-horizontal-space (&optional backward-only
)
716 "Delete all spaces and tabs around point.
717 If BACKWARD-ONLY is non-nil, only delete them before point."
719 (let ((orig-pos (point)))
724 (skip-chars-forward " \t")
725 (constrain-to-field nil orig-pos t
)))
727 (skip-chars-backward " \t")
728 (constrain-to-field nil orig-pos
)))))
730 (defun just-one-space (&optional n
)
731 "Delete all spaces and tabs around point, leaving one space (or N spaces).
732 If N is negative, delete newlines as well, leaving -N spaces."
734 (cycle-spacing n nil t
))
736 (defvar cycle-spacing--context nil
737 "Store context used in consecutive calls to `cycle-spacing' command.
738 The first time this function is run, it saves the original point
739 position and original spacing around the point in this
742 (defun cycle-spacing (&optional n preserve-nl-back single-shot
)
743 "Manipulate spaces around the point in a smart way.
745 When run as an interactive command, the first time it's called
746 in a sequence, deletes all spaces and tabs around point leaving
747 one (or N spaces). If this does not change content of the
748 buffer, skips to the second step:
750 When run for the second time in a sequence, deletes all the
751 spaces it has previously inserted.
753 When run for the third time, returns the whitespace and point in
754 a state encountered when it had been run for the first time.
756 For example, if buffer contains \"foo ^ bar\" with \"^\" denoting the
757 point, calling `cycle-spacing' command will replace two spaces with
758 a single space, calling it again immediately after, will remove all
759 spaces, and calling it for the third time will bring two spaces back
762 If N is negative, delete newlines as well. However, if
763 PRESERVE-NL-BACK is t new line characters prior to the point
766 If SINGLE-SHOT is non-nil, will only perform the first step. In
767 other words, it will work just like `just-one-space' command."
769 (let ((orig-pos (point))
770 (skip-characters (if (and n
(< n
0)) " \t\n\r" " \t"))
772 (skip-chars-backward (if preserve-nl-back
" \t" skip-characters
))
773 (constrain-to-field nil orig-pos
)
775 ;; Command run for the first time or single-shot is non-nil.
777 (not (equal last-command this-command
))
778 (not cycle-spacing--context
))
779 (let* ((start (point))
780 (n (- n
(skip-chars-forward " " (+ n
(point)))))
783 (skip-chars-forward skip-characters
)
784 (constrain-to-field nil orig-pos t
))))
785 (setq cycle-spacing--context
;; Save for later.
786 ;; Special handling for case where there was no space at all.
787 (unless (= start end
)
788 (cons orig-pos
(buffer-substring start
(point)))))
789 ;; If this run causes no change in buffer content, delete all spaces,
790 ;; otherwise delete all excess spaces.
791 (delete-region (if (and (not single-shot
) (zerop n
) (= mid end
))
793 (insert (make-string n ?\s
))))
795 ;; Command run for the second time.
796 ((not (equal orig-pos
(point)))
797 (delete-region (point) orig-pos
))
799 ;; Command run for the third time.
801 (insert (cdr cycle-spacing--context
))
802 (goto-char (car cycle-spacing--context
))
803 (setq cycle-spacing--context nil
)))))
805 (defun beginning-of-buffer (&optional arg
)
806 "Move point to the beginning of the buffer.
807 With numeric arg N, put point N/10 of the way from the beginning.
808 If the buffer is narrowed, this command uses the beginning of the
809 accessible part of the buffer.
811 If Transient Mark mode is disabled, leave mark at previous
812 position, unless a \\[universal-argument] prefix is supplied.
814 Don't use this command in Lisp programs!
815 \(goto-char (point-min)) is faster."
820 (let ((size (- (point-max) (point-min))))
821 (goto-char (if (and arg
(not (consp arg
)))
824 ;; Avoid overflow for large buffer sizes!
825 (* (prefix-numeric-value arg
)
827 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
829 (if (and arg
(not (consp arg
))) (forward-line 1)))
831 (defun end-of-buffer (&optional arg
)
832 "Move point to the end of the buffer.
833 With numeric arg N, put point N/10 of the way from the end.
834 If the buffer is narrowed, this command uses the end of the
835 accessible part of the buffer.
837 If Transient Mark mode is disabled, leave mark at previous
838 position, unless a \\[universal-argument] prefix is supplied.
840 Don't use this command in Lisp programs!
841 \(goto-char (point-max)) is faster."
843 (or (consp arg
) (region-active-p) (push-mark))
844 (let ((size (- (point-max) (point-min))))
845 (goto-char (if (and arg
(not (consp arg
)))
848 ;; Avoid overflow for large buffer sizes!
849 (* (prefix-numeric-value arg
)
851 (/ (* size
(prefix-numeric-value arg
)) 10)))
853 ;; If we went to a place in the middle of the buffer,
854 ;; adjust it to the beginning of a line.
855 (cond ((and arg
(not (consp arg
))) (forward-line 1))
856 ((and (eq (current-buffer) (window-buffer))
857 (> (point) (window-end nil t
)))
858 ;; If the end of the buffer is not already on the screen,
859 ;; then scroll specially to put it near, but not at, the bottom.
860 (overlay-recenter (point))
863 (defcustom delete-active-region t
864 "Whether single-char deletion commands delete an active region.
865 This has an effect only if Transient Mark mode is enabled, and
866 affects `delete-forward-char' and `delete-backward-char', though
869 If the value is the symbol `kill', the active region is killed
871 :type
'(choice (const :tag
"Delete active region" t
)
872 (const :tag
"Kill active region" kill
)
873 (const :tag
"Do ordinary deletion" nil
))
877 (defun delete-backward-char (n &optional killflag
)
878 "Delete the previous N characters (following if N is negative).
879 If Transient Mark mode is enabled, the mark is active, and N is 1,
880 delete the text in the region and deactivate the mark instead.
881 To disable this, set option `delete-active-region' to nil.
883 Optional second arg KILLFLAG, if non-nil, means to kill (save in
884 kill ring) instead of delete. Interactively, N is the prefix
885 arg, and KILLFLAG is set if N is explicitly specified.
887 In Overwrite mode, single character backward deletion may replace
888 tabs with spaces so as to back over columns, unless point is at
889 the end of the line."
892 (signal 'wrong-type-argument
(list 'integerp n
)))
893 (cond ((and (use-region-p)
896 ;; If a region is active, kill or delete it.
897 (if (eq delete-active-region
'kill
)
898 (kill-region (region-beginning) (region-end))
899 (delete-region (region-beginning) (region-end))))
900 ;; In Overwrite mode, maybe untabify while deleting
901 ((null (or (null overwrite-mode
)
903 (memq (char-before) '(?
\t ?
\n))
905 (eq (char-after) ?
\n)))
906 (let ((ocol (current-column)))
907 (delete-char (- n
) killflag
)
909 (insert-char ?\s
(- ocol
(current-column)) nil
))))
910 ;; Otherwise, do simple deletion.
911 (t (delete-char (- n
) killflag
))))
913 (defun delete-forward-char (n &optional killflag
)
914 "Delete the following N characters (previous if N is negative).
915 If Transient Mark mode is enabled, the mark is active, and N is 1,
916 delete the text in the region and deactivate the mark instead.
917 To disable this, set variable `delete-active-region' to nil.
919 Optional second arg KILLFLAG non-nil means to kill (save in kill
920 ring) instead of delete. Interactively, N is the prefix arg, and
921 KILLFLAG is set if N was explicitly specified."
924 (signal 'wrong-type-argument
(list 'integerp n
)))
925 (cond ((and (use-region-p)
928 ;; If a region is active, kill or delete it.
929 (if (eq delete-active-region
'kill
)
930 (kill-region (region-beginning) (region-end))
931 (delete-region (region-beginning) (region-end))))
932 ;; Otherwise, do simple deletion.
933 (t (delete-char n killflag
))))
935 (defun mark-whole-buffer ()
936 "Put point at beginning and mark at end of buffer.
937 If narrowing is in effect, only uses the accessible part of the buffer.
938 You probably should not use this function in Lisp programs;
939 it is usually a mistake for a Lisp function to use any subroutine
940 that uses or sets the mark."
943 (push-mark (point-max) nil t
)
944 (goto-char (point-min)))
947 ;; Counting lines, one way or another.
949 (defun goto-line (line &optional buffer
)
950 "Go to LINE, counting from line 1 at beginning of buffer.
951 If called interactively, a numeric prefix argument specifies
952 LINE; without a numeric prefix argument, read LINE from the
955 If optional argument BUFFER is non-nil, switch to that buffer and
956 move to line LINE there. If called interactively with \\[universal-argument]
957 as argument, BUFFER is the most recently selected other buffer.
959 Prior to moving point, this function sets the mark (without
960 activating it), unless Transient Mark mode is enabled and the
961 mark is already active.
963 This function is usually the wrong thing to use in a Lisp program.
964 What you probably want instead is something like:
965 (goto-char (point-min))
966 (forward-line (1- N))
967 If at all possible, an even better solution is to use char counts
968 rather than line counts."
970 (if (and current-prefix-arg
(not (consp current-prefix-arg
)))
971 (list (prefix-numeric-value current-prefix-arg
))
972 ;; Look for a default, a number in the buffer at point.
975 (skip-chars-backward "0-9")
976 (if (looking-at "[0-9]")
978 (buffer-substring-no-properties
980 (progn (skip-chars-forward "0-9")
982 ;; Decide if we're switching buffers.
984 (if (consp current-prefix-arg
)
985 (other-buffer (current-buffer) t
)))
988 (concat " in " (buffer-name buffer
))
990 ;; Read the argument, offering that number (if any) as default.
991 (list (read-number (format "Goto line%s: " buffer-prompt
)
992 (list default
(line-number-at-pos)))
994 ;; Switch to the desired buffer, one way or another.
996 (let ((window (get-buffer-window buffer
)))
997 (if window
(select-window window
)
998 (switch-to-buffer-other-window buffer
))))
999 ;; Leave mark at previous position
1000 (or (region-active-p) (push-mark))
1001 ;; Move to the specified line number in that buffer.
1004 (goto-char (point-min))
1005 (if (eq selective-display t
)
1006 (re-search-forward "[\n\C-m]" nil
'end
(1- line
))
1007 (forward-line (1- line
)))))
1009 (defun count-words-region (start end
&optional arg
)
1010 "Count the number of words in the region.
1011 If called interactively, print a message reporting the number of
1012 lines, words, and characters in the region (whether or not the
1013 region is active); with prefix ARG, report for the entire buffer
1014 rather than the region.
1016 If called from Lisp, return the number of words between positions
1018 (interactive (if current-prefix-arg
1019 (list nil nil current-prefix-arg
)
1020 (list (region-beginning) (region-end) nil
)))
1021 (cond ((not (called-interactively-p 'any
))
1022 (count-words start end
))
1024 (count-words--buffer-message))
1026 (count-words--message "Region" start end
))))
1028 (defun count-words (start end
)
1029 "Count words between START and END.
1030 If called interactively, START and END are normally the start and
1031 end of the buffer; but if the region is active, START and END are
1032 the start and end of the region. Print a message reporting the
1033 number of lines, words, and chars.
1035 If called from Lisp, return the number of words between START and
1036 END, without printing any message."
1037 (interactive (list nil nil
))
1038 (cond ((not (called-interactively-p 'any
))
1042 (narrow-to-region start end
)
1043 (goto-char (point-min))
1044 (while (forward-word 1)
1045 (setq words
(1+ words
)))))
1048 (call-interactively 'count-words-region
))
1050 (count-words--buffer-message))))
1052 (defun count-words--buffer-message ()
1053 (count-words--message
1054 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1055 (point-min) (point-max)))
1057 (defun count-words--message (str start end
)
1058 (let ((lines (count-lines start end
))
1059 (words (count-words start end
))
1060 (chars (- end start
)))
1061 (message "%s has %d line%s, %d word%s, and %d character%s."
1063 lines
(if (= lines
1) "" "s")
1064 words
(if (= words
1) "" "s")
1065 chars
(if (= chars
1) "" "s"))))
1067 (define-obsolete-function-alias 'count-lines-region
'count-words-region
"24.1")
1070 "Print the current buffer line number and narrowed line number of point."
1072 (let ((start (point-min))
1073 (n (line-number-at-pos)))
1075 (message "Line %d" n
)
1079 (message "line %d (narrowed line %d)"
1080 (+ n
(line-number-at-pos start
) -
1) n
))))))
1082 (defun count-lines (start end
)
1083 "Return number of lines between START and END.
1084 This is usually the number of newlines between them,
1085 but can be one more if START is not equal to END
1086 and the greater of them is not at the start of a line."
1089 (narrow-to-region start end
)
1090 (goto-char (point-min))
1091 (if (eq selective-display t
)
1094 (while (re-search-forward "[\n\C-m]" nil t
40)
1095 (setq done
(+ 40 done
)))
1096 (while (re-search-forward "[\n\C-m]" nil t
1)
1097 (setq done
(+ 1 done
)))
1098 (goto-char (point-max))
1099 (if (and (/= start end
)
1103 (- (buffer-size) (forward-line (buffer-size)))))))
1105 (defun line-number-at-pos (&optional pos
)
1106 "Return (narrowed) buffer line number at position POS.
1107 If POS is nil, use current buffer location.
1108 Counting starts at (point-min), so the value refers
1109 to the contents of the accessible portion of the buffer."
1110 (let ((opoint (or pos
(point))) start
)
1112 (goto-char (point-min))
1113 (setq start
(point))
1116 (1+ (count-lines start
(point))))))
1118 (defun what-cursor-position (&optional detail
)
1119 "Print info on cursor position (on screen and within buffer).
1120 Also describe the character after point, and give its character code
1121 in octal, decimal and hex.
1123 For a non-ASCII multibyte character, also give its encoding in the
1124 buffer's selected coding system if the coding system encodes the
1125 character safely. If the character is encoded into one byte, that
1126 code is shown in hex. If the character is encoded into more than one
1127 byte, just \"...\" is shown.
1129 In addition, with prefix argument, show details about that character
1130 in *Help* buffer. See also the command `describe-char'."
1132 (let* ((char (following-char))
1134 (cond ((memq char
'(?
\x202a ?
\x202b ?
\x202d ?
\x202e
))
1135 ;; If the character is one of LRE, LRO, RLE, RLO, it
1136 ;; will start a directional embedding, which could
1137 ;; completely disrupt the rest of the line (e.g., RLO
1138 ;; will display the rest of the line right-to-left).
1139 ;; So we put an invisible PDF character after these
1140 ;; characters, to end the embedding, which eliminates
1141 ;; any effects on the rest of the line.
1142 (propertize (string ?
\x202c
) 'invisible t
))
1143 ;; Strong right-to-left characters cause reordering of
1144 ;; the following numerical characters which show the
1145 ;; codepoint, so append LRM to countermand that.
1146 ((memq (get-char-code-property char
'bidi-class
) '(R AL
))
1147 (propertize (string ?
\x200e
) 'invisible t
))
1153 (total (buffer-size))
1154 (percent (if (> total
50000)
1155 ;; Avoid overflow from multiplying by 100!
1156 (/ (+ (/ total
200) (1- pos
)) (max (/ total
100) 1))
1157 (/ (+ (/ total
2) (* 100 (1- pos
))) (max total
1))))
1158 (hscroll (if (= (window-hscroll) 0)
1160 (format " Hscroll=%d" (window-hscroll))))
1161 (col (current-column)))
1163 (if (or (/= beg
1) (/= end
(1+ total
)))
1164 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1165 pos total percent beg end col hscroll
)
1166 (message "point=%d of %d (EOB) column=%d%s"
1167 pos total col hscroll
))
1168 (let ((coding buffer-file-coding-system
)
1169 encoded encoding-msg display-prop under-display
)
1170 (if (or (not coding
)
1171 (eq (coding-system-type coding
) t
))
1172 (setq coding
(default-value 'buffer-file-coding-system
)))
1173 (if (eq (char-charset char
) 'eight-bit
)
1175 (format "(%d, #o%o, #x%x, raw-byte)" char char char
))
1176 ;; Check if the character is displayed with some `display'
1177 ;; text property. In that case, set under-display to the
1178 ;; buffer substring covered by that property.
1179 (setq display-prop
(get-char-property pos
'display
))
1181 (let ((to (or (next-single-char-property-change pos
'display
)
1183 (if (< to
(+ pos
4))
1184 (setq under-display
"")
1185 (setq under-display
"..."
1188 (concat (buffer-substring-no-properties pos to
)
1190 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
1193 (if (not (stringp display-prop
))
1194 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1195 char char char under-display
)
1196 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1197 char char char under-display display-prop
))
1199 (format "(%d, #o%o, #x%x, file %s)"
1201 (if (> (length encoded
) 1)
1203 (encoded-string-description encoded coding
)))
1204 (format "(%d, #o%o, #x%x)" char char char
)))))
1206 ;; We show the detailed information about CHAR.
1207 (describe-char (point)))
1208 (if (or (/= beg
1) (/= end
(1+ total
)))
1209 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1211 (single-key-description char
)
1212 (buffer-substring-no-properties (point) (1+ (point))))
1214 encoding-msg pos total percent beg end col hscroll
)
1215 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1216 (if enable-multibyte-characters
1218 (single-key-description char
)
1219 (buffer-substring-no-properties (point) (1+ (point))))
1220 (single-key-description char
))
1221 bidi-fixer encoding-msg pos total percent col hscroll
))))))
1223 ;; Initialize read-expression-map. It is defined at C level.
1224 (defvar read-expression-map
1225 (let ((m (make-sparse-keymap)))
1226 (define-key m
"\M-\t" 'completion-at-point
)
1227 ;; Might as well bind TAB to completion, since inserting a TAB char is
1228 ;; much too rarely useful.
1229 (define-key m
"\t" 'completion-at-point
)
1230 (set-keymap-parent m minibuffer-local-map
)
1233 (defun read-minibuffer (prompt &optional initial-contents
)
1234 "Return a Lisp object read using the minibuffer, unevaluated.
1235 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1236 is a string to insert in the minibuffer before reading.
1237 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1238 Such arguments are used as in `read-from-minibuffer'.)"
1239 ;; Used for interactive spec `x'.
1240 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1241 t
'minibuffer-history
))
1243 (defun eval-minibuffer (prompt &optional initial-contents
)
1244 "Return value of Lisp expression read using the minibuffer.
1245 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1246 is a string to insert in the minibuffer before reading.
1247 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1248 Such arguments are used as in `read-from-minibuffer'.)"
1249 ;; Used for interactive spec `X'.
1250 (eval (read--expression prompt initial-contents
)))
1252 (defvar minibuffer-completing-symbol nil
1253 "Non-nil means completing a Lisp symbol in the minibuffer.")
1254 (make-obsolete-variable 'minibuffer-completing-symbol nil
"24.1" 'get
)
1256 (defvar minibuffer-default nil
1257 "The current default value or list of default values in the minibuffer.
1258 The functions `read-from-minibuffer' and `completing-read' bind
1259 this variable locally.")
1261 (defcustom eval-expression-print-level
4
1262 "Value for `print-level' while printing value in `eval-expression'.
1263 A value of nil means no limit."
1265 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1268 (defcustom eval-expression-print-length
12
1269 "Value for `print-length' while printing value in `eval-expression'.
1270 A value of nil means no limit."
1272 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1275 (defcustom eval-expression-debug-on-error t
1276 "If non-nil set `debug-on-error' to t in `eval-expression'.
1277 If nil, don't change the value of `debug-on-error'."
1282 (defun eval-expression-print-format (value)
1283 "Format VALUE as a result of evaluated expression.
1284 Return a formatted string which is displayed in the echo area
1285 in addition to the value printed by prin1 in functions which
1286 display the result of expression evaluation."
1287 (if (and (integerp value
)
1288 (or (not (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1289 (eq this-command last-command
)
1290 (if (boundp 'edebug-active
) edebug-active
)))
1292 (if (or (if (boundp 'edebug-active
) edebug-active
)
1293 (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1294 (prin1-char value
))))
1296 (format " (#o%o, #x%x, %s)" value value char-string
)
1297 (format " (#o%o, #x%x)" value value
)))))
1299 (defvar eval-expression-minibuffer-setup-hook nil
1300 "Hook run by `eval-expression' when entering the minibuffer.")
1302 (defun read--expression (prompt &optional initial-contents
)
1303 (let ((minibuffer-completing-symbol t
))
1304 (minibuffer-with-setup-hook
1306 (add-hook 'completion-at-point-functions
1307 #'lisp-completion-at-point nil t
)
1308 (run-hooks 'eval-expression-minibuffer-setup-hook
))
1309 (read-from-minibuffer prompt initial-contents
1310 read-expression-map t
1311 'read-expression-history
))))
1313 ;; We define this, rather than making `eval' interactive,
1314 ;; for the sake of completion of names like eval-region, eval-buffer.
1315 (defun eval-expression (exp &optional insert-value
)
1316 "Evaluate EXP and print value in the echo area.
1317 When called interactively, read an Emacs Lisp expression and
1319 Value is also consed on to front of the variable `values'.
1320 Optional argument INSERT-VALUE non-nil (interactively,
1321 with prefix argument) means insert the result into the current buffer
1322 instead of printing it in the echo area. Truncates long output
1323 according to the value of the variables `eval-expression-print-length'
1324 and `eval-expression-print-level'.
1326 If `eval-expression-debug-on-error' is non-nil, which is the default,
1327 this command arranges for all errors to enter the debugger."
1329 (list (read--expression "Eval: ")
1330 current-prefix-arg
))
1332 (if (null eval-expression-debug-on-error
)
1333 (push (eval exp lexical-binding
) values
)
1334 (let ((old-value (make-symbol "t")) new-value
)
1335 ;; Bind debug-on-error to something unique so that we can
1336 ;; detect when evalled code changes it.
1337 (let ((debug-on-error old-value
))
1338 (push (eval exp lexical-binding
) values
)
1339 (setq new-value debug-on-error
))
1340 ;; If evalled code has changed the value of debug-on-error,
1341 ;; propagate that change to the global binding.
1342 (unless (eq old-value new-value
)
1343 (setq debug-on-error new-value
))))
1345 (let ((print-length eval-expression-print-length
)
1346 (print-level eval-expression-print-level
)
1350 (let ((standard-output (current-buffer)))
1351 (prin1 (car values
))))
1353 (prin1 (car values
) t
)
1354 (let ((str (eval-expression-print-format (car values
))))
1355 (if str
(princ str t
)))))))
1357 (defun edit-and-eval-command (prompt command
)
1358 "Prompting with PROMPT, let user edit COMMAND and eval result.
1359 COMMAND is a Lisp expression. Let user edit that expression in
1360 the minibuffer, then read and evaluate the result."
1362 (let ((print-level nil
)
1363 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1365 (read-from-minibuffer prompt
1366 (prin1-to-string command
)
1367 read-expression-map t
1369 ;; If command was added to command-history as a string,
1370 ;; get rid of that. We want only evaluable expressions there.
1371 (if (stringp (car command-history
))
1372 (setq command-history
(cdr command-history
)))))))
1374 ;; If command to be redone does not match front of history,
1375 ;; add it to the history.
1376 (or (equal command
(car command-history
))
1377 (setq command-history
(cons command command-history
)))
1380 (defun repeat-complex-command (arg)
1381 "Edit and re-evaluate last complex command, or ARGth from last.
1382 A complex command is one which used the minibuffer.
1383 The command is placed in the minibuffer as a Lisp form for editing.
1384 The result is executed, repeating the command as changed.
1385 If the command has been changed or is not the most recent previous
1386 command it is added to the front of the command history.
1387 You can use the minibuffer history commands \
1388 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1389 to get different commands to edit and resubmit."
1391 (let ((elt (nth (1- arg
) command-history
))
1396 (let ((print-level nil
)
1397 (minibuffer-history-position arg
)
1398 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1400 (read-from-minibuffer
1401 "Redo: " (prin1-to-string elt
) read-expression-map t
1402 (cons 'command-history arg
))
1404 ;; If command was added to command-history as a
1405 ;; string, get rid of that. We want only
1406 ;; evaluable expressions there.
1407 (if (stringp (car command-history
))
1408 (setq command-history
(cdr command-history
))))))
1410 ;; If command to be redone does not match front of history,
1411 ;; add it to the history.
1412 (or (equal newcmd
(car command-history
))
1413 (setq command-history
(cons newcmd command-history
)))
1416 ;; Trick called-interactively-p into thinking that `newcmd' is
1417 ;; an interactive call (bug#14136).
1418 (add-hook 'called-interactively-p-functions
1419 #'repeat-complex-command--called-interactively-skip
)
1421 (remove-hook 'called-interactively-p-functions
1422 #'repeat-complex-command--called-interactively-skip
)))
1424 (error "Argument %d is beyond length of command history" arg
)
1425 (error "There are no previous complex commands to repeat")))))
1427 (defun repeat-complex-command--called-interactively-skip (i _frame1 frame2
)
1428 (and (eq 'eval
(cadr frame2
))
1429 (eq 'repeat-complex-command
1430 (cadr (backtrace-frame i
#'called-interactively-p
)))
1433 (defvar extended-command-history nil
)
1435 (defun read-extended-command ()
1436 "Read command name to invoke in `execute-extended-command'."
1437 (minibuffer-with-setup-hook
1439 (set (make-local-variable 'minibuffer-default-add-function
)
1441 ;; Get a command name at point in the original buffer
1442 ;; to propose it after M-n.
1443 (with-current-buffer (window-buffer (minibuffer-selected-window))
1444 (and (commandp (function-called-at-point))
1445 (format "%S" (function-called-at-point)))))))
1446 ;; Read a string, completing from and restricting to the set of
1447 ;; all defined commands. Don't provide any initial input.
1448 ;; Save the command read on the extended-command history list.
1451 ((eq current-prefix-arg
'-
) "- ")
1452 ((and (consp current-prefix-arg
)
1453 (eq (car current-prefix-arg
) 4)) "C-u ")
1454 ((and (consp current-prefix-arg
)
1455 (integerp (car current-prefix-arg
)))
1456 (format "%d " (car current-prefix-arg
)))
1457 ((integerp current-prefix-arg
)
1458 (format "%d " current-prefix-arg
)))
1459 ;; This isn't strictly correct if `execute-extended-command'
1460 ;; is bound to anything else (e.g. [menu]).
1461 ;; It could use (key-description (this-single-command-keys)),
1462 ;; but actually a prompt other than "M-x" would be confusing,
1463 ;; because "M-x" is a well-known prompt to read a command
1464 ;; and it serves as a shorthand for "Extended command: ".
1466 obarray
'commandp t nil
'extended-command-history
)))
1468 (defcustom suggest-key-bindings t
1469 "Non-nil means show the equivalent key-binding when M-x command has one.
1470 The value can be a length of time to show the message for.
1471 If the value is non-nil and not a number, we wait 2 seconds."
1473 :type
'(choice (const :tag
"off" nil
)
1474 (integer :tag
"time" 2)
1477 (defun execute-extended-command (prefixarg &optional command-name
)
1478 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1479 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1480 "Read function name, then read its arguments and call it.
1482 To pass a numeric argument to the command you are invoking, specify
1483 the numeric argument to this command.
1485 Noninteractively, the argument PREFIXARG is the prefix argument to
1486 give to the command you invoke, if it asks for an argument."
1487 (interactive (list current-prefix-arg
(read-extended-command)))
1488 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1489 (if (null command-name
)
1490 (setq command-name
(let ((current-prefix-arg prefixarg
)) ; for prompt
1491 (read-extended-command))))
1492 (let* ((function (and (stringp command-name
) (intern-soft command-name
)))
1493 (binding (and suggest-key-bindings
1494 (not executing-kbd-macro
)
1495 (where-is-internal function overriding-local-map t
))))
1496 (unless (commandp function
)
1497 (error "`%s' is not a valid command name" command-name
))
1498 (setq this-command function
)
1499 ;; Normally `real-this-command' should never be changed, but here we really
1500 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1501 ;; binding" for <cmd>, so the command the user really wanted to run is
1502 ;; `function' and not `execute-extended-command'. The difference is
1503 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1504 (setq real-this-command function
)
1505 (let ((prefix-arg prefixarg
))
1506 (command-execute function
'record
))
1507 ;; If enabled, show which key runs this command.
1509 ;; But first wait, and skip the message if there is input.
1511 ;; If this command displayed something in the echo area;
1512 ;; wait a few seconds, then display our suggestion message.
1514 ((zerop (length (current-message))) 0)
1515 ((numberp suggest-key-bindings
) suggest-key-bindings
)
1517 (when (and waited
(not (consp unread-command-events
)))
1519 (format "You can run the command `%s' with %s"
1520 function
(key-description binding
))
1521 (sit-for (if (numberp suggest-key-bindings
)
1522 suggest-key-bindings
1525 (defun command-execute (cmd &optional record-flag keys special
)
1526 ;; BEWARE: Called directly from the C code.
1527 "Execute CMD as an editor command.
1528 CMD must be a symbol that satisfies the `commandp' predicate.
1529 Optional second arg RECORD-FLAG non-nil
1530 means unconditionally put this command in the variable `command-history'.
1531 Otherwise, that is done only if an arg is read using the minibuffer.
1532 The argument KEYS specifies the value to use instead of (this-command-keys)
1533 when reading the arguments; if it is nil, (this-command-keys) is used.
1534 The argument SPECIAL, if non-nil, means that this command is executing
1535 a special event, so ignore the prefix argument and don't clear it."
1536 (setq debug-on-next-call nil
)
1537 (let ((prefixarg (unless special
1539 (setq current-prefix-arg prefix-arg
)
1540 (setq prefix-arg nil
)))))
1543 ;; FIXME: Weird calling convention!
1544 (run-hooks 'disabled-command-function
))
1548 (setq final
(indirect-function final
))
1549 (if (autoloadp final
)
1550 (setq final
(autoload-do-load final cmd
)))))
1553 ;; If requested, place the macro in the command history. For
1554 ;; other sorts of commands, call-interactively takes care of this.
1556 (push `(execute-kbd-macro ,final
,prefixarg
) command-history
)
1557 ;; Don't keep command history around forever.
1558 (when (and (numberp history-length
) (> history-length
0))
1559 (let ((cell (nthcdr history-length command-history
)))
1560 (if (consp cell
) (setcdr cell nil
)))))
1561 (execute-kbd-macro final prefixarg
))
1563 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1564 (prog1 (call-interactively cmd record-flag keys
)
1565 (when (and (symbolp cmd
)
1566 (get cmd
'byte-obsolete-info
)
1567 (not (get cmd
'command-execute-obsolete-warned
)))
1568 (put cmd
'command-execute-obsolete-warned t
)
1569 (message "%s" (macroexp--obsolete-warning
1570 cmd
(get cmd
'byte-obsolete-info
) "command")))))))))
1572 (defvar minibuffer-history nil
1573 "Default minibuffer history list.
1574 This is used for all minibuffer input
1575 except when an alternate history list is specified.
1577 Maximum length of the history list is determined by the value
1578 of `history-length', which see.")
1579 (defvar minibuffer-history-sexp-flag nil
1580 "Control whether history list elements are expressions or strings.
1581 If the value of this variable equals current minibuffer depth,
1582 they are expressions; otherwise they are strings.
1583 \(That convention is designed to do the right thing for
1584 recursive uses of the minibuffer.)")
1585 (setq minibuffer-history-variable
'minibuffer-history
)
1586 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1587 (defvar minibuffer-history-search-history nil
)
1589 (defvar minibuffer-text-before-history nil
1590 "Text that was in this minibuffer before any history commands.
1591 This is nil if there have not yet been any history commands
1592 in this use of the minibuffer.")
1594 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1596 (defun minibuffer-history-initialize ()
1597 (setq minibuffer-text-before-history nil
))
1599 (defun minibuffer-avoid-prompt (_new _old
)
1600 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1601 (constrain-to-field nil
(point-max)))
1603 (defcustom minibuffer-history-case-insensitive-variables nil
1604 "Minibuffer history variables for which matching should ignore case.
1605 If a history variable is a member of this list, then the
1606 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1607 commands ignore case when searching it, regardless of `case-fold-search'."
1608 :type
'(repeat variable
)
1611 (defun previous-matching-history-element (regexp n
)
1612 "Find the previous history element that matches REGEXP.
1613 \(Previous history elements refer to earlier actions.)
1614 With prefix argument N, search for Nth previous match.
1615 If N is negative, find the next or Nth next match.
1616 Normally, history elements are matched case-insensitively if
1617 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1618 makes the search case-sensitive.
1619 See also `minibuffer-history-case-insensitive-variables'."
1621 (let* ((enable-recursive-minibuffers t
)
1622 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1624 minibuffer-local-map
1626 'minibuffer-history-search-history
1627 (car minibuffer-history-search-history
))))
1628 ;; Use the last regexp specified, by default, if input is empty.
1629 (list (if (string= regexp
"")
1630 (if minibuffer-history-search-history
1631 (car minibuffer-history-search-history
)
1632 (user-error "No previous history search regexp"))
1634 (prefix-numeric-value current-prefix-arg
))))
1636 (if (and (zerop minibuffer-history-position
)
1637 (null minibuffer-text-before-history
))
1638 (setq minibuffer-text-before-history
1639 (minibuffer-contents-no-properties)))
1640 (let ((history (symbol-value minibuffer-history-variable
))
1642 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1643 ;; On some systems, ignore case for file names.
1644 (if (memq minibuffer-history-variable
1645 minibuffer-history-case-insensitive-variables
)
1647 ;; Respect the user's setting for case-fold-search:
1653 (pos minibuffer-history-position
))
1656 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1657 (when (= pos prevpos
)
1658 (user-error (if (= pos
1)
1659 "No later matching history item"
1660 "No earlier matching history item")))
1662 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1663 (let ((print-level nil
))
1664 (prin1-to-string (nth (1- pos
) history
)))
1665 (nth (1- pos
) history
)))
1668 (and (string-match regexp match-string
)
1670 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1671 (match-beginning 1))))
1673 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1674 (setq minibuffer-history-position pos
)
1675 (goto-char (point-max))
1676 (delete-minibuffer-contents)
1677 (insert match-string
)
1678 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1679 (if (memq (car (car command-history
)) '(previous-matching-history-element
1680 next-matching-history-element
))
1681 (setq command-history
(cdr command-history
))))
1683 (defun next-matching-history-element (regexp n
)
1684 "Find the next history element that matches REGEXP.
1685 \(The next history element refers to a more recent action.)
1686 With prefix argument N, search for Nth next match.
1687 If N is negative, find the previous or Nth previous match.
1688 Normally, history elements are matched case-insensitively if
1689 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1690 makes the search case-sensitive."
1692 (let* ((enable-recursive-minibuffers t
)
1693 (regexp (read-from-minibuffer "Next element matching (regexp): "
1695 minibuffer-local-map
1697 'minibuffer-history-search-history
1698 (car minibuffer-history-search-history
))))
1699 ;; Use the last regexp specified, by default, if input is empty.
1700 (list (if (string= regexp
"")
1701 (if minibuffer-history-search-history
1702 (car minibuffer-history-search-history
)
1703 (user-error "No previous history search regexp"))
1705 (prefix-numeric-value current-prefix-arg
))))
1706 (previous-matching-history-element regexp
(- n
)))
1708 (defvar minibuffer-temporary-goal-position nil
)
1710 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
1711 "Function run by `goto-history-element' before consuming default values.
1712 This is useful to dynamically add more elements to the list of default values
1713 when `goto-history-element' reaches the end of this list.
1714 Before calling this function `goto-history-element' sets the variable
1715 `minibuffer-default-add-done' to t, so it will call this function only
1716 once. In special cases, when this function needs to be called more
1717 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1718 overriding the setting of this variable to t in `goto-history-element'.")
1720 (defvar minibuffer-default-add-done nil
1721 "When nil, add more elements to the end of the list of default values.
1722 The value nil causes `goto-history-element' to add more elements to
1723 the list of defaults when it reaches the end of this list. It does
1724 this by calling a function defined by `minibuffer-default-add-function'.")
1726 (make-variable-buffer-local 'minibuffer-default-add-done
)
1728 (defun minibuffer-default-add-completions ()
1729 "Return a list of all completions without the default value.
1730 This function is used to add all elements of the completion table to
1731 the end of the list of defaults just after the default value."
1732 (let ((def minibuffer-default
)
1733 (all (all-completions ""
1734 minibuffer-completion-table
1735 minibuffer-completion-predicate
)))
1738 (cons def
(delete def all
)))))
1740 (defun goto-history-element (nabs)
1741 "Puts element of the minibuffer history in the minibuffer.
1742 The argument NABS specifies the absolute history position."
1744 (when (and (not minibuffer-default-add-done
)
1745 (functionp minibuffer-default-add-function
)
1746 (< nabs
(- (if (listp minibuffer-default
)
1747 (length minibuffer-default
)
1749 (setq minibuffer-default-add-done t
1750 minibuffer-default
(funcall minibuffer-default-add-function
)))
1751 (let ((minimum (if minibuffer-default
1752 (- (if (listp minibuffer-default
)
1753 (length minibuffer-default
)
1756 elt minibuffer-returned-to-present
)
1757 (if (and (zerop minibuffer-history-position
)
1758 (null minibuffer-text-before-history
))
1759 (setq minibuffer-text-before-history
1760 (minibuffer-contents-no-properties)))
1761 (if (< nabs minimum
)
1762 (user-error (if minibuffer-default
1763 "End of defaults; no next item"
1764 "End of history; no default available")))
1765 (if (> nabs
(length (symbol-value minibuffer-history-variable
)))
1766 (user-error "Beginning of history; no preceding item"))
1767 (unless (memq last-command
'(next-history-element
1768 previous-history-element
))
1769 (let ((prompt-end (minibuffer-prompt-end)))
1770 (set (make-local-variable 'minibuffer-temporary-goal-position
)
1771 (cond ((<= (point) prompt-end
) prompt-end
)
1774 (goto-char (point-max))
1775 (delete-minibuffer-contents)
1776 (setq minibuffer-history-position nabs
)
1778 (setq elt
(if (listp minibuffer-default
)
1779 (nth (1- (abs nabs
)) minibuffer-default
)
1780 minibuffer-default
)))
1782 (setq elt
(or minibuffer-text-before-history
""))
1783 (setq minibuffer-returned-to-present t
)
1784 (setq minibuffer-text-before-history nil
))
1785 (t (setq elt
(nth (1- minibuffer-history-position
)
1786 (symbol-value minibuffer-history-variable
)))))
1788 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1789 (not minibuffer-returned-to-present
))
1790 (let ((print-level nil
))
1791 (prin1-to-string elt
))
1793 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
1795 (defun next-history-element (n)
1796 "Puts next element of the minibuffer history in the minibuffer.
1797 With argument N, it uses the Nth following element."
1800 (goto-history-element (- minibuffer-history-position n
))))
1802 (defun previous-history-element (n)
1803 "Puts previous element of the minibuffer history in the minibuffer.
1804 With argument N, it uses the Nth previous element."
1807 (goto-history-element (+ minibuffer-history-position n
))))
1809 (defun next-complete-history-element (n)
1810 "Get next history element which completes the minibuffer before the point.
1811 The contents of the minibuffer after the point are deleted, and replaced
1812 by the new completion."
1814 (let ((point-at-start (point)))
1815 (next-matching-history-element
1817 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1819 ;; next-matching-history-element always puts us at (point-min).
1820 ;; Move to the position we were at before changing the buffer contents.
1821 ;; This is still sensible, because the text before point has not changed.
1822 (goto-char point-at-start
)))
1824 (defun previous-complete-history-element (n)
1826 Get previous history element which completes the minibuffer before the point.
1827 The contents of the minibuffer after the point are deleted, and replaced
1828 by the new completion."
1830 (next-complete-history-element (- n
)))
1832 ;; For compatibility with the old subr of the same name.
1833 (defun minibuffer-prompt-width ()
1834 "Return the display width of the minibuffer prompt.
1835 Return 0 if current buffer is not a minibuffer."
1836 ;; Return the width of everything before the field at the end of
1837 ;; the buffer; this should be 0 for normal buffers.
1838 (1- (minibuffer-prompt-end)))
1840 ;; isearch minibuffer history
1841 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
1843 (defvar minibuffer-history-isearch-message-overlay
)
1844 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
1846 (defun minibuffer-history-isearch-setup ()
1847 "Set up a minibuffer for using isearch to search the minibuffer history.
1848 Intended to be added to `minibuffer-setup-hook'."
1849 (set (make-local-variable 'isearch-search-fun-function
)
1850 'minibuffer-history-isearch-search
)
1851 (set (make-local-variable 'isearch-message-function
)
1852 'minibuffer-history-isearch-message
)
1853 (set (make-local-variable 'isearch-wrap-function
)
1854 'minibuffer-history-isearch-wrap
)
1855 (set (make-local-variable 'isearch-push-state-function
)
1856 'minibuffer-history-isearch-push-state
)
1857 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
1859 (defun minibuffer-history-isearch-end ()
1860 "Clean up the minibuffer after terminating isearch in the minibuffer."
1861 (if minibuffer-history-isearch-message-overlay
1862 (delete-overlay minibuffer-history-isearch-message-overlay
)))
1864 (defun minibuffer-history-isearch-search ()
1865 "Return the proper search function, for isearch in minibuffer history."
1866 (lambda (string bound noerror
)
1868 ;; Use standard functions to search within minibuffer text
1869 (isearch-search-fun-default))
1871 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1872 ;; searching forward. Lazy-highlight calls this lambda with the
1873 ;; bound arg, so skip the minibuffer prompt.
1874 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
1875 (goto-char (minibuffer-prompt-end)))
1877 ;; 1. First try searching in the initial minibuffer text
1878 (funcall search-fun string
1879 (if isearch-forward bound
(minibuffer-prompt-end))
1881 ;; 2. If the above search fails, start putting next/prev history
1882 ;; elements in the minibuffer successively, and search the string
1883 ;; in them. Do this only when bound is nil (i.e. not while
1884 ;; lazy-highlighting search strings in the current minibuffer text).
1889 (cond (isearch-forward
1890 (next-history-element 1)
1891 (goto-char (minibuffer-prompt-end)))
1893 (previous-history-element 1)
1894 (goto-char (point-max))))
1895 (setq isearch-barrier
(point) isearch-opoint
(point))
1896 ;; After putting the next/prev history element, search
1897 ;; the string in them again, until next-history-element
1898 ;; or previous-history-element raises an error at the
1899 ;; beginning/end of history.
1900 (setq found
(funcall search-fun string
1901 (unless isearch-forward
1902 ;; For backward search, don't search
1903 ;; in the minibuffer prompt
1904 (minibuffer-prompt-end))
1906 ;; Return point of the new search result
1908 ;; Return nil when next(prev)-history-element fails
1911 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
1912 "Display the minibuffer history search prompt.
1913 If there are no search errors, this function displays an overlay with
1914 the isearch prompt which replaces the original minibuffer prompt.
1915 Otherwise, it displays the standard isearch message returned from
1916 the function `isearch-message'."
1917 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
1918 ;; Use standard function `isearch-message' when not in the minibuffer,
1919 ;; or search fails, or has an error (like incomplete regexp).
1920 ;; This function overwrites minibuffer text with isearch message,
1921 ;; so it's possible to see what is wrong in the search string.
1922 (isearch-message c-q-hack ellipsis
)
1923 ;; Otherwise, put the overlay with the standard isearch prompt over
1924 ;; the initial minibuffer prompt.
1925 (if (overlayp minibuffer-history-isearch-message-overlay
)
1926 (move-overlay minibuffer-history-isearch-message-overlay
1927 (point-min) (minibuffer-prompt-end))
1928 (setq minibuffer-history-isearch-message-overlay
1929 (make-overlay (point-min) (minibuffer-prompt-end)))
1930 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
1931 (overlay-put minibuffer-history-isearch-message-overlay
1932 'display
(isearch-message-prefix c-q-hack ellipsis
))
1933 ;; And clear any previous isearch message.
1936 (defun minibuffer-history-isearch-wrap ()
1937 "Wrap the minibuffer history search when search fails.
1938 Move point to the first history element for a forward search,
1939 or to the last history element for a backward search."
1940 ;; When `minibuffer-history-isearch-search' fails on reaching the
1941 ;; beginning/end of the history, wrap the search to the first/last
1942 ;; minibuffer history element.
1944 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
1945 (goto-history-element 0))
1946 (setq isearch-success t
)
1947 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
1949 (defun minibuffer-history-isearch-push-state ()
1950 "Save a function restoring the state of minibuffer history search.
1951 Save `minibuffer-history-position' to the additional state parameter
1952 in the search status stack."
1953 (let ((pos minibuffer-history-position
))
1955 (minibuffer-history-isearch-pop-state cmd pos
))))
1957 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos
)
1958 "Restore the minibuffer history search state.
1959 Go to the history element by the absolute history position HIST-POS."
1960 (goto-history-element hist-pos
))
1963 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1964 (define-obsolete-function-alias 'advertised-undo
'undo
"23.2")
1966 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
1967 "Table mapping redo records to the corresponding undo one.
1968 A redo record for undo-in-region maps to t.
1969 A redo record for ordinary undo maps to the following (earlier) undo.")
1971 (defvar undo-in-region nil
1972 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1974 (defvar undo-no-redo nil
1975 "If t, `undo' doesn't go through redo entries.")
1977 (defvar pending-undo-list nil
1978 "Within a run of consecutive undo commands, list remaining to be undone.
1979 If t, we undid all the way to the end of it.")
1981 (defun undo (&optional arg
)
1982 "Undo some previous changes.
1983 Repeat this command to undo more changes.
1984 A numeric ARG serves as a repeat count.
1986 In Transient Mark mode when the mark is active, only undo changes within
1987 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1988 as an argument limits undo to changes within the current region."
1990 ;; Make last-command indicate for the next command that this was an undo.
1991 ;; That way, another undo will undo more.
1992 ;; If we get to the end of the undo history and get an error,
1993 ;; another undo command will find the undo history empty
1994 ;; and will get another error. To begin undoing the undos,
1995 ;; you must type some other command.
1996 (let* ((modified (buffer-modified-p))
1997 ;; For an indirect buffer, look in the base buffer for the
1999 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2000 (recent-save (with-current-buffer base-buffer
2001 (recent-auto-save-p)))
2003 ;; If we get an error in undo-start,
2004 ;; the next command should not be a "consecutive undo".
2005 ;; So set `this-command' to something other than `undo'.
2006 (setq this-command
'undo-start
)
2008 (unless (and (eq last-command
'undo
)
2009 (or (eq pending-undo-list t
)
2010 ;; If something (a timer or filter?) changed the buffer
2011 ;; since the previous command, don't continue the undo seq.
2012 (let ((list buffer-undo-list
))
2013 (while (eq (car list
) nil
)
2014 (setq list
(cdr list
)))
2015 ;; If the last undo record made was made by undo
2016 ;; it shows nothing else happened in between.
2017 (gethash list undo-equiv-table
))))
2018 (setq undo-in-region
2019 (or (region-active-p) (and arg
(not (numberp arg
)))))
2021 (undo-start (region-beginning) (region-end))
2023 ;; get rid of initial undo boundary
2025 ;; If we got this far, the next command should be a consecutive undo.
2026 (setq this-command
'undo
)
2027 ;; Check to see whether we're hitting a redo record, and if
2028 ;; so, ask the user whether she wants to skip the redo/undo pair.
2029 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
2030 (or (eq (selected-window) (minibuffer-window))
2031 (setq message
(format "%s%s!"
2032 (if (or undo-no-redo
(not equiv
))
2034 (if undo-in-region
" in region" ""))))
2035 (when (and (consp equiv
) undo-no-redo
)
2036 ;; The equiv entry might point to another redo record if we have done
2037 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2038 (while (let ((next (gethash equiv undo-equiv-table
)))
2039 (if next
(setq equiv next
))))
2040 (setq pending-undo-list equiv
)))
2043 (prefix-numeric-value arg
)
2045 ;; Record the fact that the just-generated undo records come from an
2046 ;; undo operation--that is, they are redo records.
2047 ;; In the ordinary case (not within a region), map the redo
2048 ;; record to the following undos.
2049 ;; I don't know how to do that in the undo-in-region case.
2050 (let ((list buffer-undo-list
))
2051 ;; Strip any leading undo boundaries there might be, like we do
2052 ;; above when checking.
2053 (while (eq (car list
) nil
)
2054 (setq list
(cdr list
)))
2055 (puthash list
(if undo-in-region t pending-undo-list
)
2057 ;; Don't specify a position in the undo record for the undo command.
2058 ;; Instead, undoing this should move point to where the change is.
2059 (let ((tail buffer-undo-list
)
2062 (when (integerp (car tail
))
2063 (let ((pos (car tail
)))
2065 (setcdr prev
(cdr tail
))
2066 (setq buffer-undo-list
(cdr tail
)))
2067 (setq tail
(cdr tail
))
2069 (if (eq pos
(car tail
))
2071 (setcdr prev
(cdr tail
))
2072 (setq buffer-undo-list
(cdr tail
)))
2074 (setq tail
(cdr tail
)))
2076 (setq prev tail tail
(cdr tail
))))
2077 ;; Record what the current undo list says,
2078 ;; so the next command can tell if the buffer was modified in between.
2079 (and modified
(not (buffer-modified-p))
2080 (with-current-buffer base-buffer
2081 (delete-auto-save-file-if-necessary recent-save
)))
2082 ;; Display a message announcing success.
2084 (message "%s" message
))))
2086 (defun buffer-disable-undo (&optional buffer
)
2087 "Make BUFFER stop keeping undo information.
2088 No argument or nil as argument means do this for the current buffer."
2090 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
2091 (setq buffer-undo-list t
)))
2093 (defun undo-only (&optional arg
)
2094 "Undo some previous changes.
2095 Repeat this command to undo more changes.
2096 A numeric ARG serves as a repeat count.
2097 Contrary to `undo', this will not redo a previous undo."
2099 (let ((undo-no-redo t
)) (undo arg
)))
2101 (defvar undo-in-progress nil
2102 "Non-nil while performing an undo.
2103 Some change-hooks test this variable to do something different.")
2105 (defun undo-more (n)
2106 "Undo back N undo-boundaries beyond what was already undone recently.
2107 Call `undo-start' to get ready to undo recent changes,
2108 then call `undo-more' one or more times to undo them."
2109 (or (listp pending-undo-list
)
2110 (user-error (concat "No further undo information"
2111 (and undo-in-region
" for region"))))
2112 (let ((undo-in-progress t
))
2113 ;; Note: The following, while pulling elements off
2114 ;; `pending-undo-list' will call primitive change functions which
2115 ;; will push more elements onto `buffer-undo-list'.
2116 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
2117 (if (null pending-undo-list
)
2118 (setq pending-undo-list t
))))
2120 (defun primitive-undo (n list
)
2121 "Undo N records from the front of the list LIST.
2122 Return what remains of the list."
2124 ;; This is a good feature, but would make undo-start
2125 ;; unable to do what is expected.
2126 ;;(when (null (car (list)))
2127 ;; ;; If the head of the list is a boundary, it is the boundary
2128 ;; ;; preceding this command. Get rid of it and don't count it.
2129 ;; (setq list (cdr list))))
2132 ;; In a writable buffer, enable undoing read-only text that is
2133 ;; so because of text properties.
2134 (inhibit-read-only t
)
2135 ;; Don't let `intangible' properties interfere with undo.
2136 (inhibit-point-motion-hooks t
)
2137 ;; We use oldlist only to check for EQ. ++kfs
2138 (oldlist buffer-undo-list
)
2142 (while (setq next
(pop list
)) ;Exit inner loop at undo boundary.
2143 ;; Handle an integer by setting point to that value.
2145 ((pred integerp
) (goto-char next
))
2146 ;; Element (t . TIME) records previous modtime.
2147 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2148 ;; UNKNOWN_MODTIME_NSECS.
2150 ;; If this records an obsolete save
2151 ;; (not matching the actual disk file)
2152 ;; then don't mark unmodified.
2153 (when (or (equal time
(visited-file-modtime))
2155 (equal (list (car time
) (cdr time
))
2156 (visited-file-modtime))))
2157 (when (fboundp 'unlock-buffer
)
2159 (set-buffer-modified-p nil
)))
2160 ;; Element (nil PROP VAL BEG . END) is property change.
2161 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2162 (when (or (> (point-min) beg
) (< (point-max) end
))
2163 (error "Changes to be undone are outside visible portion of buffer"))
2164 (put-text-property beg end prop val
))
2165 ;; Element (BEG . END) means range was inserted.
2166 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2167 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2168 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2169 (when (or (> (point-min) beg
) (< (point-max) end
))
2170 (error "Changes to be undone are outside visible portion of buffer"))
2171 ;; Set point first thing, so that undoing this undo
2172 ;; does not send point back to where it is now.
2174 (delete-region beg end
))
2175 ;; Element (apply FUN . ARGS) means call FUN to undo.
2176 (`(apply .
,fun-args
)
2177 (let ((currbuff (current-buffer)))
2178 (if (integerp (car fun-args
))
2179 ;; Long format: (apply DELTA START END FUN . ARGS).
2180 (pcase-let* ((`(,delta
,start
,end
,fun .
,args
) fun-args
)
2181 (start-mark (copy-marker start nil
))
2182 (end-mark (copy-marker end t
)))
2183 (when (or (> (point-min) start
) (< (point-max) end
))
2184 (error "Changes to be undone are outside visible portion of buffer"))
2185 (apply fun args
) ;; Use `save-current-buffer'?
2186 ;; Check that the function did what the entry
2187 ;; said it would do.
2188 (unless (and (= start start-mark
)
2189 (= (+ delta end
) end-mark
))
2190 (error "Changes to be undone by function different than announced"))
2191 (set-marker start-mark nil
)
2192 (set-marker end-mark nil
))
2194 (unless (eq currbuff
(current-buffer))
2195 (error "Undo function switched buffer"))
2196 (setq did-apply t
)))
2197 ;; Element (STRING . POS) means STRING was deleted.
2198 (`(,(and string
(pred stringp
)) .
,(and pos
(pred integerp
)))
2199 (when (let ((apos (abs pos
)))
2200 (or (< apos
(point-min)) (> apos
(point-max))))
2201 (error "Changes to be undone are outside visible portion of buffer"))
2207 ;; Now that we record marker adjustments
2208 ;; (caused by deletion) for undo,
2209 ;; we should always insert after markers,
2210 ;; so that undoing the marker adjustments
2211 ;; put the markers back in the right place.
2214 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2215 (`(,(and marker
(pred markerp
)) .
,(and offset
(pred integerp
)))
2216 (when (marker-buffer marker
)
2219 (marker-buffer marker
))))
2220 (_ (error "Unrecognized entry in undo list %S" next
))))
2221 (setq arg
(1- arg
)))
2222 ;; Make sure an apply entry produces at least one undo entry,
2223 ;; so the test in `undo' for continuing an undo series
2226 (eq oldlist buffer-undo-list
))
2227 (setq buffer-undo-list
2228 (cons (list 'apply
'cdr nil
) buffer-undo-list
))))
2231 ;; Deep copy of a list
2232 (defun undo-copy-list (list)
2233 "Make a copy of undo list LIST."
2234 (mapcar 'undo-copy-list-1 list
))
2236 (defun undo-copy-list-1 (elt)
2238 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
2241 (defun undo-start (&optional beg end
)
2242 "Set `pending-undo-list' to the front of the undo list.
2243 The next call to `undo-more' will undo the most recently made change.
2244 If BEG and END are specified, then only undo elements
2245 that apply to text between BEG and END are used; other undo elements
2246 are ignored. If BEG and END are nil, all undo elements are used."
2247 (if (eq buffer-undo-list t
)
2248 (user-error "No undo information in this buffer"))
2249 (setq pending-undo-list
2250 (if (and beg end
(not (= beg end
)))
2251 (undo-make-selective-list (min beg end
) (max beg end
))
2254 (defvar undo-adjusted-markers
)
2256 (defun undo-make-selective-list (start end
)
2257 "Return a list of undo elements for the region START to END.
2258 The elements come from `buffer-undo-list', but we keep only
2259 the elements inside this region, and discard those outside this region.
2260 If we find an element that crosses an edge of this region,
2261 we stop and ignore all further elements."
2262 (let ((undo-list-copy (undo-copy-list buffer-undo-list
))
2263 (undo-list (list nil
))
2264 undo-adjusted-markers
2266 undo-elt temp-undo-list delta
)
2267 (while undo-list-copy
2268 (setq undo-elt
(car undo-list-copy
))
2270 (cond ((and (consp undo-elt
) (eq (car undo-elt
) t
))
2271 ;; This is a "was unmodified" element.
2272 ;; Keep it if we have kept everything thus far.
2273 (not some-rejected
))
2275 (undo-elt-in-region undo-elt start end
)))))
2278 (setq end
(+ end
(cdr (undo-delta undo-elt
))))
2279 ;; Don't put two nils together in the list
2280 (if (not (and (eq (car undo-list
) nil
)
2282 (setq undo-list
(cons undo-elt undo-list
))))
2283 (if (undo-elt-crosses-region undo-elt start end
)
2284 (setq undo-list-copy nil
)
2285 (setq some-rejected t
)
2286 (setq temp-undo-list
(cdr undo-list-copy
))
2287 (setq delta
(undo-delta undo-elt
))
2289 (when (/= (cdr delta
) 0)
2290 (let ((position (car delta
))
2291 (offset (cdr delta
)))
2293 ;; Loop down the earlier events adjusting their buffer
2294 ;; positions to reflect the fact that a change to the buffer
2295 ;; isn't being undone. We only need to process those element
2296 ;; types which undo-elt-in-region will return as being in
2297 ;; the region since only those types can ever get into the
2300 (while temp-undo-list
2301 (setq undo-elt
(car temp-undo-list
))
2302 (cond ((integerp undo-elt
)
2303 (if (>= undo-elt position
)
2304 (setcar temp-undo-list
(- undo-elt offset
))))
2305 ((atom undo-elt
) nil
)
2306 ((stringp (car undo-elt
))
2307 ;; (TEXT . POSITION)
2308 (let ((text-pos (abs (cdr undo-elt
)))
2309 (point-at-end (< (cdr undo-elt
) 0 )))
2310 (if (>= text-pos position
)
2311 (setcdr undo-elt
(* (if point-at-end -
1 1)
2312 (- text-pos offset
))))))
2313 ((integerp (car undo-elt
))
2315 (when (>= (car undo-elt
) position
)
2316 (setcar undo-elt
(- (car undo-elt
) offset
))
2317 (setcdr undo-elt
(- (cdr undo-elt
) offset
))))
2318 ((null (car undo-elt
))
2319 ;; (nil PROPERTY VALUE BEG . END)
2320 (let ((tail (nthcdr 3 undo-elt
)))
2321 (when (>= (car tail
) position
)
2322 (setcar tail
(- (car tail
) offset
))
2323 (setcdr tail
(- (cdr tail
) offset
))))))
2324 (setq temp-undo-list
(cdr temp-undo-list
))))))))
2325 (setq undo-list-copy
(cdr undo-list-copy
)))
2326 (nreverse undo-list
)))
2328 (defun undo-elt-in-region (undo-elt start end
)
2329 "Determine whether UNDO-ELT falls inside the region START ... END.
2330 If it crosses the edge, we return nil."
2331 (cond ((integerp undo-elt
)
2332 (and (>= undo-elt start
)
2338 ((stringp (car undo-elt
))
2339 ;; (TEXT . POSITION)
2340 (and (>= (abs (cdr undo-elt
)) start
)
2341 (< (abs (cdr undo-elt
)) end
)))
2342 ((and (consp undo-elt
) (markerp (car undo-elt
)))
2343 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
2344 ;; See if MARKER is inside the region.
2345 (let ((alist-elt (assq (car undo-elt
) undo-adjusted-markers
)))
2347 (setq alist-elt
(cons (car undo-elt
)
2348 (marker-position (car undo-elt
))))
2349 (setq undo-adjusted-markers
2350 (cons alist-elt undo-adjusted-markers
)))
2351 (and (cdr alist-elt
)
2352 (>= (cdr alist-elt
) start
)
2353 (<= (cdr alist-elt
) end
))))
2354 ((null (car undo-elt
))
2355 ;; (nil PROPERTY VALUE BEG . END)
2356 (let ((tail (nthcdr 3 undo-elt
)))
2357 (and (>= (car tail
) start
)
2358 (<= (cdr tail
) end
))))
2359 ((integerp (car undo-elt
))
2361 (and (>= (car undo-elt
) start
)
2362 (<= (cdr undo-elt
) end
)))))
2364 (defun undo-elt-crosses-region (undo-elt start end
)
2365 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2366 This assumes we have already decided that UNDO-ELT
2367 is not *inside* the region START...END."
2368 (cond ((atom undo-elt
) nil
)
2369 ((null (car undo-elt
))
2370 ;; (nil PROPERTY VALUE BEG . END)
2371 (let ((tail (nthcdr 3 undo-elt
)))
2372 (and (< (car tail
) end
)
2373 (> (cdr tail
) start
))))
2374 ((integerp (car undo-elt
))
2376 (and (< (car undo-elt
) end
)
2377 (> (cdr undo-elt
) start
)))))
2379 ;; Return the first affected buffer position and the delta for an undo element
2380 ;; delta is defined as the change in subsequent buffer positions if we *did*
2382 (defun undo-delta (undo-elt)
2383 (if (consp undo-elt
)
2384 (cond ((stringp (car undo-elt
))
2385 ;; (TEXT . POSITION)
2386 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
2387 ((integerp (car undo-elt
))
2389 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
2394 (defcustom undo-ask-before-discard nil
2395 "If non-nil ask about discarding undo info for the current command.
2396 Normally, Emacs discards the undo info for the current command if
2397 it exceeds `undo-outer-limit'. But if you set this option
2398 non-nil, it asks in the echo area whether to discard the info.
2399 If you answer no, there is a slight risk that Emacs might crash, so
2400 only do it if you really want to undo the command.
2402 This option is mainly intended for debugging. You have to be
2403 careful if you use it for other purposes. Garbage collection is
2404 inhibited while the question is asked, meaning that Emacs might
2405 leak memory. So you should make sure that you do not wait
2406 excessively long before answering the question."
2411 (defvar undo-extra-outer-limit nil
2412 "If non-nil, an extra level of size that's ok in an undo item.
2413 We don't ask the user about truncating the undo list until the
2414 current item gets bigger than this amount.
2416 This variable only matters if `undo-ask-before-discard' is non-nil.")
2417 (make-variable-buffer-local 'undo-extra-outer-limit
)
2419 ;; When the first undo batch in an undo list is longer than
2420 ;; undo-outer-limit, this function gets called to warn the user that
2421 ;; the undo info for the current command was discarded. Garbage
2422 ;; collection is inhibited around the call, so it had better not do a
2424 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
2425 (defun undo-outer-limit-truncate (size)
2426 (if undo-ask-before-discard
2427 (when (or (null undo-extra-outer-limit
)
2428 (> size undo-extra-outer-limit
))
2429 ;; Don't ask the question again unless it gets even bigger.
2430 ;; This applies, in particular, if the user quits from the question.
2431 ;; Such a quit quits out of GC, but something else will call GC
2432 ;; again momentarily. It will call this function again,
2433 ;; but we don't want to ask the question again.
2434 (setq undo-extra-outer-limit
(+ size
50000))
2435 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
2436 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2437 (buffer-name) size
)))
2438 (progn (setq buffer-undo-list nil
)
2439 (setq undo-extra-outer-limit nil
)
2442 (display-warning '(undo discard-info
)
2444 (format "Buffer `%s' undo info was %d bytes long.\n"
2446 "The undo info was discarded because it exceeded \
2449 This is normal if you executed a command that made a huge change
2450 to the buffer. In that case, to prevent similar problems in the
2451 future, set `undo-outer-limit' to a value that is large enough to
2452 cover the maximum size of normal changes you expect a single
2453 command to make, but not so large that it might exceed the
2454 maximum memory allotted to Emacs.
2456 If you did not execute any such command, the situation is
2457 probably due to a bug and you should report it.
2459 You can disable the popping up of this buffer by adding the entry
2460 \(undo discard-info) to the user option `warning-suppress-types',
2461 which is defined in the `warnings' library.\n")
2463 (setq buffer-undo-list nil
)
2466 (defvar shell-command-history nil
2467 "History list for some commands that read shell commands.
2469 Maximum length of the history list is determined by the value
2470 of `history-length', which see.")
2472 (defvar shell-command-switch
(purecopy "-c")
2473 "Switch used to have the shell execute its command line argument.")
2475 (defvar shell-command-default-error-buffer nil
2476 "Buffer name for `shell-command' and `shell-command-on-region' error output.
2477 This buffer is used when `shell-command' or `shell-command-on-region'
2478 is run interactively. A value of nil means that output to stderr and
2479 stdout will be intermixed in the output stream.")
2481 (declare-function mailcap-file-default-commands
"mailcap" (files))
2482 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
2484 (defun minibuffer-default-add-shell-commands ()
2485 "Return a list of all commands associated with the current file.
2486 This function is used to add all related commands retrieved by `mailcap'
2487 to the end of the list of defaults just after the default value."
2489 (let* ((filename (if (listp minibuffer-default
)
2490 (car minibuffer-default
)
2491 minibuffer-default
))
2492 (commands (and filename
(require 'mailcap nil t
)
2493 (mailcap-file-default-commands (list filename
)))))
2494 (setq commands
(mapcar (lambda (command)
2495 (concat command
" " filename
))
2497 (if (listp minibuffer-default
)
2498 (append minibuffer-default commands
)
2499 (cons minibuffer-default commands
))))
2501 (declare-function shell-completion-vars
"shell" ())
2503 (defvar minibuffer-local-shell-command-map
2504 (let ((map (make-sparse-keymap)))
2505 (set-keymap-parent map minibuffer-local-map
)
2506 (define-key map
"\t" 'completion-at-point
)
2508 "Keymap used for completing shell commands in minibuffer.")
2510 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
2511 "Read a shell command from the minibuffer.
2512 The arguments are the same as the ones of `read-from-minibuffer',
2513 except READ and KEYMAP are missing and HIST defaults
2514 to `shell-command-history'."
2516 (minibuffer-with-setup-hook
2518 (shell-completion-vars)
2519 (set (make-local-variable 'minibuffer-default-add-function
)
2520 'minibuffer-default-add-shell-commands
))
2521 (apply 'read-from-minibuffer prompt initial-contents
2522 minibuffer-local-shell-command-map
2524 (or hist
'shell-command-history
)
2527 (defcustom async-shell-command-buffer
'confirm-new-buffer
2528 "What to do when the output buffer is used by another shell command.
2529 This option specifies how to resolve the conflict where a new command
2530 wants to direct its output to the buffer `*Async Shell Command*',
2531 but this buffer is already taken by another running shell command.
2533 The value `confirm-kill-process' is used to ask for confirmation before
2534 killing the already running process and running a new process
2535 in the same buffer, `confirm-new-buffer' for confirmation before running
2536 the command in a new buffer with a name other than the default buffer name,
2537 `new-buffer' for doing the same without confirmation,
2538 `confirm-rename-buffer' for confirmation before renaming the existing
2539 output buffer and running a new command in the default buffer,
2540 `rename-buffer' for doing the same without confirmation."
2541 :type
'(choice (const :tag
"Confirm killing of running command"
2542 confirm-kill-process
)
2543 (const :tag
"Confirm creation of a new buffer"
2545 (const :tag
"Create a new buffer"
2547 (const :tag
"Confirm renaming of existing buffer"
2548 confirm-rename-buffer
)
2549 (const :tag
"Rename the existing buffer"
2554 (defun async-shell-command (command &optional output-buffer error-buffer
)
2555 "Execute string COMMAND asynchronously in background.
2557 Like `shell-command', but adds `&' at the end of COMMAND
2558 to execute it asynchronously.
2560 The output appears in the buffer `*Async Shell Command*'.
2561 That buffer is in shell mode.
2563 In Elisp, you will often be better served by calling `start-process'
2564 directly, since it offers more control and does not impose the use of a
2565 shell (with its need to quote arguments)."
2568 (read-shell-command "Async shell command: " nil nil
2572 ((eq major-mode
'dired-mode
)
2573 (dired-get-filename nil t
)))))
2574 (and filename
(file-relative-name filename
))))
2576 shell-command-default-error-buffer
))
2577 (unless (string-match "&[ \t]*\\'" command
)
2578 (setq command
(concat command
" &")))
2579 (shell-command command output-buffer error-buffer
))
2581 (defun shell-command (command &optional output-buffer error-buffer
)
2582 "Execute string COMMAND in inferior shell; display output, if any.
2583 With prefix argument, insert the COMMAND's output at point.
2585 If COMMAND ends in `&', execute it asynchronously.
2586 The output appears in the buffer `*Async Shell Command*'.
2587 That buffer is in shell mode. You can also use
2588 `async-shell-command' that automatically adds `&'.
2590 Otherwise, COMMAND is executed synchronously. The output appears in
2591 the buffer `*Shell Command Output*'. If the output is short enough to
2592 display in the echo area (which is determined by the variables
2593 `resize-mini-windows' and `max-mini-window-height'), it is shown
2594 there, but it is nonetheless available in buffer `*Shell Command
2595 Output*' even though that buffer is not automatically displayed.
2597 To specify a coding system for converting non-ASCII characters
2598 in the shell command output, use \\[universal-coding-system-argument] \
2599 before this command.
2601 Noninteractive callers can specify coding systems by binding
2602 `coding-system-for-read' and `coding-system-for-write'.
2604 The optional second argument OUTPUT-BUFFER, if non-nil,
2605 says to put the output in some other buffer.
2606 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2607 If OUTPUT-BUFFER is not a buffer and not nil,
2608 insert output in current buffer. (This cannot be done asynchronously.)
2609 In either case, the buffer is first erased, and the output is
2610 inserted after point (leaving mark after it).
2612 If the command terminates without error, but generates output,
2613 and you did not specify \"insert it in the current buffer\",
2614 the output can be displayed in the echo area or in its buffer.
2615 If the output is short enough to display in the echo area
2616 \(determined by the variable `max-mini-window-height' if
2617 `resize-mini-windows' is non-nil), it is shown there.
2618 Otherwise,the buffer containing the output is displayed.
2620 If there is output and an error, and you did not specify \"insert it
2621 in the current buffer\", a message about the error goes at the end
2624 If there is no output, or if output is inserted in the current buffer,
2625 then `*Shell Command Output*' is deleted.
2627 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2628 or buffer name to which to direct the command's standard error output.
2629 If it is nil, error output is mingled with regular output.
2630 In an interactive call, the variable `shell-command-default-error-buffer'
2631 specifies the value of ERROR-BUFFER.
2633 In Elisp, you will often be better served by calling `call-process' or
2634 `start-process' directly, since it offers more control and does not impose
2635 the use of a shell (with its need to quote arguments)."
2639 (read-shell-command "Shell command: " nil nil
2643 ((eq major-mode
'dired-mode
)
2644 (dired-get-filename nil t
)))))
2645 (and filename
(file-relative-name filename
))))
2647 shell-command-default-error-buffer
))
2648 ;; Look for a handler in case default-directory is a remote file name.
2650 (find-file-name-handler (directory-file-name default-directory
)
2653 (funcall handler
'shell-command command output-buffer error-buffer
)
2654 (if (and output-buffer
2655 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
2656 ;; Output goes in current buffer.
2660 (expand-file-name "scor"
2661 (or small-temporary-file-directory
2662 temporary-file-directory
)))
2664 (barf-if-buffer-read-only)
2666 ;; We do not use -f for csh; we will not support broken use of
2667 ;; .cshrcs. Even the BSD csh manual says to use
2668 ;; "if ($?prompt) exit" before things which are not useful
2669 ;; non-interactively. Besides, if someone wants their other
2670 ;; aliases for shell commands then they can still have them.
2671 (call-process shell-file-name nil
2675 nil shell-command-switch command
)
2676 (when (and error-file
(file-exists-p error-file
))
2677 (if (< 0 (nth 7 (file-attributes error-file
)))
2678 (with-current-buffer (get-buffer-create error-buffer
)
2679 (let ((pos-from-end (- (point-max) (point))))
2682 ;; Do no formatting while reading error file,
2683 ;; because that can run a shell command, and we
2684 ;; don't want that to cause an infinite recursion.
2685 (format-insert-file error-file nil
)
2686 ;; Put point after the inserted errors.
2687 (goto-char (- (point-max) pos-from-end
)))
2688 (display-buffer (current-buffer))))
2689 (delete-file error-file
))
2690 ;; This is like exchange-point-and-mark, but doesn't
2691 ;; activate the mark. It is cleaner to avoid activation,
2692 ;; even though the command loop would deactivate the mark
2693 ;; because we inserted text.
2694 (goto-char (prog1 (mark t
)
2695 (set-marker (mark-marker) (point)
2696 (current-buffer)))))
2697 ;; Output goes in a separate buffer.
2698 ;; Preserve the match data in case called from a program.
2700 (if (string-match "[ \t]*&[ \t]*\\'" command
)
2701 ;; Command ending with ampersand means asynchronous.
2702 (let ((buffer (get-buffer-create
2703 (or output-buffer
"*Async Shell Command*")))
2704 (directory default-directory
)
2706 ;; Remove the ampersand.
2707 (setq command
(substring command
0 (match-beginning 0)))
2708 ;; Ask the user what to do with already running process.
2709 (setq proc
(get-buffer-process buffer
))
2712 ((eq async-shell-command-buffer
'confirm-kill-process
)
2713 ;; If will kill a process, query first.
2714 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
2716 (error "Shell command in progress")))
2717 ((eq async-shell-command-buffer
'confirm-new-buffer
)
2718 ;; If will create a new buffer, query first.
2719 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
2720 (setq buffer
(generate-new-buffer
2721 (or output-buffer
"*Async Shell Command*")))
2722 (error "Shell command in progress")))
2723 ((eq async-shell-command-buffer
'new-buffer
)
2724 ;; It will create a new buffer.
2725 (setq buffer
(generate-new-buffer
2726 (or output-buffer
"*Async Shell Command*"))))
2727 ((eq async-shell-command-buffer
'confirm-rename-buffer
)
2728 ;; If will rename the buffer, query first.
2729 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
2731 (with-current-buffer buffer
2733 (setq buffer
(get-buffer-create
2734 (or output-buffer
"*Async Shell Command*"))))
2735 (error "Shell command in progress")))
2736 ((eq async-shell-command-buffer
'rename-buffer
)
2737 ;; It will rename the buffer.
2738 (with-current-buffer buffer
2740 (setq buffer
(get-buffer-create
2741 (or output-buffer
"*Async Shell Command*"))))))
2742 (with-current-buffer buffer
2743 (setq buffer-read-only nil
)
2744 ;; Setting buffer-read-only to nil doesn't suffice
2745 ;; if some text has a non-nil read-only property,
2746 ;; which comint sometimes adds for prompts.
2747 (let ((inhibit-read-only t
))
2749 (display-buffer buffer
)
2750 (setq default-directory directory
)
2751 (setq proc
(start-process "Shell" buffer shell-file-name
2752 shell-command-switch command
))
2753 (setq mode-line-process
'(":%s"))
2754 (require 'shell
) (shell-mode)
2755 (set-process-sentinel proc
'shell-command-sentinel
)
2756 ;; Use the comint filter for proper handling of carriage motion
2757 ;; (see `comint-inhibit-carriage-motion'),.
2758 (set-process-filter proc
'comint-output-filter
)
2760 ;; Otherwise, command is executed synchronously.
2761 (shell-command-on-region (point) (point) command
2762 output-buffer nil error-buffer
)))))))
2764 (defun display-message-or-buffer (message
2765 &optional buffer-name not-this-window frame
)
2766 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2767 MESSAGE may be either a string or a buffer.
2769 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2770 the maximum height of the echo area, as defined by `max-mini-window-height'
2771 if `resize-mini-windows' is non-nil.
2773 Returns either the string shown in the echo area, or when a pop-up
2774 buffer is used, the window used to display it.
2776 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2777 name of the buffer used to display it in the case where a pop-up buffer
2778 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2779 string and it is displayed in the echo area, it is not specified whether
2780 the contents are inserted into the buffer anyway.
2782 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2783 and only used if a buffer is displayed."
2784 (cond ((and (stringp message
) (not (string-match "\n" message
)))
2785 ;; Trivial case where we can use the echo area
2786 (message "%s" message
))
2787 ((and (stringp message
)
2788 (= (string-match "\n" message
) (1- (length message
))))
2789 ;; Trivial case where we can just remove single trailing newline
2790 (message "%s" (substring message
0 (1- (length message
)))))
2793 (with-current-buffer
2794 (if (bufferp message
)
2796 (get-buffer-create (or buffer-name
"*Message*")))
2798 (unless (bufferp message
)
2803 (if (= (buffer-size) 0)
2805 (count-screen-lines nil nil nil
(minibuffer-window)))))
2807 ((and (or (<= lines
1)
2809 (if resize-mini-windows
2810 (cond ((floatp max-mini-window-height
)
2812 max-mini-window-height
))
2813 ((integerp max-mini-window-height
)
2814 max-mini-window-height
)
2818 ;; Don't use the echo area if the output buffer is
2819 ;; already displayed in the selected frame.
2820 (not (get-buffer-window (current-buffer))))
2822 (goto-char (point-max))
2825 (message "%s" (buffer-substring (point-min) (point))))
2828 (goto-char (point-min))
2829 (display-buffer (current-buffer)
2830 not-this-window frame
))))))))
2833 ;; We have a sentinel to prevent insertion of a termination message
2834 ;; in the buffer itself.
2835 (defun shell-command-sentinel (process signal
)
2836 (if (memq (process-status process
) '(exit signal
))
2838 (car (cdr (cdr (process-command process
))))
2839 (substring signal
0 -
1))))
2841 (defun shell-command-on-region (start end command
2842 &optional output-buffer replace
2843 error-buffer display-error-buffer
)
2844 "Execute string COMMAND in inferior shell with region as input.
2845 Normally display output (if any) in temp buffer `*Shell Command Output*';
2846 Prefix arg means replace the region with it. Return the exit code of
2849 To specify a coding system for converting non-ASCII characters
2850 in the input and output to the shell command, use \\[universal-coding-system-argument]
2851 before this command. By default, the input (from the current buffer)
2852 is encoded using coding-system specified by `process-coding-system-alist',
2853 falling back to `default-process-coding-system' if no match for COMMAND
2854 is found in `process-coding-system-alist'.
2856 Noninteractive callers can specify coding systems by binding
2857 `coding-system-for-read' and `coding-system-for-write'.
2859 If the command generates output, the output may be displayed
2860 in the echo area or in a buffer.
2861 If the output is short enough to display in the echo area
2862 \(determined by the variable `max-mini-window-height' if
2863 `resize-mini-windows' is non-nil), it is shown there.
2864 Otherwise it is displayed in the buffer `*Shell Command Output*'.
2865 The output is available in that buffer in both cases.
2867 If there is output and an error, a message about the error
2868 appears at the end of the output. If there is no output, or if
2869 output is inserted in the current buffer, the buffer `*Shell
2870 Command Output*' is deleted.
2872 Optional fourth arg OUTPUT-BUFFER specifies where to put the
2873 command's output. If the value is a buffer or buffer name,
2874 put the output there. If the value is nil, use the buffer
2875 `*Shell Command Output*'. Any other value, excluding nil,
2876 means to insert the output in the current buffer. In either case,
2877 the output is inserted after point (leaving mark after it).
2879 Optional fifth arg REPLACE, if non-nil, means to insert the
2880 output in place of text from START to END, putting point and mark
2883 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
2884 or buffer name to which to direct the command's standard error
2885 output. If nil, error output is mingled with regular output.
2886 When called interactively, `shell-command-default-error-buffer'
2887 is used for ERROR-BUFFER.
2889 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
2890 display the error buffer if there were any errors. When called
2891 interactively, this is t."
2892 (interactive (let (string)
2894 (error "The mark is not set now, so there is no region"))
2895 ;; Do this before calling region-beginning
2896 ;; and region-end, in case subprocess output
2897 ;; relocates them while we are in the minibuffer.
2898 (setq string
(read-shell-command "Shell command on region: "))
2899 ;; call-interactively recognizes region-beginning and
2900 ;; region-end specially, leaving them in the history.
2901 (list (region-beginning) (region-end)
2905 shell-command-default-error-buffer
2910 (expand-file-name "scor"
2911 (or small-temporary-file-directory
2912 temporary-file-directory
)))
2917 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
2918 ;; Replace specified region with output from command.
2919 (let ((swap (and replace
(< start end
))))
2920 ;; Don't muck with mark unless REPLACE says we should.
2922 (and replace
(push-mark (point) 'nomsg
))
2924 (call-process-region start end shell-file-name replace
2928 nil shell-command-switch command
))
2929 ;; It is rude to delete a buffer which the command is not using.
2930 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2931 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2932 ;; (kill-buffer shell-buffer)))
2933 ;; Don't muck with mark unless REPLACE says we should.
2934 (and replace swap
(exchange-point-and-mark)))
2935 ;; No prefix argument: put the output in a temp buffer,
2936 ;; replacing its entire contents.
2937 (let ((buffer (get-buffer-create
2938 (or output-buffer
"*Shell Command Output*"))))
2940 (if (eq buffer
(current-buffer))
2941 ;; If the input is the same buffer as the output,
2942 ;; delete everything but the specified region,
2943 ;; then replace that region with the output.
2944 (progn (setq buffer-read-only nil
)
2945 (delete-region (max start end
) (point-max))
2946 (delete-region (point-min) (min start end
))
2948 (call-process-region (point-min) (point-max)
2953 nil shell-command-switch
2955 ;; Clear the output buffer, then run the command with
2957 (let ((directory default-directory
))
2958 (with-current-buffer buffer
2959 (setq buffer-read-only nil
)
2960 (if (not output-buffer
)
2961 (setq default-directory directory
))
2964 (call-process-region start end shell-file-name nil
2966 (list buffer error-file
)
2968 nil shell-command-switch command
)))
2969 ;; Report the output.
2970 (with-current-buffer buffer
2971 (setq mode-line-process
2972 (cond ((null exit-status
)
2974 ((stringp exit-status
)
2975 (format " - Signal [%s]" exit-status
))
2976 ((not (equal 0 exit-status
))
2977 (format " - Exit [%d]" exit-status
)))))
2978 (if (with-current-buffer buffer
(> (point-max) (point-min)))
2979 ;; There's some output, display it
2980 (display-message-or-buffer buffer
)
2981 ;; No output; error?
2984 (< 0 (nth 7 (file-attributes error-file
))))
2985 (format "some error output%s"
2986 (if shell-command-default-error-buffer
2987 (format " to the \"%s\" buffer"
2988 shell-command-default-error-buffer
)
2991 (cond ((null exit-status
)
2992 (message "(Shell command failed with error)"))
2993 ((equal 0 exit-status
)
2994 (message "(Shell command succeeded with %s)"
2996 ((stringp exit-status
)
2997 (message "(Shell command killed by signal %s)"
3000 (message "(Shell command failed with code %d and %s)"
3001 exit-status output
))))
3002 ;; Don't kill: there might be useful info in the undo-log.
3003 ;; (kill-buffer buffer)
3006 (when (and error-file
(file-exists-p error-file
))
3007 (if (< 0 (nth 7 (file-attributes error-file
)))
3008 (with-current-buffer (get-buffer-create error-buffer
)
3009 (let ((pos-from-end (- (point-max) (point))))
3012 ;; Do no formatting while reading error file,
3013 ;; because that can run a shell command, and we
3014 ;; don't want that to cause an infinite recursion.
3015 (format-insert-file error-file nil
)
3016 ;; Put point after the inserted errors.
3017 (goto-char (- (point-max) pos-from-end
)))
3018 (and display-error-buffer
3019 (display-buffer (current-buffer)))))
3020 (delete-file error-file
))
3023 (defun shell-command-to-string (command)
3024 "Execute shell command COMMAND and return its output as a string."
3025 (with-output-to-string
3026 (with-current-buffer
3028 (process-file shell-file-name nil t nil shell-command-switch command
))))
3030 (defun process-file (program &optional infile buffer display
&rest args
)
3031 "Process files synchronously in a separate process.
3032 Similar to `call-process', but may invoke a file handler based on
3033 `default-directory'. The current working directory of the
3034 subprocess is `default-directory'.
3036 File names in INFILE and BUFFER are handled normally, but file
3037 names in ARGS should be relative to `default-directory', as they
3038 are passed to the process verbatim. \(This is a difference to
3039 `call-process' which does not support file handlers for INFILE
3042 Some file handlers might not support all variants, for example
3043 they might behave as if DISPLAY was nil, regardless of the actual
3045 (let ((fh (find-file-name-handler default-directory
'process-file
))
3048 (if fh
(apply fh
'process-file program infile buffer display args
)
3049 (when infile
(setq lc
(file-local-copy infile
)))
3050 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
3051 (make-temp-file "emacs")))
3053 (apply 'call-process program
3055 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
3057 (when stderr-file
(copy-file stderr-file
(cadr buffer
) t
))))
3058 (when stderr-file
(delete-file stderr-file
))
3059 (when lc
(delete-file lc
)))))
3061 (defvar process-file-side-effects t
3062 "Whether a call of `process-file' changes remote files.
3064 By default, this variable is always set to `t', meaning that a
3065 call of `process-file' could potentially change any file on a
3066 remote host. When set to `nil', a file handler could optimize
3067 its behavior with respect to remote file attribute caching.
3069 You should only ever change this variable with a let-binding;
3070 never with `setq'.")
3072 (defun start-file-process (name buffer program
&rest program-args
)
3073 "Start a program in a subprocess. Return the process object for it.
3075 Similar to `start-process', but may invoke a file handler based on
3076 `default-directory'. See Info node `(elisp)Magic File Names'.
3078 This handler ought to run PROGRAM, perhaps on the local host,
3079 perhaps on a remote host that corresponds to `default-directory'.
3080 In the latter case, the local part of `default-directory' becomes
3081 the working directory of the process.
3083 PROGRAM and PROGRAM-ARGS might be file names. They are not
3084 objects of file handler invocation. File handlers might not
3085 support pty association, if PROGRAM is nil."
3086 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
3087 (if fh
(apply fh
'start-file-process name buffer program program-args
)
3088 (apply 'start-process name buffer program program-args
))))
3092 (defvar tabulated-list-format
)
3093 (defvar tabulated-list-entries
)
3094 (defvar tabulated-list-sort-key
)
3095 (declare-function tabulated-list-init-header
"tabulated-list" ())
3096 (declare-function tabulated-list-print
"tabulated-list"
3097 (&optional remember-pos
))
3099 (defvar process-menu-query-only nil
)
3101 (define-derived-mode process-menu-mode tabulated-list-mode
"Process Menu"
3102 "Major mode for listing the processes called by Emacs."
3103 (setq tabulated-list-format
[("Process" 15 t
)
3108 (make-local-variable 'process-menu-query-only
)
3109 (setq tabulated-list-sort-key
(cons "Process" nil
))
3110 (add-hook 'tabulated-list-revert-hook
'list-processes--refresh nil t
)
3111 (tabulated-list-init-header))
3113 (defun list-processes--refresh ()
3114 "Recompute the list of processes for the Process List buffer.
3115 Also, delete any process that is exited or signaled."
3116 (setq tabulated-list-entries nil
)
3117 (dolist (p (process-list))
3118 (cond ((memq (process-status p
) '(exit signal closed
))
3120 ((or (not process-menu-query-only
)
3121 (process-query-on-exit-flag p
))
3122 (let* ((buf (process-buffer p
))
3123 (type (process-type p
))
3124 (name (process-name p
))
3125 (status (symbol-name (process-status p
)))
3126 (buf-label (if (buffer-live-p buf
)
3127 `(,(buffer-name buf
)
3129 help-echo
,(concat "Visit buffer `"
3130 (buffer-name buf
) "'")
3133 action process-menu-visit-buffer
)
3135 (tty (or (process-tty-name p
) "--"))
3137 (if (memq type
'(network serial
))
3138 (let ((contact (process-contact p t
)))
3139 (if (eq type
'network
)
3141 (if (plist-get contact
:type
)
3144 (if (plist-get contact
:server
)
3145 (format "server on %s"
3147 (plist-get contact
:host
)
3148 (plist-get contact
:local
)))
3149 (format "connection to %s"
3150 (plist-get contact
:host
))))
3151 (format "(serial port %s%s)"
3152 (or (plist-get contact
:port
) "?")
3153 (let ((speed (plist-get contact
:speed
)))
3155 (format " at %s b/s" speed
)
3157 (mapconcat 'identity
(process-command p
) " "))))
3158 (push (list p
(vector name status buf-label tty cmd
))
3159 tabulated-list-entries
))))))
3161 (defun process-menu-visit-buffer (button)
3162 (display-buffer (button-get button
'process-buffer
)))
3164 (defun list-processes (&optional query-only buffer
)
3165 "Display a list of all processes that are Emacs sub-processes.
3166 If optional argument QUERY-ONLY is non-nil, only processes with
3167 the query-on-exit flag set are listed.
3168 Any process listed as exited or signaled is actually eliminated
3169 after the listing is made.
3170 Optional argument BUFFER specifies a buffer to use, instead of
3172 The return value is always nil.
3174 This function lists only processes that were launched by Emacs. To
3175 see other processes running on the system, use `list-system-processes'."
3177 (or (fboundp 'process-list
)
3178 (error "Asynchronous subprocesses are not supported on this system"))
3179 (unless (bufferp buffer
)
3180 (setq buffer
(get-buffer-create "*Process List*")))
3181 (with-current-buffer buffer
3183 (setq process-menu-query-only query-only
)
3184 (list-processes--refresh)
3185 (tabulated-list-print))
3186 (display-buffer buffer
)
3189 (defvar universal-argument-map
3190 (let ((map (make-sparse-keymap))
3191 (universal-argument-minus
3192 ;; For backward compatibility, minus with no modifiers is an ordinary
3193 ;; command if digits have already been entered.
3194 `(menu-item "" negative-argument
3195 :filter
,(lambda (cmd)
3196 (if (integerp prefix-arg
) nil cmd
)))))
3197 (define-key map
[switch-frame
]
3198 (lambda (e) (interactive "e")
3199 (handle-switch-frame e
) (universal-argument--mode)))
3200 (define-key map
[?\C-u
] 'universal-argument-more
)
3201 (define-key map
[?-
] universal-argument-minus
)
3202 (define-key map
[?
0] 'digit-argument
)
3203 (define-key map
[?
1] 'digit-argument
)
3204 (define-key map
[?
2] 'digit-argument
)
3205 (define-key map
[?
3] 'digit-argument
)
3206 (define-key map
[?
4] 'digit-argument
)
3207 (define-key map
[?
5] 'digit-argument
)
3208 (define-key map
[?
6] 'digit-argument
)
3209 (define-key map
[?
7] 'digit-argument
)
3210 (define-key map
[?
8] 'digit-argument
)
3211 (define-key map
[?
9] 'digit-argument
)
3212 (define-key map
[kp-0
] 'digit-argument
)
3213 (define-key map
[kp-1
] 'digit-argument
)
3214 (define-key map
[kp-2
] 'digit-argument
)
3215 (define-key map
[kp-3
] 'digit-argument
)
3216 (define-key map
[kp-4
] 'digit-argument
)
3217 (define-key map
[kp-5
] 'digit-argument
)
3218 (define-key map
[kp-6
] 'digit-argument
)
3219 (define-key map
[kp-7
] 'digit-argument
)
3220 (define-key map
[kp-8
] 'digit-argument
)
3221 (define-key map
[kp-9
] 'digit-argument
)
3222 (define-key map
[kp-subtract
] universal-argument-minus
)
3224 "Keymap used while processing \\[universal-argument].")
3226 (defun universal-argument--mode ()
3227 (set-temporary-overlay-map universal-argument-map
))
3229 (defun universal-argument ()
3230 "Begin a numeric argument for the following command.
3231 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3232 \\[universal-argument] following the digits or minus sign ends the argument.
3233 \\[universal-argument] without digits or minus sign provides 4 as argument.
3234 Repeating \\[universal-argument] without digits or minus sign
3235 multiplies the argument by 4 each time.
3236 For some commands, just \\[universal-argument] by itself serves as a flag
3237 which is different in effect from any particular numeric argument.
3238 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3240 (setq prefix-arg
(list 4))
3241 (universal-argument--mode))
3243 (defun universal-argument-more (arg)
3244 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3245 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3247 (setq prefix-arg
(if (consp arg
)
3248 (list (* 4 (car arg
)))
3252 (when (consp prefix-arg
) (universal-argument--mode)))
3254 (defun negative-argument (arg)
3255 "Begin a negative numeric argument for the next command.
3256 \\[universal-argument] following digits or minus sign ends the argument."
3258 (setq prefix-arg
(cond ((integerp arg
) (- arg
))
3261 (universal-argument--mode))
3263 (defun digit-argument (arg)
3264 "Part of the numeric argument for the next command.
3265 \\[universal-argument] following digits or minus sign ends the argument."
3267 (let* ((char (if (integerp last-command-event
)
3269 (get last-command-event
'ascii-character
)))
3270 (digit (- (logand char ?
\177) ?
0)))
3271 (setq prefix-arg
(cond ((integerp arg
)
3273 (if (< arg
0) (- digit
) digit
)))
3275 ;; Treat -0 as just -, so that -01 will work.
3276 (if (zerop digit
) '-
(- digit
)))
3279 (universal-argument--mode))
3282 (defvar filter-buffer-substring-functions nil
3283 "This variable is a wrapper hook around `filter-buffer-substring'.")
3284 (make-obsolete-variable 'filter-buffer-substring-functions
3285 'filter-buffer-substring-function
"24.4")
3287 (defvar filter-buffer-substring-function
#'buffer-substring--filter
3288 "Function to perform the filtering in `filter-buffer-substring'.
3289 The function is called with 3 arguments:
3290 \(BEG END DELETE). The arguments BEG, END, and DELETE are the same
3291 as those of `filter-buffer-substring' in each case.
3292 It should return the buffer substring between BEG and END, after filtering.")
3294 (defvar buffer-substring-filters nil
3295 "List of filter functions for `filter-buffer-substring'.
3296 Each function must accept a single argument, a string, and return
3297 a string. The buffer substring is passed to the first function
3298 in the list, and the return value of each function is passed to
3300 As a special convention, point is set to the start of the buffer text
3301 being operated on (i.e., the first argument of `filter-buffer-substring')
3302 before these functions are called.")
3303 (make-obsolete-variable 'buffer-substring-filters
3304 'filter-buffer-substring-function
"24.1")
3306 (defun filter-buffer-substring (beg end
&optional delete
)
3307 "Return the buffer substring between BEG and END, after filtering.
3308 The hook `filter-buffer-substring-function' performs the actual filtering.
3309 By default, no filtering is done.
3311 If DELETE is non-nil, the text between BEG and END is deleted
3314 This function should be used instead of `buffer-substring',
3315 `buffer-substring-no-properties', or `delete-and-extract-region'
3316 when you want to allow filtering to take place. For example,
3317 major or minor modes can use `filter-buffer-substring-function' to
3318 extract characters that are special to a buffer, and should not
3319 be copied into other buffers."
3320 (funcall filter-buffer-substring-function beg end delete
))
3322 ;; FIXME: `with-wrapper-hook' is obsolete
3323 (defun buffer-substring--filter (beg end
&optional delete
)
3324 (with-wrapper-hook filter-buffer-substring-functions
(beg end delete
)
3326 ((or delete buffer-substring-filters
)
3329 (let ((string (if delete
(delete-and-extract-region beg end
)
3330 (buffer-substring beg end
))))
3331 (dolist (filter buffer-substring-filters
)
3332 (setq string
(funcall filter string
)))
3335 (buffer-substring beg end
)))))
3338 ;;;; Window system cut and paste hooks.
3340 (defvar interprogram-cut-function nil
3341 "Function to call to make a killed region available to other programs.
3342 Most window systems provide a facility for cutting and pasting
3343 text between different programs, such as the clipboard on X and
3344 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3346 This variable holds a function that Emacs calls whenever text is
3347 put in the kill ring, to make the new kill available to other
3348 programs. The function takes one argument, TEXT, which is a
3349 string containing the text which should be made available.")
3351 (defvar interprogram-paste-function nil
3352 "Function to call to get text cut from other programs.
3353 Most window systems provide a facility for cutting and pasting
3354 text between different programs, such as the clipboard on X and
3355 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3357 This variable holds a function that Emacs calls to obtain text
3358 that other programs have provided for pasting. The function is
3359 called with no arguments. If no other program has provided text
3360 to paste, the function should return nil (in which case the
3361 caller, usually `current-kill', should use the top of the Emacs
3362 kill ring). If another program has provided text to paste, the
3363 function should return that text as a string (in which case the
3364 caller should put this string in the kill ring as the latest
3367 The function may also return a list of strings if the window
3368 system supports multiple selections. The first string will be
3369 used as the pasted text, but the other will be placed in the kill
3370 ring for easy access via `yank-pop'.
3372 Note that the function should return a string only if a program
3373 other than Emacs has provided a string for pasting; if Emacs
3374 provided the most recent string, the function should return nil.
3375 If it is difficult to tell whether Emacs or some other program
3376 provided the current string, it is probably good enough to return
3377 nil if the string is equal (according to `string=') to the last
3378 text Emacs provided.")
3382 ;;;; The kill ring data structure.
3384 (defvar kill-ring nil
3385 "List of killed text sequences.
3386 Since the kill ring is supposed to interact nicely with cut-and-paste
3387 facilities offered by window systems, use of this variable should
3388 interact nicely with `interprogram-cut-function' and
3389 `interprogram-paste-function'. The functions `kill-new',
3390 `kill-append', and `current-kill' are supposed to implement this
3391 interaction; you may want to use them instead of manipulating the kill
3394 (defcustom kill-ring-max
60
3395 "Maximum length of kill ring before oldest elements are thrown away."
3399 (defvar kill-ring-yank-pointer nil
3400 "The tail of the kill ring whose car is the last thing yanked.")
3402 (defcustom save-interprogram-paste-before-kill nil
3403 "Save clipboard strings into kill ring before replacing them.
3404 When one selects something in another program to paste it into Emacs,
3405 but kills something in Emacs before actually pasting it,
3406 this selection is gone unless this variable is non-nil,
3407 in which case the other program's selection is saved in the `kill-ring'
3408 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3413 (defcustom kill-do-not-save-duplicates nil
3414 "Do not add a new string to `kill-ring' if it duplicates the last one.
3415 The comparison is done using `equal-including-properties'."
3420 (defun kill-new (string &optional replace yank-handler
)
3421 "Make STRING the latest kill in the kill ring.
3422 Set `kill-ring-yank-pointer' to point to it.
3423 If `interprogram-cut-function' is non-nil, apply it to STRING.
3424 Optional second argument REPLACE non-nil means that STRING will replace
3425 the front of the kill ring, rather than being added to the list.
3427 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3428 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3431 When the yank handler has a non-nil PARAM element, the original STRING
3432 argument is not used by `insert-for-yank'. However, since Lisp code
3433 may access and use elements from the kill ring directly, the STRING
3434 argument should still be a \"useful\" string for such uses."
3435 (if (> (length string
) 0)
3437 (put-text-property 0 (length string
)
3438 'yank-handler yank-handler string
))
3440 (signal 'args-out-of-range
3441 (list string
"yank-handler specified for empty string"))))
3442 (unless (and kill-do-not-save-duplicates
3443 ;; Due to text properties such as 'yank-handler that
3444 ;; can alter the contents to yank, comparison using
3445 ;; `equal' is unsafe.
3446 (equal-including-properties string
(car kill-ring
)))
3447 (if (fboundp 'menu-bar-update-yank-menu
)
3448 (menu-bar-update-yank-menu string
(and replace
(car kill-ring
)))))
3449 (when save-interprogram-paste-before-kill
3450 (let ((interprogram-paste (and interprogram-paste-function
3451 (funcall interprogram-paste-function
))))
3452 (when interprogram-paste
3453 (dolist (s (if (listp interprogram-paste
)
3454 (nreverse interprogram-paste
)
3455 (list interprogram-paste
)))
3456 (unless (and kill-do-not-save-duplicates
3457 (equal-including-properties s
(car kill-ring
)))
3458 (push s kill-ring
))))))
3459 (unless (and kill-do-not-save-duplicates
3460 (equal-including-properties string
(car kill-ring
)))
3461 (if (and replace kill-ring
)
3462 (setcar kill-ring string
)
3463 (push string kill-ring
)
3464 (if (> (length kill-ring
) kill-ring-max
)
3465 (setcdr (nthcdr (1- kill-ring-max
) kill-ring
) nil
))))
3466 (setq kill-ring-yank-pointer kill-ring
)
3467 (if interprogram-cut-function
3468 (funcall interprogram-cut-function string
)))
3469 (set-advertised-calling-convention
3470 'kill-new
'(string &optional replace
) "23.3")
3472 (defun kill-append (string before-p
&optional yank-handler
)
3473 "Append STRING to the end of the latest kill in the kill ring.
3474 If BEFORE-P is non-nil, prepend STRING to the kill.
3475 If `interprogram-cut-function' is set, pass the resulting kill to it."
3476 (let* ((cur (car kill-ring
)))
3477 (kill-new (if before-p
(concat string cur
) (concat cur string
))
3478 (or (= (length cur
) 0)
3479 (equal yank-handler
(get-text-property 0 'yank-handler cur
)))
3481 (set-advertised-calling-convention 'kill-append
'(string before-p
) "23.3")
3483 (defcustom yank-pop-change-selection nil
3484 "Whether rotating the kill ring changes the window system selection.
3485 If non-nil, whenever the kill ring is rotated (usually via the
3486 `yank-pop' command), Emacs also calls `interprogram-cut-function'
3487 to copy the new kill to the window system selection."
3492 (defun current-kill (n &optional do-not-move
)
3493 "Rotate the yanking point by N places, and then return that kill.
3494 If N is zero and `interprogram-paste-function' is set to a
3495 function that returns a string or a list of strings, and if that
3496 function doesn't return nil, then that string (or list) is added
3497 to the front of the kill ring and the string (or first string in
3498 the list) is returned as the latest kill.
3500 If N is not zero, and if `yank-pop-change-selection' is
3501 non-nil, use `interprogram-cut-function' to transfer the
3502 kill at the new yank point into the window system selection.
3504 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3505 move the yanking point; just return the Nth kill forward."
3507 (let ((interprogram-paste (and (= n
0)
3508 interprogram-paste-function
3509 (funcall interprogram-paste-function
))))
3510 (if interprogram-paste
3512 ;; Disable the interprogram cut function when we add the new
3513 ;; text to the kill ring, so Emacs doesn't try to own the
3514 ;; selection, with identical text.
3515 (let ((interprogram-cut-function nil
))
3516 (if (listp interprogram-paste
)
3517 (mapc 'kill-new
(nreverse interprogram-paste
))
3518 (kill-new interprogram-paste
)))
3520 (or kill-ring
(error "Kill ring is empty"))
3521 (let ((ARGth-kill-element
3522 (nthcdr (mod (- n
(length kill-ring-yank-pointer
))
3526 (setq kill-ring-yank-pointer ARGth-kill-element
)
3527 (when (and yank-pop-change-selection
3529 interprogram-cut-function
)
3530 (funcall interprogram-cut-function
(car ARGth-kill-element
))))
3531 (car ARGth-kill-element
)))))
3535 ;;;; Commands for manipulating the kill ring.
3537 (defcustom kill-read-only-ok nil
3538 "Non-nil means don't signal an error for killing read-only text."
3542 (defun kill-region (beg end
&optional yank-handler
)
3543 "Kill (\"cut\") text between point and mark.
3544 This deletes the text from the buffer and saves it in the kill ring.
3545 The command \\[yank] can retrieve it from there.
3546 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3548 If you want to append the killed region to the last killed text,
3549 use \\[append-next-kill] before \\[kill-region].
3551 If the buffer is read-only, Emacs will beep and refrain from deleting
3552 the text, but put the text in the kill ring anyway. This means that
3553 you can use the killing commands to copy text from a read-only buffer.
3555 Lisp programs should use this function for killing text.
3556 (To delete text, use `delete-region'.)
3557 Supply two arguments, character positions indicating the stretch of text
3559 Any command that calls this function is a \"kill command\".
3560 If the previous command was also a kill command,
3561 the text killed this time appends to the text killed last time
3562 to make one entry in the kill ring."
3563 ;; Pass point first, then mark, because the order matters
3564 ;; when calling kill-append.
3565 (interactive (list (point) (mark)))
3566 (unless (and beg end
)
3567 (error "The mark is not set now, so there is no region"))
3569 (let ((string (filter-buffer-substring beg end t
)))
3570 (when string
;STRING is nil if BEG = END
3571 ;; Add that string to the kill ring, one way or another.
3572 (if (eq last-command
'kill-region
)
3573 (kill-append string
(< end beg
) yank-handler
)
3574 (kill-new string nil yank-handler
)))
3575 (when (or string
(eq last-command
'kill-region
))
3576 (setq this-command
'kill-region
))
3577 (setq deactivate-mark t
)
3579 ((buffer-read-only text-read-only
)
3580 ;; The code above failed because the buffer, or some of the characters
3581 ;; in the region, are read-only.
3582 ;; We should beep, in case the user just isn't aware of this.
3583 ;; However, there's no harm in putting
3584 ;; the region's text in the kill ring, anyway.
3585 (copy-region-as-kill beg end
)
3586 ;; Set this-command now, so it will be set even if we get an error.
3587 (setq this-command
'kill-region
)
3588 ;; This should barf, if appropriate, and give us the correct error.
3589 (if kill-read-only-ok
3590 (progn (message "Read only text copied to kill ring") nil
)
3591 ;; Signal an error if the buffer is read-only.
3592 (barf-if-buffer-read-only)
3593 ;; If the buffer isn't read-only, the text is.
3594 (signal 'text-read-only
(list (current-buffer)))))))
3595 (set-advertised-calling-convention 'kill-region
'(beg end
) "23.3")
3597 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3598 ;; to get two copies of the text when the user accidentally types M-w and
3599 ;; then corrects it with the intended C-w.
3600 (defun copy-region-as-kill (beg end
)
3601 "Save the region as if killed, but don't kill it.
3602 In Transient Mark mode, deactivate the mark.
3603 If `interprogram-cut-function' is non-nil, also save the text for a window
3604 system cut and paste.
3606 This command's old key binding has been given to `kill-ring-save'."
3608 (if (eq last-command
'kill-region
)
3609 (kill-append (filter-buffer-substring beg end
) (< end beg
))
3610 (kill-new (filter-buffer-substring beg end
)))
3611 (setq deactivate-mark t
)
3614 (defun kill-ring-save (beg end
)
3615 "Save the region as if killed, but don't kill it.
3616 In Transient Mark mode, deactivate the mark.
3617 If `interprogram-cut-function' is non-nil, also save the text for a window
3618 system cut and paste.
3620 If you want to append the killed line to the last killed text,
3621 use \\[append-next-kill] before \\[kill-ring-save].
3623 This command is similar to `copy-region-as-kill', except that it gives
3624 visual feedback indicating the extent of the region being copied."
3626 (copy-region-as-kill beg end
)
3627 ;; This use of called-interactively-p is correct because the code it
3628 ;; controls just gives the user visual feedback.
3629 (if (called-interactively-p 'interactive
)
3630 (indicate-copied-region)))
3632 (defun indicate-copied-region (&optional message-len
)
3633 "Indicate that the region text has been copied interactively.
3634 If the mark is visible in the selected window, blink the cursor
3635 between point and mark if there is currently no active region
3638 If the mark lies outside the selected window, display an
3639 informative message containing a sample of the copied text. The
3640 optional argument MESSAGE-LEN, if non-nil, specifies the length
3641 of this sample text; it defaults to 40."
3642 (let ((mark (mark t
))
3644 ;; Inhibit quitting so we can make a quit here
3645 ;; look like a C-g typed as a command.
3647 (if (pos-visible-in-window-p mark
(selected-window))
3648 ;; Swap point-and-mark quickly so as to show the region that
3649 ;; was selected. Don't do it if the region is highlighted.
3650 (unless (and (region-active-p)
3651 (face-background 'region
))
3652 ;; Swap point and mark.
3653 (set-marker (mark-marker) (point) (current-buffer))
3655 (sit-for blink-matching-delay
)
3657 (set-marker (mark-marker) mark
(current-buffer))
3659 ;; If user quit, deactivate the mark
3660 ;; as C-g would as a command.
3661 (and quit-flag mark-active
3663 (let ((len (min (abs (- mark point
))
3664 (or message-len
40))))
3666 ;; Don't say "killed"; that is misleading.
3667 (message "Saved text until \"%s\""
3668 (buffer-substring-no-properties (- mark len
) mark
))
3669 (message "Saved text from \"%s\""
3670 (buffer-substring-no-properties mark
(+ mark len
))))))))
3672 (defun append-next-kill (&optional interactive
)
3673 "Cause following command, if it kills, to append to previous kill.
3674 The argument is used for internal purposes; do not supply one."
3676 ;; We don't use (interactive-p), since that breaks kbd macros.
3679 (setq this-command
'kill-region
)
3680 (message "If the next command is a kill, it will append"))
3681 (setq last-command
'kill-region
)))
3685 (defcustom yank-handled-properties
3686 '((font-lock-face . yank-handle-font-lock-face-property
)
3687 (category . yank-handle-category-property
))
3688 "List of special text property handling conditions for yanking.
3689 Each element should have the form (PROP . FUN), where PROP is a
3690 property symbol and FUN is a function. When the `yank' command
3691 inserts text into the buffer, it scans the inserted text for
3692 stretches of text that have `eq' values of the text property
3693 PROP; for each such stretch of text, FUN is called with three
3694 arguments: the property's value in that text, and the start and
3695 end positions of the text.
3697 This is done prior to removing the properties specified by
3698 `yank-excluded-properties'."
3702 ;; This is actually used in subr.el but defcustom does not work there.
3703 (defcustom yank-excluded-properties
3704 '(category field follow-link fontified font-lock-face help-echo
3705 intangible invisible keymap local-map mouse-face read-only
3707 "Text properties to discard when yanking.
3708 The value should be a list of text properties to discard or t,
3709 which means to discard all text properties.
3711 See also `yank-handled-properties'."
3712 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
3716 (defvar yank-window-start nil
)
3717 (defvar yank-undo-function nil
3718 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3719 Function is called with two parameters, START and END corresponding to
3720 the value of the mark and point; it is guaranteed that START <= END.
3721 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3723 (defun yank-pop (&optional arg
)
3724 "Replace just-yanked stretch of killed text with a different stretch.
3725 This command is allowed only immediately after a `yank' or a `yank-pop'.
3726 At such a time, the region contains a stretch of reinserted
3727 previously-killed text. `yank-pop' deletes that text and inserts in its
3728 place a different stretch of killed text.
3730 With no argument, the previous kill is inserted.
3731 With argument N, insert the Nth previous kill.
3732 If N is negative, this is a more recent kill.
3734 The sequence of kills wraps around, so that after the oldest one
3735 comes the newest one.
3737 When this command inserts killed text into the buffer, it honors
3738 `yank-excluded-properties' and `yank-handler' as described in the
3739 doc string for `insert-for-yank-1', which see."
3741 (if (not (eq last-command
'yank
))
3742 (error "Previous command was not a yank"))
3743 (setq this-command
'yank
)
3744 (unless arg
(setq arg
1))
3745 (let ((inhibit-read-only t
)
3746 (before (< (point) (mark t
))))
3748 (funcall (or yank-undo-function
'delete-region
) (point) (mark t
))
3749 (funcall (or yank-undo-function
'delete-region
) (mark t
) (point)))
3750 (setq yank-undo-function nil
)
3751 (set-marker (mark-marker) (point) (current-buffer))
3752 (insert-for-yank (current-kill arg
))
3753 ;; Set the window start back where it was in the yank command,
3755 (set-window-start (selected-window) yank-window-start t
)
3757 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3758 ;; It is cleaner to avoid activation, even though the command
3759 ;; loop would deactivate the mark because we inserted text.
3760 (goto-char (prog1 (mark t
)
3761 (set-marker (mark-marker) (point) (current-buffer))))))
3764 (defun yank (&optional arg
)
3765 "Reinsert (\"paste\") the last stretch of killed text.
3766 More precisely, reinsert the most recent kill, which is the
3767 stretch of killed text most recently killed OR yanked. Put point
3768 at the end, and set mark at the beginning without activating it.
3769 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
3770 With argument N, reinsert the Nth most recent kill.
3772 When this command inserts text into the buffer, it honors the
3773 `yank-handled-properties' and `yank-excluded-properties'
3774 variables, and the `yank-handler' text property. See
3775 `insert-for-yank-1' for details.
3777 See also the command `yank-pop' (\\[yank-pop])."
3779 (setq yank-window-start
(window-start))
3780 ;; If we don't get all the way thru, make last-command indicate that
3781 ;; for the following command.
3782 (setq this-command t
)
3784 (insert-for-yank (current-kill (cond
3789 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3790 ;; It is cleaner to avoid activation, even though the command
3791 ;; loop would deactivate the mark because we inserted text.
3792 (goto-char (prog1 (mark t
)
3793 (set-marker (mark-marker) (point) (current-buffer)))))
3794 ;; If we do get all the way thru, make this-command indicate that.
3795 (if (eq this-command t
)
3796 (setq this-command
'yank
))
3799 (defun rotate-yank-pointer (arg)
3800 "Rotate the yanking point in the kill ring.
3801 With ARG, rotate that many kills forward (or backward, if negative)."
3805 ;; Some kill commands.
3807 ;; Internal subroutine of delete-char
3808 (defun kill-forward-chars (arg)
3809 (if (listp arg
) (setq arg
(car arg
)))
3810 (if (eq arg
'-
) (setq arg -
1))
3811 (kill-region (point) (+ (point) arg
)))
3813 ;; Internal subroutine of backward-delete-char
3814 (defun kill-backward-chars (arg)
3815 (if (listp arg
) (setq arg
(car arg
)))
3816 (if (eq arg
'-
) (setq arg -
1))
3817 (kill-region (point) (- (point) arg
)))
3819 (defcustom backward-delete-char-untabify-method
'untabify
3820 "The method for untabifying when deleting backward.
3821 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3822 `hungry' -- delete all whitespace, both tabs and spaces;
3823 `all' -- delete all whitespace, including tabs, spaces and newlines;
3824 nil -- just delete one character."
3825 :type
'(choice (const untabify
) (const hungry
) (const all
) (const nil
))
3829 (defun backward-delete-char-untabify (arg &optional killp
)
3830 "Delete characters backward, changing tabs into spaces.
3831 The exact behavior depends on `backward-delete-char-untabify-method'.
3832 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3833 Interactively, ARG is the prefix arg (default 1)
3834 and KILLP is t if a prefix arg was specified."
3835 (interactive "*p\nP")
3836 (when (eq backward-delete-char-untabify-method
'untabify
)
3839 (while (and (> count
0) (not (bobp)))
3840 (if (= (preceding-char) ?
\t)
3841 (let ((col (current-column)))
3843 (setq col
(- col
(current-column)))
3844 (insert-char ?\s col
)
3847 (setq count
(1- count
))))))
3848 (let* ((skip (cond ((eq backward-delete-char-untabify-method
'hungry
) " \t")
3849 ((eq backward-delete-char-untabify-method
'all
)
3852 (let* ((oldpt (point))
3853 (wh (- oldpt
(save-excursion
3854 (skip-chars-backward skip
)
3855 (constrain-to-field nil oldpt
)))))
3856 (+ arg
(if (zerop wh
) 0 (1- wh
))))
3858 ;; Avoid warning about delete-backward-char
3859 (with-no-warnings (delete-backward-char n killp
))))
3861 (defun zap-to-char (arg char
)
3862 "Kill up to and including ARGth occurrence of CHAR.
3863 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3864 Goes backward if ARG is negative; error if CHAR not found."
3865 (interactive (list (prefix-numeric-value current-prefix-arg
)
3866 (read-char "Zap to char: " t
)))
3867 ;; Avoid "obsolete" warnings for translation-table-for-input.
3869 (if (char-table-p translation-table-for-input
)
3870 (setq char
(or (aref translation-table-for-input char
) char
))))
3871 (kill-region (point) (progn
3872 (search-forward (char-to-string char
) nil nil arg
)
3875 ;; kill-line and its subroutines.
3877 (defcustom kill-whole-line nil
3878 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
3882 (defun kill-line (&optional arg
)
3883 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3884 With prefix argument ARG, kill that many lines from point.
3885 Negative arguments kill lines backward.
3886 With zero argument, kills the text before point on the current line.
3888 When calling from a program, nil means \"no arg\",
3889 a number counts as a prefix arg.
3891 To kill a whole line, when point is not at the beginning, type \
3892 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3894 If `show-trailing-whitespace' is non-nil, this command will just
3895 kill the rest of the current line, even if there are only
3898 If option `kill-whole-line' is non-nil, then this command kills the whole line
3899 including its terminating newline, when used at the beginning of a line
3900 with no argument. As a consequence, you can always kill a whole line
3901 by typing \\[move-beginning-of-line] \\[kill-line].
3903 If you want to append the killed line to the last killed text,
3904 use \\[append-next-kill] before \\[kill-line].
3906 If the buffer is read-only, Emacs will beep and refrain from deleting
3907 the line, but put the line in the kill ring anyway. This means that
3908 you can use this command to copy text from a read-only buffer.
3909 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3912 (kill-region (point)
3913 ;; It is better to move point to the other end of the kill
3914 ;; before killing. That way, in a read-only buffer, point
3915 ;; moves across the text that is copied to the kill ring.
3916 ;; The choice has no effect on undo now that undo records
3917 ;; the value of point from before the command was run.
3920 (forward-visible-line (prefix-numeric-value arg
))
3922 (signal 'end-of-buffer nil
))
3925 (end-of-visible-line) (point))))
3926 (if (or (save-excursion
3927 ;; If trailing whitespace is visible,
3928 ;; don't treat it as nothing.
3929 (unless show-trailing-whitespace
3930 (skip-chars-forward " \t" end
))
3932 (and kill-whole-line
(bolp)))
3933 (forward-visible-line 1)
3937 (defun kill-whole-line (&optional arg
)
3939 With prefix ARG, kill that many lines starting from the current line.
3940 If ARG is negative, kill backward. Also kill the preceding newline.
3941 \(This is meant to make \\[repeat] work well with negative arguments.\)
3942 If ARG is zero, kill current line but exclude the trailing newline."
3944 (or arg
(setq arg
1))
3945 (if (and (> arg
0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3946 (signal 'end-of-buffer nil
))
3947 (if (and (< arg
0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3948 (signal 'beginning-of-buffer nil
))
3949 (unless (eq last-command
'kill-region
)
3951 (setq last-command
'kill-region
))
3953 ;; We need to kill in two steps, because the previous command
3954 ;; could have been a kill command, in which case the text
3955 ;; before point needs to be prepended to the current kill
3956 ;; ring entry and the text after point appended. Also, we
3957 ;; need to use save-excursion to avoid copying the same text
3958 ;; twice to the kill ring in read-only buffers.
3960 (kill-region (point) (progn (forward-visible-line 0) (point))))
3961 (kill-region (point) (progn (end-of-visible-line) (point))))
3964 (kill-region (point) (progn (end-of-visible-line) (point))))
3965 (kill-region (point)
3966 (progn (forward-visible-line (1+ arg
))
3967 (unless (bobp) (backward-char))
3971 (kill-region (point) (progn (forward-visible-line 0) (point))))
3972 (kill-region (point)
3973 (progn (forward-visible-line arg
) (point))))))
3975 (defun forward-visible-line (arg)
3976 "Move forward by ARG lines, ignoring currently invisible newlines only.
3977 If ARG is negative, move backward -ARG lines.
3978 If ARG is zero, move to the beginning of the current line."
3983 (or (zerop (forward-line 1))
3984 (signal 'end-of-buffer nil
))
3985 ;; If the newline we just skipped is invisible,
3988 (get-char-property (1- (point)) 'invisible
)))
3989 (if (if (eq buffer-invisibility-spec t
)
3991 (or (memq prop buffer-invisibility-spec
)
3992 (assq prop buffer-invisibility-spec
)))
3993 (setq arg
(1+ arg
))))
3994 (setq arg
(1- arg
)))
3995 ;; If invisible text follows, and it is a number of complete lines,
3997 (let ((opoint (point)))
3998 (while (and (not (eobp))
4000 (get-char-property (point) 'invisible
)))
4001 (if (eq buffer-invisibility-spec t
)
4003 (or (memq prop buffer-invisibility-spec
)
4004 (assq prop buffer-invisibility-spec
)))))
4006 (if (get-text-property (point) 'invisible
)
4007 (or (next-single-property-change (point) 'invisible
)
4009 (next-overlay-change (point)))))
4011 (goto-char opoint
))))
4013 (while (or first
(<= arg
0))
4016 (or (zerop (forward-line -
1))
4017 (signal 'beginning-of-buffer nil
)))
4018 ;; If the newline we just moved to is invisible,
4022 (get-char-property (1- (point)) 'invisible
)))
4023 (unless (if (eq buffer-invisibility-spec t
)
4025 (or (memq prop buffer-invisibility-spec
)
4026 (assq prop buffer-invisibility-spec
)))
4027 (setq arg
(1+ arg
)))))
4029 ;; If invisible text follows, and it is a number of complete lines,
4031 (let ((opoint (point)))
4032 (while (and (not (bobp))
4034 (get-char-property (1- (point)) 'invisible
)))
4035 (if (eq buffer-invisibility-spec t
)
4037 (or (memq prop buffer-invisibility-spec
)
4038 (assq prop buffer-invisibility-spec
)))))
4040 (if (get-text-property (1- (point)) 'invisible
)
4041 (or (previous-single-property-change (point) 'invisible
)
4043 (previous-overlay-change (point)))))
4045 (goto-char opoint
)))))
4046 ((beginning-of-buffer end-of-buffer
)
4049 (defun end-of-visible-line ()
4050 "Move to end of current visible line."
4052 ;; If the following character is currently invisible,
4053 ;; skip all characters with that same `invisible' property value,
4054 ;; then find the next newline.
4055 (while (and (not (eobp))
4057 (skip-chars-forward "^\n")
4059 (get-char-property (point) 'invisible
)))
4060 (if (eq buffer-invisibility-spec t
)
4062 (or (memq prop buffer-invisibility-spec
)
4063 (assq prop buffer-invisibility-spec
))))))
4064 (skip-chars-forward "^\n")
4065 (if (get-text-property (point) 'invisible
)
4066 (goto-char (or (next-single-property-change (point) 'invisible
)
4068 (goto-char (next-overlay-change (point))))
4071 (defun insert-buffer (buffer)
4072 "Insert after point the contents of BUFFER.
4073 Puts mark after the inserted text.
4074 BUFFER may be a buffer or a buffer name.
4076 This function is meant for the user to run interactively.
4077 Don't call it from programs: use `insert-buffer-substring' instead!"
4081 (barf-if-buffer-read-only)
4082 (read-buffer "Insert buffer: "
4083 (if (eq (selected-window) (next-window))
4084 (other-buffer (current-buffer))
4085 (window-buffer (next-window)))
4089 (insert-buffer-substring (get-buffer buffer
))
4093 (defun append-to-buffer (buffer start end
)
4094 "Append to specified buffer the text of the region.
4095 It is inserted into that buffer before its point.
4097 When calling from a program, give three arguments:
4098 BUFFER (or buffer name), START and END.
4099 START and END specify the portion of the current buffer to be copied."
4101 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t
))
4102 (region-beginning) (region-end)))
4103 (let* ((oldbuf (current-buffer))
4104 (append-to (get-buffer-create buffer
))
4105 (windows (get-buffer-window-list append-to t t
))
4108 (with-current-buffer append-to
4109 (setq point
(point))
4110 (barf-if-buffer-read-only)
4111 (insert-buffer-substring oldbuf start end
)
4112 (dolist (window windows
)
4113 (when (= (window-point window
) point
)
4114 (set-window-point window
(point))))))))
4116 (defun prepend-to-buffer (buffer start end
)
4117 "Prepend to specified buffer the text of the region.
4118 It is inserted into that buffer after its point.
4120 When calling from a program, give three arguments:
4121 BUFFER (or buffer name), START and END.
4122 START and END specify the portion of the current buffer to be copied."
4123 (interactive "BPrepend to buffer: \nr")
4124 (let ((oldbuf (current-buffer)))
4125 (with-current-buffer (get-buffer-create buffer
)
4126 (barf-if-buffer-read-only)
4128 (insert-buffer-substring oldbuf start end
)))))
4130 (defun copy-to-buffer (buffer start end
)
4131 "Copy to specified buffer the text of the region.
4132 It is inserted into that buffer, replacing existing text there.
4134 When calling from a program, give three arguments:
4135 BUFFER (or buffer name), START and END.
4136 START and END specify the portion of the current buffer to be copied."
4137 (interactive "BCopy to buffer: \nr")
4138 (let ((oldbuf (current-buffer)))
4139 (with-current-buffer (get-buffer-create buffer
)
4140 (barf-if-buffer-read-only)
4143 (insert-buffer-substring oldbuf start end
)))))
4145 (define-error 'mark-inactive
(purecopy "The mark is not active now"))
4147 (defvar activate-mark-hook nil
4148 "Hook run when the mark becomes active.
4149 It is also run at the end of a command, if the mark is active and
4150 it is possible that the region may have changed.")
4152 (defvar deactivate-mark-hook nil
4153 "Hook run when the mark becomes inactive.")
4155 (defun mark (&optional force
)
4156 "Return this buffer's mark value as integer, or nil if never set.
4158 In Transient Mark mode, this function signals an error if
4159 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
4160 or the argument FORCE is non-nil, it disregards whether the mark
4161 is active, and returns an integer or nil in the usual way.
4163 If you are using this in an editing command, you are most likely making
4164 a mistake; see the documentation of `set-mark'."
4165 (if (or force
(not transient-mark-mode
) mark-active mark-even-if-inactive
)
4166 (marker-position (mark-marker))
4167 (signal 'mark-inactive nil
)))
4169 ;; Behind display-selections-p.
4170 (declare-function x-selection-owner-p
"xselect.c"
4171 (&optional selection terminal
))
4172 (declare-function x-selection-exists-p
"xselect.c"
4173 (&optional selection terminal
))
4175 (defun deactivate-mark (&optional force
)
4176 "Deactivate the mark.
4177 If Transient Mark mode is disabled, this function normally does
4178 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
4180 Deactivating the mark sets `mark-active' to nil, updates the
4181 primary selection according to `select-active-regions', and runs
4182 `deactivate-mark-hook'.
4184 If Transient Mark mode was temporarily enabled, reset the value
4185 of the variable `transient-mark-mode'; if this causes Transient
4186 Mark mode to be disabled, don't change `mark-active' to nil or
4187 run `deactivate-mark-hook'."
4188 (when (or transient-mark-mode force
)
4189 (when (and (if (eq select-active-regions
'only
)
4190 (eq (car-safe transient-mark-mode
) 'only
)
4191 select-active-regions
)
4193 (display-selections-p))
4194 ;; The var `saved-region-selection', if non-nil, is the text in
4195 ;; the region prior to the last command modifying the buffer.
4196 ;; Set the selection to that, or to the current region.
4197 (cond (saved-region-selection
4198 (x-set-selection 'PRIMARY saved-region-selection
)
4199 (setq saved-region-selection nil
))
4200 ;; If another program has acquired the selection, region
4201 ;; deactivation should not clobber it (Bug#11772).
4202 ((and (/= (region-beginning) (region-end))
4203 (or (x-selection-owner-p 'PRIMARY
)
4204 (null (x-selection-exists-p 'PRIMARY
))))
4205 (x-set-selection 'PRIMARY
4206 (buffer-substring (region-beginning)
4208 (if (and (null force
)
4209 (or (eq transient-mark-mode
'lambda
)
4210 (and (eq (car-safe transient-mark-mode
) 'only
)
4211 (null (cdr transient-mark-mode
)))))
4212 ;; When deactivating a temporary region, don't change
4213 ;; `mark-active' or run `deactivate-mark-hook'.
4214 (setq transient-mark-mode nil
)
4215 (if (eq (car-safe transient-mark-mode
) 'only
)
4216 (setq transient-mark-mode
(cdr transient-mark-mode
)))
4217 (setq mark-active nil
)
4218 (run-hooks 'deactivate-mark-hook
))))
4220 (defun activate-mark ()
4221 "Activate the mark."
4223 (setq mark-active t
)
4224 (unless transient-mark-mode
4225 (setq transient-mark-mode
'lambda
))
4226 (run-hooks 'activate-mark-hook
)))
4228 (defun set-mark (pos)
4229 "Set this buffer's mark to POS. Don't use this function!
4230 That is to say, don't use this function unless you want
4231 the user to see that the mark has moved, and you want the previous
4232 mark position to be lost.
4234 Normally, when a new mark is set, the old one should go on the stack.
4235 This is why most applications should use `push-mark', not `set-mark'.
4237 Novice Emacs Lisp programmers often try to use the mark for the wrong
4238 purposes. The mark saves a location for the user's convenience.
4239 Most editing commands should not alter the mark.
4240 To remember a location for internal use in the Lisp program,
4241 store it in a Lisp variable. Example:
4243 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
4247 (setq mark-active t
)
4248 (run-hooks 'activate-mark-hook
)
4249 (set-marker (mark-marker) pos
(current-buffer)))
4250 ;; Normally we never clear mark-active except in Transient Mark mode.
4251 ;; But when we actually clear out the mark value too, we must
4252 ;; clear mark-active in any mode.
4254 (set-marker (mark-marker) nil
)))
4256 (defcustom use-empty-active-region nil
4257 "Whether \"region-aware\" commands should act on empty regions.
4258 If nil, region-aware commands treat empty regions as inactive.
4259 If non-nil, region-aware commands treat the region as active as
4260 long as the mark is active, even if the region is empty.
4262 Region-aware commands are those that act on the region if it is
4263 active and Transient Mark mode is enabled, and on the text near
4267 :group
'editing-basics
)
4269 (defun use-region-p ()
4270 "Return t if the region is active and it is appropriate to act on it.
4271 This is used by commands that act specially on the region under
4272 Transient Mark mode.
4274 The return value is t if Transient Mark mode is enabled and the
4275 mark is active; furthermore, if `use-empty-active-region' is nil,
4276 the region must not be empty. Otherwise, the return value is nil.
4278 For some commands, it may be appropriate to ignore the value of
4279 `use-empty-active-region'; in that case, use `region-active-p'."
4280 (and (region-active-p)
4281 (or use-empty-active-region
(> (region-end) (region-beginning)))))
4283 (defun region-active-p ()
4284 "Return t if Transient Mark mode is enabled and the mark is active.
4286 Some commands act specially on the region when Transient Mark
4287 mode is enabled. Usually, such commands should use
4288 `use-region-p' instead of this function, because `use-region-p'
4289 also checks the value of `use-empty-active-region'."
4290 (and transient-mark-mode mark-active
))
4292 (defvar mark-ring nil
4293 "The list of former marks of the current buffer, most recent first.")
4294 (make-variable-buffer-local 'mark-ring
)
4295 (put 'mark-ring
'permanent-local t
)
4297 (defcustom mark-ring-max
16
4298 "Maximum size of mark ring. Start discarding off end if gets this big."
4300 :group
'editing-basics
)
4302 (defvar global-mark-ring nil
4303 "The list of saved global marks, most recent first.")
4305 (defcustom global-mark-ring-max
16
4306 "Maximum size of global mark ring. \
4307 Start discarding off end if gets this big."
4309 :group
'editing-basics
)
4311 (defun pop-to-mark-command ()
4312 "Jump to mark, and pop a new position for mark off the ring.
4313 \(Does not affect global mark ring\)."
4316 (error "No mark set in this buffer")
4317 (if (= (point) (mark t
))
4318 (message "Mark popped"))
4319 (goto-char (mark t
))
4322 (defun push-mark-command (arg &optional nomsg
)
4323 "Set mark at where point is.
4324 If no prefix ARG and mark is already set there, just activate it.
4325 Display `Mark set' unless the optional second arg NOMSG is non-nil."
4327 (let ((mark (marker-position (mark-marker))))
4328 (if (or arg
(null mark
) (/= mark
(point)))
4329 (push-mark nil nomsg t
)
4330 (setq mark-active t
)
4331 (run-hooks 'activate-mark-hook
)
4333 (message "Mark activated")))))
4335 (defcustom set-mark-command-repeat-pop nil
4336 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
4337 That means that C-u \\[set-mark-command] \\[set-mark-command]
4338 will pop the mark twice, and
4339 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
4340 will pop the mark three times.
4342 A value of nil means \\[set-mark-command]'s behavior does not change
4343 after C-u \\[set-mark-command]."
4345 :group
'editing-basics
)
4347 (defun set-mark-command (arg)
4348 "Set the mark where point is, or jump to the mark.
4349 Setting the mark also alters the region, which is the text
4350 between point and mark; this is the closest equivalent in
4351 Emacs to what some editors call the \"selection\".
4353 With no prefix argument, set the mark at point, and push the
4354 old mark position on local mark ring. Also push the old mark on
4355 global mark ring, if the previous mark was set in another buffer.
4357 When Transient Mark Mode is off, immediately repeating this
4358 command activates `transient-mark-mode' temporarily.
4360 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
4361 jump to the mark, and set the mark from
4362 position popped off the local mark ring \(this does not affect the global
4363 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
4364 mark ring \(see `pop-global-mark'\).
4366 If `set-mark-command-repeat-pop' is non-nil, repeating
4367 the \\[set-mark-command] command with no prefix argument pops the next position
4368 off the local (or global) mark ring and jumps there.
4370 With \\[universal-argument] \\[universal-argument] as prefix
4371 argument, unconditionally set mark where point is, even if
4372 `set-mark-command-repeat-pop' is non-nil.
4374 Novice Emacs Lisp programmers often try to use the mark for the wrong
4375 purposes. See the documentation of `set-mark' for more information."
4377 (cond ((eq transient-mark-mode
'lambda
)
4378 (setq transient-mark-mode nil
))
4379 ((eq (car-safe transient-mark-mode
) 'only
)
4382 ((and (consp arg
) (> (prefix-numeric-value arg
) 4))
4383 (push-mark-command nil
))
4384 ((not (eq this-command
'set-mark-command
))
4386 (pop-to-mark-command)
4387 (push-mark-command t
)))
4388 ((and set-mark-command-repeat-pop
4389 (eq last-command
'pop-to-mark-command
))
4390 (setq this-command
'pop-to-mark-command
)
4391 (pop-to-mark-command))
4392 ((and set-mark-command-repeat-pop
4393 (eq last-command
'pop-global-mark
)
4395 (setq this-command
'pop-global-mark
)
4398 (setq this-command
'pop-to-mark-command
)
4399 (pop-to-mark-command))
4400 ((eq last-command
'set-mark-command
)
4401 (if (region-active-p)
4404 (message "Mark deactivated"))
4406 (message "Mark activated")))
4408 (push-mark-command nil
))))
4410 (defun push-mark (&optional location nomsg activate
)
4411 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
4412 If the last global mark pushed was not in the current buffer,
4413 also push LOCATION on the global mark ring.
4414 Display `Mark set' unless the optional second arg NOMSG is non-nil.
4416 Novice Emacs Lisp programmers often try to use the mark for the wrong
4417 purposes. See the documentation of `set-mark' for more information.
4419 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
4420 (unless (null (mark t
))
4421 (setq mark-ring
(cons (copy-marker (mark-marker)) mark-ring
))
4422 (when (> (length mark-ring
) mark-ring-max
)
4423 (move-marker (car (nthcdr mark-ring-max mark-ring
)) nil
)
4424 (setcdr (nthcdr (1- mark-ring-max
) mark-ring
) nil
)))
4425 (set-marker (mark-marker) (or location
(point)) (current-buffer))
4426 ;; Now push the mark on the global mark ring.
4427 (if (and global-mark-ring
4428 (eq (marker-buffer (car global-mark-ring
)) (current-buffer)))
4429 ;; The last global mark pushed was in this same buffer.
4430 ;; Don't push another one.
4432 (setq global-mark-ring
(cons (copy-marker (mark-marker)) global-mark-ring
))
4433 (when (> (length global-mark-ring
) global-mark-ring-max
)
4434 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring
)) nil
)
4435 (setcdr (nthcdr (1- global-mark-ring-max
) global-mark-ring
) nil
)))
4436 (or nomsg executing-kbd-macro
(> (minibuffer-depth) 0)
4437 (message "Mark set"))
4438 (if (or activate
(not transient-mark-mode
))
4439 (set-mark (mark t
)))
4443 "Pop off mark ring into the buffer's actual mark.
4444 Does not set point. Does nothing if mark ring is empty."
4446 (setq mark-ring
(nconc mark-ring
(list (copy-marker (mark-marker)))))
4447 (set-marker (mark-marker) (+ 0 (car mark-ring
)) (current-buffer))
4448 (move-marker (car mark-ring
) nil
)
4449 (if (null (mark t
)) (ding))
4450 (setq mark-ring
(cdr mark-ring
)))
4453 (define-obsolete-function-alias
4454 'exchange-dot-and-mark
'exchange-point-and-mark
"23.3")
4455 (defun exchange-point-and-mark (&optional arg
)
4456 "Put the mark where point is now, and point where the mark is now.
4457 This command works even when the mark is not active,
4458 and it reactivates the mark.
4460 If Transient Mark mode is on, a prefix ARG deactivates the mark
4461 if it is active, and otherwise avoids reactivating it. If
4462 Transient Mark mode is off, a prefix ARG enables Transient Mark
4465 (let ((omark (mark t
))
4466 (temp-highlight (eq (car-safe transient-mark-mode
) 'only
)))
4468 (error "No mark set in this buffer"))
4472 (cond (temp-highlight
4473 (setq transient-mark-mode
(cons 'only transient-mark-mode
)))
4474 ((or (and arg
(region-active-p)) ; (xor arg (not (region-active-p)))
4475 (not (or arg
(region-active-p))))
4477 (t (activate-mark)))
4480 (defcustom shift-select-mode t
4481 "When non-nil, shifted motion keys activate the mark momentarily.
4483 While the mark is activated in this way, any shift-translated point
4484 motion key extends the region, and if Transient Mark mode was off, it
4485 is temporarily turned on. Furthermore, the mark will be deactivated
4486 by any subsequent point motion key that was not shift-translated, or
4487 by any action that normally deactivates the mark in Transient Mark mode.
4489 See `this-command-keys-shift-translated' for the meaning of
4492 :group
'editing-basics
)
4494 (defun handle-shift-selection ()
4495 "Activate/deactivate mark depending on invocation thru shift translation.
4496 This function is called by `call-interactively' when a command
4497 with a `^' character in its `interactive' spec is invoked, before
4498 running the command itself.
4500 If `shift-select-mode' is enabled and the command was invoked
4501 through shift translation, set the mark and activate the region
4502 temporarily, unless it was already set in this way. See
4503 `this-command-keys-shift-translated' for the meaning of shift
4506 Otherwise, if the region has been activated temporarily,
4507 deactivate it, and restore the variable `transient-mark-mode' to
4509 (cond ((and shift-select-mode this-command-keys-shift-translated
)
4510 (unless (and mark-active
4511 (eq (car-safe transient-mark-mode
) 'only
))
4512 (setq transient-mark-mode
4514 (unless (eq transient-mark-mode
'lambda
)
4515 transient-mark-mode
)))
4516 (push-mark nil nil t
)))
4517 ((eq (car-safe transient-mark-mode
) 'only
)
4518 (setq transient-mark-mode
(cdr transient-mark-mode
))
4519 (deactivate-mark))))
4521 (define-minor-mode transient-mark-mode
4522 "Toggle Transient Mark mode.
4523 With a prefix argument ARG, enable Transient Mark mode if ARG is
4524 positive, and disable it otherwise. If called from Lisp, enable
4525 Transient Mark mode if ARG is omitted or nil.
4527 Transient Mark mode is a global minor mode. When enabled, the
4528 region is highlighted whenever the mark is active. The mark is
4529 \"deactivated\" by changing the buffer, and after certain other
4530 operations that set the mark but whose main purpose is something
4531 else--for example, incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4533 You can also deactivate the mark by typing \\[keyboard-quit] or
4534 \\[keyboard-escape-quit].
4536 Many commands change their behavior when Transient Mark mode is
4537 in effect and the mark is active, by acting on the region instead
4538 of their usual default part of the buffer's text. Examples of
4539 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
4540 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4541 To see the documentation of commands which are sensitive to the
4542 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
4543 or \"mark.*active\" at the prompt."
4545 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4546 :variable transient-mark-mode
)
4548 (defvar widen-automatically t
4549 "Non-nil means it is ok for commands to call `widen' when they want to.
4550 Some commands will do this in order to go to positions outside
4551 the current accessible part of the buffer.
4553 If `widen-automatically' is nil, these commands will do something else
4554 as a fallback, and won't change the buffer bounds.")
4556 (defvar non-essential nil
4557 "Whether the currently executing code is performing an essential task.
4558 This variable should be non-nil only when running code which should not
4559 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4560 user for a password when we are simply scanning a set of files in the
4561 background or displaying possible completions before the user even asked
4564 (defun pop-global-mark ()
4565 "Pop off global mark ring and jump to the top location."
4567 ;; Pop entries which refer to non-existent buffers.
4568 (while (and global-mark-ring
(not (marker-buffer (car global-mark-ring
))))
4569 (setq global-mark-ring
(cdr global-mark-ring
)))
4570 (or global-mark-ring
4571 (error "No global mark set"))
4572 (let* ((marker (car global-mark-ring
))
4573 (buffer (marker-buffer marker
))
4574 (position (marker-position marker
)))
4575 (setq global-mark-ring
(nconc (cdr global-mark-ring
)
4576 (list (car global-mark-ring
))))
4578 (or (and (>= position
(point-min))
4579 (<= position
(point-max)))
4580 (if widen-automatically
4582 (error "Global mark position is outside accessible part of buffer")))
4583 (goto-char position
)
4584 (switch-to-buffer buffer
)))
4586 (defcustom next-line-add-newlines nil
4587 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4590 :group
'editing-basics
)
4592 (defun next-line (&optional arg try-vscroll
)
4593 "Move cursor vertically down ARG lines.
4594 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4595 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4596 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4597 function will not vscroll.
4601 If there is no character in the target line exactly under the current column,
4602 the cursor is positioned after the character in that line which spans this
4603 column, or at the end of the line if it is not long enough.
4604 If there is no line in the buffer after this one, behavior depends on the
4605 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4606 to create a line, and moves the cursor to that line. Otherwise it moves the
4607 cursor to the end of the buffer.
4609 If the variable `line-move-visual' is non-nil, this command moves
4610 by display lines. Otherwise, it moves by buffer lines, without
4611 taking variable-width characters or continued lines into account.
4613 The command \\[set-goal-column] can be used to create
4614 a semipermanent goal column for this command.
4615 Then instead of trying to move exactly vertically (or as close as possible),
4616 this command moves to the specified goal column (or as close as possible).
4617 The goal column is stored in the variable `goal-column', which is nil
4618 when there is no goal column. Note that setting `goal-column'
4619 overrides `line-move-visual' and causes this command to move by buffer
4620 lines rather than by display lines.
4622 If you are thinking of using this in a Lisp program, consider
4623 using `forward-line' instead. It is usually easier to use
4624 and more reliable (no dependence on goal column, etc.)."
4625 (interactive "^p\np")
4626 (or arg
(setq arg
1))
4627 (if (and next-line-add-newlines
(= arg
1))
4628 (if (save-excursion (end-of-line) (eobp))
4629 ;; When adding a newline, don't expand an abbrev.
4630 (let ((abbrev-mode nil
))
4632 (insert (if use-hard-newlines hard-newline
"\n")))
4633 (line-move arg nil nil try-vscroll
))
4634 (if (called-interactively-p 'interactive
)
4636 (line-move arg nil nil try-vscroll
)
4637 ((beginning-of-buffer end-of-buffer
)
4638 (signal (car err
) (cdr err
))))
4639 (line-move arg nil nil try-vscroll
)))
4642 (defun previous-line (&optional arg try-vscroll
)
4643 "Move cursor vertically up ARG lines.
4644 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4645 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4646 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4647 function will not vscroll.
4651 If there is no character in the target line exactly over the current column,
4652 the cursor is positioned after the character in that line which spans this
4653 column, or at the end of the line if it is not long enough.
4655 If the variable `line-move-visual' is non-nil, this command moves
4656 by display lines. Otherwise, it moves by buffer lines, without
4657 taking variable-width characters or continued lines into account.
4659 The command \\[set-goal-column] can be used to create
4660 a semipermanent goal column for this command.
4661 Then instead of trying to move exactly vertically (or as close as possible),
4662 this command moves to the specified goal column (or as close as possible).
4663 The goal column is stored in the variable `goal-column', which is nil
4664 when there is no goal column. Note that setting `goal-column'
4665 overrides `line-move-visual' and causes this command to move by buffer
4666 lines rather than by display lines.
4668 If you are thinking of using this in a Lisp program, consider using
4669 `forward-line' with a negative argument instead. It is usually easier
4670 to use and more reliable (no dependence on goal column, etc.)."
4671 (interactive "^p\np")
4672 (or arg
(setq arg
1))
4673 (if (called-interactively-p 'interactive
)
4675 (line-move (- arg
) nil nil try-vscroll
)
4676 ((beginning-of-buffer end-of-buffer
)
4677 (signal (car err
) (cdr err
))))
4678 (line-move (- arg
) nil nil try-vscroll
))
4681 (defcustom track-eol nil
4682 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4683 This means moving to the end of each line moved onto.
4684 The beginning of a blank line does not count as the end of a line.
4685 This has no effect when the variable `line-move-visual' is non-nil."
4687 :group
'editing-basics
)
4689 (defcustom goal-column nil
4690 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
4691 A non-nil setting overrides the variable `line-move-visual', which see."
4692 :type
'(choice integer
4693 (const :tag
"None" nil
))
4694 :group
'editing-basics
)
4695 (make-variable-buffer-local 'goal-column
)
4697 (defvar temporary-goal-column
0
4698 "Current goal column for vertical motion.
4699 It is the column where point was at the start of the current run
4700 of vertical motion commands.
4702 When moving by visual lines via the function `line-move-visual', it is a cons
4703 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4704 divided by the default column width, and HSCROLL is the number of
4705 columns by which window is scrolled from left margin.
4707 When the `track-eol' feature is doing its job, the value is
4708 `most-positive-fixnum'.")
4710 (defcustom line-move-ignore-invisible t
4711 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
4712 Outline mode sets this."
4714 :group
'editing-basics
)
4716 (defcustom line-move-visual t
4717 "When non-nil, `line-move' moves point by visual lines.
4718 This movement is based on where the cursor is displayed on the
4719 screen, instead of relying on buffer contents alone. It takes
4720 into account variable-width characters and line continuation.
4721 If nil, `line-move' moves point by logical lines.
4722 A non-nil setting of `goal-column' overrides the value of this variable
4723 and forces movement by logical lines.
4724 A window that is horizontally scrolled also forces movement by logical
4727 :group
'editing-basics
4730 ;; Only used if display-graphic-p.
4731 (declare-function font-info
"font.c" (name &optional frame
))
4733 (defun default-font-height ()
4734 "Return the height in pixels of the current buffer's default face font."
4735 (let ((default-font (face-font 'default
)))
4737 ((and (display-multi-font-p)
4738 ;; Avoid calling font-info if the frame's default font was
4739 ;; not changed since the frame was created. That's because
4740 ;; font-info is expensive for some fonts, see bug #14838.
4741 (not (string= (frame-parameter nil
'font
) default-font
)))
4742 (aref (font-info default-font
) 3))
4743 (t (frame-char-height)))))
4745 (defun default-line-height ()
4746 "Return the pixel height of current buffer's default-face text line.
4748 The value includes `line-spacing', if any, defined for the buffer
4750 (let ((dfh (default-font-height))
4751 (lsp (if (display-graphic-p)
4753 (default-value 'line-spacing
)
4754 (frame-parameter nil
'line-spacing
)
4758 (setq lsp
(* dfh lsp
)))
4761 (defun window-screen-lines ()
4762 "Return the number of screen lines in the text area of the selected window.
4764 This is different from `window-text-height' in that this function counts
4765 lines in units of the height of the font used by the default face displayed
4766 in the window, not in units of the frame's default font, and also accounts
4767 for `line-spacing', if any, defined for the window's buffer or frame.
4769 The value is a floating-point number."
4770 (let ((canonical (window-text-height))
4771 (fch (frame-char-height))
4772 (dlh (default-line-height)))
4773 (/ (* (float canonical
) fch
) dlh
)))
4775 ;; Returns non-nil if partial move was done.
4776 (defun line-move-partial (arg noerror to-end
)
4778 ;; Move backward (up).
4779 ;; If already vscrolled, reduce vscroll
4780 (let ((vs (window-vscroll nil t
))
4781 (dlh (default-line-height)))
4783 (set-window-vscroll nil
(- vs dlh
) t
)))
4785 ;; Move forward (down).
4786 (let* ((lh (window-line-height -
1))
4791 (this-lh (window-line-height))
4792 (this-height (car this-lh
))
4793 (this-ypos (nth 2 this-lh
))
4794 (dlh (default-line-height))
4795 (wslines (window-screen-lines))
4796 (edges (window-inside-pixel-edges))
4797 (winh (- (nth 3 edges
) (nth 1 edges
) 1))
4799 (if (> (mod wslines
1.0) 0.0)
4800 (setq wslines
(round (+ wslines
0.5))))
4805 (<= this-ypos
(- dlh
)))
4807 (let ((wend (pos-visible-in-window-p t nil t
)))
4808 (setq rbot
(nth 3 wend
)
4810 vpos
(nth 5 wend
))))
4812 (let ((wstart (pos-visible-in-window-p nil nil t
)))
4813 (setq this-ypos
(nth 2 wstart
)
4814 this-height
(nth 4 wstart
))))
4817 (let ((ppos (posn-at-point))
4819 (setq col-row
(posn-actual-col-row ppos
))
4821 (- (cdr col-row
) (window-vscroll))
4822 (cdr (posn-col-row ppos
))))))
4823 ;; VPOS > 0 means the last line is only partially visible.
4824 ;; But if the part that is visible is at least as tall as the
4825 ;; default font, that means the line is actually fully
4826 ;; readable, and something like line-spacing is hidden. So in
4827 ;; that case we accept the last line in the window as still
4828 ;; visible, and consider the margin as starting one line
4830 (if (and vpos
(> vpos
0))
4832 (>= rowh
(default-font-height))
4834 (setq last-line
(min (- wslines scroll-margin
) vpos
))
4835 (setq last-line
(min (- wslines scroll-margin
1) (1- vpos
)))))
4837 ;; If last line of window is fully visible, and vscrolling
4838 ;; more would make this line invisible, move forward.
4839 ((and (or (< (setq vs
(window-vscroll nil t
)) dlh
)
4841 (<= this-height dlh
))
4842 (or (null rbot
) (= rbot
0)))
4844 ;; If cursor is not in the bottom scroll margin, and the
4845 ;; current line is is not too tall, move forward.
4846 ((and (or (null this-height
) (<= this-height winh
))
4851 ;; When already vscrolled, we vscroll some more if we can,
4852 ;; or clear vscroll and move forward at end of tall image.
4854 (when (or (and rbot
(> rbot
0))
4855 (and this-height
(> this-height dlh
)))
4856 (set-window-vscroll nil
(+ vs dlh
) t
)))
4857 ;; If cursor just entered the bottom scroll margin, move forward,
4858 ;; but also optionally vscroll one line so redisplay won't recenter.
4862 ;; Don't vscroll if the partially-visible line at window
4863 ;; bottom is not too tall (a.k.a. "just one more text
4864 ;; line"): in that case, we do want redisplay to behave
4865 ;; normally, i.e. recenter or whatever.
4867 ;; Note: ROWH + RBOT from the value returned by
4868 ;; pos-visible-in-window-p give the total height of the
4869 ;; partially-visible glyph row at the end of the window. As
4870 ;; we are dealing with floats, we disregard sub-pixel
4871 ;; discrepancies between that and DLH.
4872 (if (and rowh rbot
(>= (- (+ rowh rbot
) winh
) 1))
4873 (set-window-vscroll nil dlh t
))
4874 (line-move-1 arg noerror to-end
)
4876 ;; If there are lines above the last line, scroll-up one line.
4877 ((and vpos
(> vpos
0))
4880 ;; Finally, start vscroll.
4882 (set-window-vscroll nil dlh t
)))))))
4885 ;; This is like line-move-1 except that it also performs
4886 ;; vertical scrolling of tall images if appropriate.
4887 ;; That is not really a clean thing to do, since it mixes
4888 ;; scrolling with cursor motion. But so far we don't have
4889 ;; a cleaner solution to the problem of making C-n do something
4890 ;; useful given a tall image.
4891 (defun line-move (arg &optional noerror to-end try-vscroll
)
4894 (unless (and auto-window-vscroll try-vscroll
4895 ;; Only vscroll for single line moves
4897 ;; Under scroll-conservatively, the display engine
4898 ;; does this better.
4899 (zerop scroll-conservatively
)
4900 ;; But don't vscroll in a keyboard macro.
4901 (not defining-kbd-macro
)
4902 (not executing-kbd-macro
)
4903 (line-move-partial arg noerror to-end
))
4904 (set-window-vscroll nil
0 t
)
4905 (if (and line-move-visual
4906 ;; Display-based column are incompatible with goal-column.
4908 ;; When the text in the window is scrolled to the left,
4909 ;; display-based motion doesn't make sense (because each
4910 ;; logical line occupies exactly one screen line).
4911 (not (> (window-hscroll) 0)))
4912 (prog1 (line-move-visual arg noerror
)
4913 ;; If we moved into a tall line, set vscroll to make
4914 ;; scrolling through tall images more smooth.
4915 (let ((lh (line-pixel-height))
4916 (edges (window-inside-pixel-edges))
4917 (dlh (default-line-height))
4919 (setq winh
(- (nth 3 edges
) (nth 1 edges
) 1))
4921 (< (point) (window-start))
4926 (line-move-1 arg noerror to-end
)))))
4928 ;; Display-based alternative to line-move-1.
4929 ;; Arg says how many lines to move. The value is t if we can move the
4930 ;; specified number of lines.
4931 (defun line-move-visual (arg &optional noerror
)
4932 (let ((opoint (point))
4933 (hscroll (window-hscroll))
4935 ;; Check if the previous command was a line-motion command, or if
4936 ;; we were called from some other command.
4937 (if (and (consp temporary-goal-column
)
4938 (memq last-command
`(next-line previous-line
,this-command
)))
4939 ;; If so, there's no need to reset `temporary-goal-column',
4940 ;; but we may need to hscroll.
4941 (if (or (/= (cdr temporary-goal-column
) hscroll
)
4942 (> (cdr temporary-goal-column
) 0))
4943 (setq target-hscroll
(cdr temporary-goal-column
)))
4944 ;; Otherwise, we should reset `temporary-goal-column'.
4945 (let ((posn (posn-at-point)))
4947 ;; Handle the `overflow-newline-into-fringe' case:
4948 ((eq (nth 1 posn
) 'right-fringe
)
4949 (setq temporary-goal-column
(cons (- (window-width) 1) hscroll
)))
4950 ((car (posn-x-y posn
))
4951 (setq temporary-goal-column
4952 (cons (/ (float (car (posn-x-y posn
)))
4953 (frame-char-width)) hscroll
))))))
4955 (set-window-hscroll (selected-window) target-hscroll
))
4956 ;; vertical-motion can move more than it was asked to if it moves
4957 ;; across display strings with newlines. We don't want to ring
4958 ;; the bell and announce beginning/end of buffer in that case.
4959 (or (and (or (and (>= arg
0)
4960 (>= (vertical-motion
4961 (cons (or goal-column
4962 (if (consp temporary-goal-column
)
4963 (car temporary-goal-column
)
4964 temporary-goal-column
))
4968 (<= (vertical-motion
4969 (cons (or goal-column
4970 (if (consp temporary-goal-column
)
4971 (car temporary-goal-column
)
4972 temporary-goal-column
))
4977 ;; If the goal column lies on a display string,
4978 ;; `vertical-motion' advances the cursor to the end
4979 ;; of the string. For arg < 0, this can cause the
4980 ;; cursor to get stuck. (Bug#3020).
4981 (= (vertical-motion arg
) arg
)))
4983 (signal (if (< arg
0) 'beginning-of-buffer
'end-of-buffer
)
4986 ;; This is the guts of next-line and previous-line.
4987 ;; Arg says how many lines to move.
4988 ;; The value is t if we can move the specified number of lines.
4989 (defun line-move-1 (arg &optional noerror _to-end
)
4990 ;; Don't run any point-motion hooks, and disregard intangibility,
4991 ;; for intermediate positions.
4992 (let ((inhibit-point-motion-hooks t
)
4995 (if (consp temporary-goal-column
)
4996 (setq temporary-goal-column
(+ (car temporary-goal-column
)
4997 (cdr temporary-goal-column
))))
5000 (if (not (memq last-command
'(next-line previous-line
)))
5001 (setq temporary-goal-column
5002 (if (and track-eol
(eolp)
5003 ;; Don't count beg of empty line as end of line
5004 ;; unless we just did explicit end-of-line.
5005 (or (not (bolp)) (eq last-command
'move-end-of-line
)))
5006 most-positive-fixnum
5009 (if (not (or (integerp selective-display
)
5010 line-move-ignore-invisible
))
5011 ;; Use just newline characters.
5012 ;; Set ARG to 0 if we move as many lines as requested.
5014 (progn (if (> arg
1) (forward-line (1- arg
)))
5015 ;; This way of moving forward ARG lines
5016 ;; verifies that we have a newline after the last one.
5017 ;; It doesn't get confused by intangible text.
5019 (if (zerop (forward-line 1))
5021 (and (zerop (forward-line arg
))
5025 (signal (if (< arg
0)
5026 'beginning-of-buffer
5029 ;; Move by arg lines, but ignore invisible ones.
5031 (while (and (> arg
0) (not done
))
5032 ;; If the following character is currently invisible,
5033 ;; skip all characters with that same `invisible' property value.
5034 (while (and (not (eobp)) (invisible-p (point)))
5035 (goto-char (next-char-property-change (point))))
5037 ;; We don't use `end-of-line', since we want to escape
5038 ;; from field boundaries occurring exactly at point.
5039 (goto-char (constrain-to-field
5040 (let ((inhibit-field-text-motion t
))
5041 (line-end-position))
5043 'inhibit-line-move-field-capture
))
5044 ;; If there's no invisibility here, move over the newline.
5048 (signal 'end-of-buffer nil
)
5050 ((and (> arg
1) ;; Use vertical-motion for last move
5051 (not (integerp selective-display
))
5052 (not (invisible-p (point))))
5053 ;; We avoid vertical-motion when possible
5054 ;; because that has to fontify.
5056 ;; Otherwise move a more sophisticated way.
5057 ((zerop (vertical-motion 1))
5059 (signal 'end-of-buffer nil
)
5062 (setq arg
(1- arg
))))
5063 ;; The logic of this is the same as the loop above,
5064 ;; it just goes in the other direction.
5065 (while (and (< arg
0) (not done
))
5066 ;; For completely consistency with the forward-motion
5067 ;; case, we should call beginning-of-line here.
5068 ;; However, if point is inside a field and on a
5069 ;; continued line, the call to (vertical-motion -1)
5070 ;; below won't move us back far enough; then we return
5071 ;; to the same column in line-move-finish, and point
5072 ;; gets stuck -- cyd
5077 (signal 'beginning-of-buffer nil
)
5079 ((and (< arg -
1) ;; Use vertical-motion for last move
5080 (not (integerp selective-display
))
5081 (not (invisible-p (1- (point)))))
5083 ((zerop (vertical-motion -
1))
5085 (signal 'beginning-of-buffer nil
)
5089 (while (and ;; Don't move over previous invis lines
5090 ;; if our target is the middle of this line.
5091 (or (zerop (or goal-column temporary-goal-column
))
5093 (not (bobp)) (invisible-p (1- (point))))
5094 (goto-char (previous-char-property-change (point))))))))
5095 ;; This is the value the function returns.
5099 ;; If we did not move down as far as desired, at least go
5100 ;; to end of line. Be sure to call point-entered and
5101 ;; point-left-hooks.
5102 (let* ((npoint (prog1 (line-end-position)
5103 (goto-char opoint
)))
5104 (inhibit-point-motion-hooks nil
))
5105 (goto-char npoint
)))
5107 ;; If we did not move up as far as desired,
5108 ;; at least go to beginning of line.
5109 (let* ((npoint (prog1 (line-beginning-position)
5110 (goto-char opoint
)))
5111 (inhibit-point-motion-hooks nil
))
5112 (goto-char npoint
)))
5114 (line-move-finish (or goal-column temporary-goal-column
)
5115 opoint
(> orig-arg
0)))))))
5117 (defun line-move-finish (column opoint forward
)
5120 ;; Set REPEAT to t to repeat the whole thing.
5125 (line-beg (line-beginning-position))
5127 ;; Compute the end of the line
5128 ;; ignoring effectively invisible newlines.
5130 ;; Like end-of-line but ignores fields.
5131 (skip-chars-forward "^\n")
5132 (while (and (not (eobp)) (invisible-p (point)))
5133 (goto-char (next-char-property-change (point)))
5134 (skip-chars-forward "^\n"))
5137 ;; Move to the desired column.
5138 (line-move-to-column (truncate column
))
5140 ;; Corner case: suppose we start out in a field boundary in
5141 ;; the middle of a continued line. When we get to
5142 ;; line-move-finish, point is at the start of a new *screen*
5143 ;; line but the same text line; then line-move-to-column would
5144 ;; move us backwards. Test using C-n with point on the "x" in
5145 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
5152 ;; Process intangibility within a line.
5153 ;; With inhibit-point-motion-hooks bound to nil, a call to
5154 ;; goto-char moves point past intangible text.
5156 ;; However, inhibit-point-motion-hooks controls both the
5157 ;; intangibility and the point-entered/point-left hooks. The
5158 ;; following hack avoids calling the point-* hooks
5159 ;; unnecessarily. Note that we move *forward* past intangible
5160 ;; text when the initial and final points are the same.
5162 (let ((inhibit-point-motion-hooks nil
))
5165 ;; If intangibility moves us to a different (later) place
5166 ;; in the same line, use that as the destination.
5167 (if (<= (point) line-end
)
5169 ;; If that position is "too late",
5170 ;; try the previous allowable position.
5174 ;; If going forward, don't accept the previous
5175 ;; allowable position if it is before the target line.
5176 (< line-beg
(point))
5177 ;; If going backward, don't accept the previous
5178 ;; allowable position if it is still after the target line.
5179 (<= (point) line-end
))
5181 ;; As a last resort, use the end of the line.
5182 (setq new line-end
))))
5184 ;; Now move to the updated destination, processing fields
5185 ;; as well as intangibility.
5187 (let ((inhibit-point-motion-hooks nil
))
5189 ;; Ignore field boundaries if the initial and final
5190 ;; positions have the same `field' property, even if the
5191 ;; fields are non-contiguous. This seems to be "nicer"
5192 ;; behavior in many situations.
5193 (if (eq (get-char-property new
'field
)
5194 (get-char-property opoint
'field
))
5196 (constrain-to-field new opoint t t
5197 'inhibit-line-move-field-capture
))))
5199 ;; If all this moved us to a different line,
5200 ;; retry everything within that new line.
5201 (when (or (< (point) line-beg
) (> (point) line-end
))
5202 ;; Repeat the intangibility and field processing.
5203 (setq repeat t
))))))
5205 (defun line-move-to-column (col)
5206 "Try to find column COL, considering invisibility.
5207 This function works only in certain cases,
5208 because what we really need is for `move-to-column'
5209 and `current-column' to be able to ignore invisible text."
5212 (move-to-column col
))
5214 (when (and line-move-ignore-invisible
5215 (not (bolp)) (invisible-p (1- (point))))
5216 (let ((normal-location (point))
5217 (normal-column (current-column)))
5218 ;; If the following character is currently invisible,
5219 ;; skip all characters with that same `invisible' property value.
5220 (while (and (not (eobp))
5221 (invisible-p (point)))
5222 (goto-char (next-char-property-change (point))))
5223 ;; Have we advanced to a larger column position?
5224 (if (> (current-column) normal-column
)
5225 ;; We have made some progress towards the desired column.
5226 ;; See if we can make any further progress.
5227 (line-move-to-column (+ (current-column) (- col normal-column
)))
5228 ;; Otherwise, go to the place we originally found
5229 ;; and move back over invisible text.
5230 ;; that will get us to the same place on the screen
5231 ;; but with a more reasonable buffer position.
5232 (goto-char normal-location
)
5233 (let ((line-beg (line-beginning-position)))
5234 (while (and (not (bolp)) (invisible-p (1- (point))))
5235 (goto-char (previous-char-property-change (point) line-beg
))))))))
5237 (defun move-end-of-line (arg)
5238 "Move point to end of current line as displayed.
5239 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5240 If point reaches the beginning or end of buffer, it stops there.
5242 To ignore the effects of the `intangible' text or overlay
5243 property, bind `inhibit-point-motion-hooks' to t.
5244 If there is an image in the current line, this function
5245 disregards newlines that are part of the text on which the image
5248 (or arg
(setq arg
1))
5253 (let ((goal-column 0)
5254 (line-move-visual nil
))
5255 (and (line-move arg t
)
5256 ;; With bidi reordering, we may not be at bol,
5257 ;; so make sure we are.
5258 (skip-chars-backward "^\n")
5261 (while (and (not (bobp)) (invisible-p (1- (point))))
5262 (goto-char (previous-single-char-property-change
5263 (point) 'invisible
)))
5267 (if (and (> (point) newpos
)
5268 (eq (preceding-char) ?
\n))
5270 (if (and (> (point) newpos
) (not (eobp))
5271 (not (eq (following-char) ?
\n)))
5272 ;; If we skipped something intangible and now we're not
5273 ;; really at eol, keep going.
5277 (defun move-beginning-of-line (arg)
5278 "Move point to beginning of current line as displayed.
5279 \(If there's an image in the line, this disregards newlines
5280 which are part of the text that the image rests on.)
5282 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5283 If point reaches the beginning or end of buffer, it stops there.
5284 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5286 (or arg
(setq arg
1))
5288 (let ((orig (point))
5289 first-vis first-vis-field-value
)
5291 ;; Move by lines, if ARG is not 1 (the default).
5293 (let ((line-move-visual nil
))
5294 (line-move (1- arg
) t
)))
5296 ;; Move to beginning-of-line, ignoring fields and invisible text.
5297 (skip-chars-backward "^\n")
5298 (while (and (not (bobp)) (invisible-p (1- (point))))
5299 (goto-char (previous-char-property-change (point)))
5300 (skip-chars-backward "^\n"))
5302 ;; Now find first visible char in the line
5303 (while (and (not (eobp)) (invisible-p (point)))
5304 (goto-char (next-char-property-change (point))))
5305 (setq first-vis
(point))
5307 ;; See if fields would stop us from reaching FIRST-VIS.
5308 (setq first-vis-field-value
5309 (constrain-to-field first-vis orig
(/= arg
1) t nil
))
5311 (goto-char (if (/= first-vis-field-value first-vis
)
5312 ;; If yes, obey them.
5313 first-vis-field-value
5314 ;; Otherwise, move to START with attention to fields.
5315 ;; (It is possible that fields never matter in this case.)
5316 (constrain-to-field (point) orig
5317 (/= arg
1) t nil
)))))
5320 ;; Many people have said they rarely use this feature, and often type
5321 ;; it by accident. Maybe it shouldn't even be on a key.
5322 (put 'set-goal-column
'disabled t
)
5324 (defun set-goal-column (arg)
5325 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
5326 Those commands will move to this position in the line moved to
5327 rather than trying to keep the same horizontal position.
5328 With a non-nil argument ARG, clears out the goal column
5329 so that \\[next-line] and \\[previous-line] resume vertical motion.
5330 The goal column is stored in the variable `goal-column'."
5334 (setq goal-column nil
)
5335 (message "No goal column"))
5336 (setq goal-column
(current-column))
5337 ;; The older method below can be erroneous if `set-goal-column' is bound
5338 ;; to a sequence containing %
5339 ;;(message (substitute-command-keys
5340 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
5344 (format "Goal column %d " goal-column
)
5345 (substitute-command-keys
5346 "(use \\[set-goal-column] with an arg to unset it)")))
5351 ;;; Editing based on visual lines, as opposed to logical lines.
5353 (defun end-of-visual-line (&optional n
)
5354 "Move point to end of current visual line.
5355 With argument N not nil or 1, move forward N - 1 visual lines first.
5356 If point reaches the beginning or end of buffer, it stops there.
5357 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5361 (let ((line-move-visual t
))
5362 (line-move (1- n
) t
)))
5363 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
5364 ;; constrain to field boundaries, so we don't either.
5365 (vertical-motion (cons (window-width) 0)))
5367 (defun beginning-of-visual-line (&optional n
)
5368 "Move point to beginning of current visual line.
5369 With argument N not nil or 1, move forward N - 1 visual lines first.
5370 If point reaches the beginning or end of buffer, it stops there.
5371 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5374 (let ((opoint (point)))
5376 (let ((line-move-visual t
))
5377 (line-move (1- n
) t
)))
5379 ;; Constrain to field boundaries, like `move-beginning-of-line'.
5380 (goto-char (constrain-to-field (point) opoint
(/= n
1)))))
5382 (defun kill-visual-line (&optional arg
)
5383 "Kill the rest of the visual line.
5384 With prefix argument ARG, kill that many visual lines from point.
5385 If ARG is negative, kill visual lines backward.
5386 If ARG is zero, kill the text before point on the current visual
5389 If you want to append the killed line to the last killed text,
5390 use \\[append-next-kill] before \\[kill-line].
5392 If the buffer is read-only, Emacs will beep and refrain from deleting
5393 the line, but put the line in the kill ring anyway. This means that
5394 you can use this command to copy text from a read-only buffer.
5395 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5398 ;; Like in `kill-line', it's better to move point to the other end
5399 ;; of the kill before killing.
5400 (let ((opoint (point))
5401 (kill-whole-line (and kill-whole-line
(bolp))))
5403 (vertical-motion (prefix-numeric-value arg
))
5404 (end-of-visual-line 1)
5405 (if (= (point) opoint
)
5407 ;; Skip any trailing whitespace at the end of the visual line.
5408 ;; We used to do this only if `show-trailing-whitespace' is
5409 ;; nil, but that's wrong; the correct thing would be to check
5410 ;; whether the trailing whitespace is highlighted. But, it's
5411 ;; OK to just do this unconditionally.
5412 (skip-chars-forward " \t")))
5413 (kill-region opoint
(if (and kill-whole-line
(looking-at "\n"))
5417 (defun next-logical-line (&optional arg try-vscroll
)
5418 "Move cursor vertically down ARG lines.
5419 This is identical to `next-line', except that it always moves
5420 by logical lines instead of visual lines, ignoring the value of
5421 the variable `line-move-visual'."
5422 (interactive "^p\np")
5423 (let ((line-move-visual nil
))
5425 (next-line arg try-vscroll
))))
5427 (defun previous-logical-line (&optional arg try-vscroll
)
5428 "Move cursor vertically up ARG lines.
5429 This is identical to `previous-line', except that it always moves
5430 by logical lines instead of visual lines, ignoring the value of
5431 the variable `line-move-visual'."
5432 (interactive "^p\np")
5433 (let ((line-move-visual nil
))
5435 (previous-line arg try-vscroll
))))
5437 (defgroup visual-line nil
5438 "Editing based on visual lines."
5442 (defvar visual-line-mode-map
5443 (let ((map (make-sparse-keymap)))
5444 (define-key map
[remap kill-line
] 'kill-visual-line
)
5445 (define-key map
[remap move-beginning-of-line
] 'beginning-of-visual-line
)
5446 (define-key map
[remap move-end-of-line
] 'end-of-visual-line
)
5447 ;; These keybindings interfere with xterm function keys. Are
5448 ;; there any other suitable bindings?
5449 ;; (define-key map "\M-[" 'previous-logical-line)
5450 ;; (define-key map "\M-]" 'next-logical-line)
5453 (defcustom visual-line-fringe-indicators
'(nil nil
)
5454 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
5455 The value should be a list of the form (LEFT RIGHT), where LEFT
5456 and RIGHT are symbols representing the bitmaps to display, to
5457 indicate wrapped lines, in the left and right fringes respectively.
5458 See also `fringe-indicator-alist'.
5459 The default is not to display fringe indicators for wrapped lines.
5460 This variable does not affect fringe indicators displayed for
5462 :type
'(list (choice (const :tag
"Hide left indicator" nil
)
5463 (const :tag
"Left curly arrow" left-curly-arrow
)
5464 (symbol :tag
"Other bitmap"))
5465 (choice (const :tag
"Hide right indicator" nil
)
5466 (const :tag
"Right curly arrow" right-curly-arrow
)
5467 (symbol :tag
"Other bitmap")))
5468 :set
(lambda (symbol value
)
5469 (dolist (buf (buffer-list))
5470 (with-current-buffer buf
5471 (when (and (boundp 'visual-line-mode
)
5472 (symbol-value 'visual-line-mode
))
5473 (setq fringe-indicator-alist
5474 (cons (cons 'continuation value
)
5477 (copy-tree fringe-indicator-alist
)))))))
5478 (set-default symbol value
)))
5480 (defvar visual-line--saved-state nil
)
5482 (define-minor-mode visual-line-mode
5483 "Toggle visual line based editing (Visual Line mode).
5484 With a prefix argument ARG, enable Visual Line mode if ARG is
5485 positive, and disable it otherwise. If called from Lisp, enable
5486 the mode if ARG is omitted or nil.
5488 When Visual Line mode is enabled, `word-wrap' is turned on in
5489 this buffer, and simple editing commands are redefined to act on
5490 visual lines, not logical lines. See Info node `Visual Line
5492 :keymap visual-line-mode-map
5495 (if visual-line-mode
5497 (set (make-local-variable 'visual-line--saved-state
) nil
)
5498 ;; Save the local values of some variables, to be restored if
5499 ;; visual-line-mode is turned off.
5500 (dolist (var '(line-move-visual truncate-lines
5501 truncate-partial-width-windows
5502 word-wrap fringe-indicator-alist
))
5503 (if (local-variable-p var
)
5504 (push (cons var
(symbol-value var
))
5505 visual-line--saved-state
)))
5506 (set (make-local-variable 'line-move-visual
) t
)
5507 (set (make-local-variable 'truncate-partial-width-windows
) nil
)
5508 (setq truncate-lines nil
5510 fringe-indicator-alist
5511 (cons (cons 'continuation visual-line-fringe-indicators
)
5512 fringe-indicator-alist
)))
5513 (kill-local-variable 'line-move-visual
)
5514 (kill-local-variable 'word-wrap
)
5515 (kill-local-variable 'truncate-lines
)
5516 (kill-local-variable 'truncate-partial-width-windows
)
5517 (kill-local-variable 'fringe-indicator-alist
)
5518 (dolist (saved visual-line--saved-state
)
5519 (set (make-local-variable (car saved
)) (cdr saved
)))
5520 (kill-local-variable 'visual-line--saved-state
)))
5522 (defun turn-on-visual-line-mode ()
5523 (visual-line-mode 1))
5525 (define-globalized-minor-mode global-visual-line-mode
5526 visual-line-mode turn-on-visual-line-mode
)
5529 (defun transpose-chars (arg)
5530 "Interchange characters around point, moving forward one character.
5531 With prefix arg ARG, effect is to take character before point
5532 and drag it forward past ARG other characters (backward if ARG negative).
5533 If no argument and at end of line, the previous two chars are exchanged."
5535 (and (null arg
) (eolp) (forward-char -
1))
5536 (transpose-subr 'forward-char
(prefix-numeric-value arg
)))
5538 (defun transpose-words (arg)
5539 "Interchange words around point, leaving point at end of them.
5540 With prefix arg ARG, effect is to take word before or around point
5541 and drag it forward past ARG other words (backward if ARG negative).
5542 If ARG is zero, the words around or after point and around or after mark
5544 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
5546 (transpose-subr 'forward-word arg
))
5548 (defun transpose-sexps (arg)
5549 "Like \\[transpose-words] but applies to sexps.
5550 Does not work on a sexp that point is in the middle of
5551 if it is a list or string."
5555 ;; Here we should try to simulate the behavior of
5556 ;; (cons (progn (forward-sexp x) (point))
5557 ;; (progn (forward-sexp (- x)) (point)))
5558 ;; Except that we don't want to rely on the second forward-sexp
5559 ;; putting us back to where we want to be, since forward-sexp-function
5560 ;; might do funny things like infix-precedence.
5562 (looking-at "\\sw\\|\\s_")
5564 (save-excursion (forward-char -
1) (looking-at "\\sw\\|\\s_"))))
5565 ;; Jumping over a symbol. We might be inside it, mind you.
5566 (progn (funcall (if (> arg
0)
5567 'skip-syntax-backward
'skip-syntax-forward
)
5569 (cons (save-excursion (forward-sexp arg
) (point)) (point)))
5570 ;; Otherwise, we're between sexps. Take a step back before jumping
5571 ;; to make sure we'll obey the same precedence no matter which direction
5573 (funcall (if (> arg
0) 'skip-syntax-backward
'skip-syntax-forward
) " .")
5574 (cons (save-excursion (forward-sexp arg
) (point))
5575 (progn (while (or (forward-comment (if (> arg
0) 1 -
1))
5576 (not (zerop (funcall (if (> arg
0)
5577 'skip-syntax-forward
5578 'skip-syntax-backward
)
5583 (defun transpose-lines (arg)
5584 "Exchange current line and previous line, leaving point after both.
5585 With argument ARG, takes previous line and moves it past ARG lines.
5586 With argument 0, interchanges line point is in with line mark is in."
5588 (transpose-subr (function
5592 ;; Move forward over ARG lines,
5593 ;; but create newlines if necessary.
5594 (setq arg
(forward-line arg
))
5595 (if (/= (preceding-char) ?
\n)
5596 (setq arg
(1+ arg
)))
5599 (forward-line arg
))))
5602 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
5603 ;; which seems inconsistent with the ARG /= 0 case.
5604 ;; FIXME document SPECIAL.
5605 (defun transpose-subr (mover arg
&optional special
)
5606 "Subroutine to do the work of transposing objects.
5607 Works for lines, sentences, paragraphs, etc. MOVER is a function that
5608 moves forward by units of the given object (e.g. forward-sentence,
5609 forward-paragraph). If ARG is zero, exchanges the current object
5610 with the one containing mark. If ARG is an integer, moves the
5611 current object past ARG following (if ARG is positive) or
5612 preceding (if ARG is negative) objects, leaving point after the
5614 (let ((aux (if special mover
5616 (cons (progn (funcall mover x
) (point))
5617 (progn (funcall mover
(- x
)) (point))))))
5622 (setq pos1
(funcall aux
1))
5623 (goto-char (or (mark) (error "No mark set in this buffer")))
5624 (setq pos2
(funcall aux
1))
5625 (transpose-subr-1 pos1 pos2
))
5626 (exchange-point-and-mark))
5628 (setq pos1
(funcall aux -
1))
5629 (setq pos2
(funcall aux arg
))
5630 (transpose-subr-1 pos1 pos2
)
5631 (goto-char (car pos2
)))
5633 (setq pos1
(funcall aux -
1))
5634 (goto-char (car pos1
))
5635 (setq pos2
(funcall aux arg
))
5636 (transpose-subr-1 pos1 pos2
)))))
5638 (defun transpose-subr-1 (pos1 pos2
)
5639 (when (> (car pos1
) (cdr pos1
)) (setq pos1
(cons (cdr pos1
) (car pos1
))))
5640 (when (> (car pos2
) (cdr pos2
)) (setq pos2
(cons (cdr pos2
) (car pos2
))))
5641 (when (> (car pos1
) (car pos2
))
5643 (setq pos1 pos2 pos2 swap
)))
5644 (if (> (cdr pos1
) (car pos2
)) (error "Don't have two things to transpose"))
5645 (atomic-change-group
5646 ;; This sequence of insertions attempts to preserve marker
5647 ;; positions at the start and end of the transposed objects.
5648 (let* ((word (buffer-substring (car pos2
) (cdr pos2
)))
5649 (len1 (- (cdr pos1
) (car pos1
)))
5650 (len2 (length word
))
5651 (boundary (make-marker)))
5652 (set-marker boundary
(car pos2
))
5653 (goto-char (cdr pos1
))
5654 (insert-before-markers word
)
5655 (setq word
(delete-and-extract-region (car pos1
) (+ (car pos1
) len1
)))
5656 (goto-char boundary
)
5658 (goto-char (+ boundary len1
))
5659 (delete-region (point) (+ (point) len2
))
5660 (set-marker boundary nil
))))
5662 (defun backward-word (&optional arg
)
5663 "Move backward until encountering the beginning of a word.
5664 With argument ARG, do this that many times.
5665 If ARG is omitted or nil, move point backward one word."
5667 (forward-word (- (or arg
1))))
5669 (defun mark-word (&optional arg allow-extend
)
5670 "Set mark ARG words away from point.
5671 The place mark goes is the same place \\[forward-word] would
5672 move to with the same argument.
5673 Interactively, if this command is repeated
5674 or (in Transient Mark mode) if the mark is active,
5675 it marks the next ARG words after the ones already marked."
5676 (interactive "P\np")
5677 (cond ((and allow-extend
5678 (or (and (eq last-command this-command
) (mark t
))
5680 (setq arg
(if arg
(prefix-numeric-value arg
)
5681 (if (< (mark) (point)) -
1 1)))
5690 (forward-word (prefix-numeric-value arg
))
5694 (defun kill-word (arg)
5695 "Kill characters forward until encountering the end of a word.
5696 With argument ARG, do this that many times."
5698 (kill-region (point) (progn (forward-word arg
) (point))))
5700 (defun backward-kill-word (arg)
5701 "Kill characters backward until encountering the beginning of a word.
5702 With argument ARG, do this that many times."
5704 (kill-word (- arg
)))
5706 (defun current-word (&optional strict really-word
)
5707 "Return the symbol or word that point is on (or a nearby one) as a string.
5708 The return value includes no text properties.
5709 If optional arg STRICT is non-nil, return nil unless point is within
5710 or adjacent to a symbol or word. In all cases the value can be nil
5711 if there is no word nearby.
5712 The function, belying its name, normally finds a symbol.
5713 If optional arg REALLY-WORD is non-nil, it finds just a word."
5715 (let* ((oldpoint (point)) (start (point)) (end (point))
5716 (syntaxes (if really-word
"w" "w_"))
5717 (not-syntaxes (concat "^" syntaxes
)))
5718 (skip-syntax-backward syntaxes
) (setq start
(point))
5719 (goto-char oldpoint
)
5720 (skip-syntax-forward syntaxes
) (setq end
(point))
5721 (when (and (eq start oldpoint
) (eq end oldpoint
)
5722 ;; Point is neither within nor adjacent to a word.
5724 ;; Look for preceding word in same line.
5725 (skip-syntax-backward not-syntaxes
(line-beginning-position))
5727 ;; No preceding word in same line.
5728 ;; Look for following word in same line.
5730 (skip-syntax-forward not-syntaxes
(line-end-position))
5731 (setq start
(point))
5732 (skip-syntax-forward syntaxes
)
5735 (skip-syntax-backward syntaxes
)
5736 (setq start
(point))))
5737 ;; If we found something nonempty, return it as a string.
5738 (unless (= start end
)
5739 (buffer-substring-no-properties start end
)))))
5741 (defcustom fill-prefix nil
5742 "String for filling to insert at front of new line, or nil for none."
5743 :type
'(choice (const :tag
"None" nil
)
5746 (make-variable-buffer-local 'fill-prefix
)
5747 (put 'fill-prefix
'safe-local-variable
'string-or-null-p
)
5749 (defcustom auto-fill-inhibit-regexp nil
5750 "Regexp to match lines which should not be auto-filled."
5751 :type
'(choice (const :tag
"None" nil
)
5755 (defun do-auto-fill ()
5756 "The default value for `normal-auto-fill-function'.
5757 This is the default auto-fill function, some major modes use a different one.
5758 Returns t if it really did any work."
5759 (let (fc justify give-up
5760 (fill-prefix fill-prefix
))
5761 (if (or (not (setq justify
(current-justification)))
5762 (null (setq fc
(current-fill-column)))
5763 (and (eq justify
'left
)
5764 (<= (current-column) fc
))
5765 (and auto-fill-inhibit-regexp
5766 (save-excursion (beginning-of-line)
5767 (looking-at auto-fill-inhibit-regexp
))))
5768 nil
;; Auto-filling not required
5769 (if (memq justify
'(full center right
))
5770 (save-excursion (unjustify-current-line)))
5772 ;; Choose a fill-prefix automatically.
5773 (when (and adaptive-fill-mode
5774 (or (null fill-prefix
) (string= fill-prefix
"")))
5776 (fill-context-prefix
5777 (save-excursion (fill-forward-paragraph -
1) (point))
5778 (save-excursion (fill-forward-paragraph 1) (point)))))
5779 (and prefix
(not (equal prefix
""))
5780 ;; Use auto-indentation rather than a guessed empty prefix.
5781 (not (and fill-indent-according-to-mode
5782 (string-match "\\`[ \t]*\\'" prefix
)))
5783 (setq fill-prefix prefix
))))
5785 (while (and (not give-up
) (> (current-column) fc
))
5786 ;; Determine where to split the line.
5791 (setq after-prefix
(point))
5793 (looking-at (regexp-quote fill-prefix
))
5794 (setq after-prefix
(match-end 0)))
5795 (move-to-column (1+ fc
))
5796 (fill-move-to-break-point after-prefix
)
5799 ;; See whether the place we found is any good.
5801 (goto-char fill-point
)
5803 ;; There is no use breaking at end of line.
5804 (save-excursion (skip-chars-forward " ") (eolp))
5805 ;; It is futile to split at the end of the prefix
5806 ;; since we would just insert the prefix again.
5807 (and after-prefix
(<= (point) after-prefix
))
5808 ;; Don't split right after a comment starter
5809 ;; since we would just make another comment starter.
5810 (and comment-start-skip
5811 (let ((limit (point)))
5813 (and (re-search-forward comment-start-skip
5815 (eq (point) limit
))))))
5816 ;; No good place to break => stop trying.
5818 ;; Ok, we have a useful place to break the line. Do it.
5819 (let ((prev-column (current-column)))
5820 ;; If point is at the fill-point, do not `save-excursion'.
5821 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5822 ;; point will end up before it rather than after it.
5824 (skip-chars-backward " \t")
5825 (= (point) fill-point
))
5826 (default-indent-new-line t
)
5828 (goto-char fill-point
)
5829 (default-indent-new-line t
)))
5830 ;; Now do justification, if required
5831 (if (not (eq justify
'left
))
5834 (justify-current-line justify nil t
)))
5835 ;; If making the new line didn't reduce the hpos of
5836 ;; the end of the line, then give up now;
5837 ;; trying again will not help.
5838 (if (>= (current-column) prev-column
)
5839 (setq give-up t
))))))
5840 ;; Justify last line.
5841 (justify-current-line justify t t
)
5844 (defvar comment-line-break-function
'comment-indent-new-line
5845 "Mode-specific function which line breaks and continues a comment.
5846 This function is called during auto-filling when a comment syntax
5848 The function should take a single optional argument, which is a flag
5849 indicating whether it should use soft newlines.")
5851 (defun default-indent-new-line (&optional soft
)
5852 "Break line at point and indent.
5853 If a comment syntax is defined, call `comment-indent-new-line'.
5855 The inserted newline is marked hard if variable `use-hard-newlines' is true,
5856 unless optional argument SOFT is non-nil."
5859 (funcall comment-line-break-function soft
)
5860 ;; Insert the newline before removing empty space so that markers
5861 ;; get preserved better.
5862 (if soft
(insert-and-inherit ?
\n) (newline 1))
5863 (save-excursion (forward-char -
1) (delete-horizontal-space))
5864 (delete-horizontal-space)
5866 (if (and fill-prefix
(not adaptive-fill-mode
))
5867 ;; Blindly trust a non-adaptive fill-prefix.
5869 (indent-to-left-margin)
5870 (insert-before-markers-and-inherit fill-prefix
))
5873 ;; If there's an adaptive prefix, use it unless we're inside
5874 ;; a comment and the prefix is not a comment starter.
5876 (indent-to-left-margin)
5877 (insert-and-inherit fill-prefix
))
5878 ;; If we're not inside a comment, just try to indent.
5879 (t (indent-according-to-mode))))))
5881 (defvar normal-auto-fill-function
'do-auto-fill
5882 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
5883 Some major modes set this.")
5885 (put 'auto-fill-function
:minor-mode-function
'auto-fill-mode
)
5886 ;; `functions' and `hooks' are usually unsafe to set, but setting
5887 ;; auto-fill-function to nil in a file-local setting is safe and
5888 ;; can be useful to prevent auto-filling.
5889 (put 'auto-fill-function
'safe-local-variable
'null
)
5891 (define-minor-mode auto-fill-mode
5892 "Toggle automatic line breaking (Auto Fill mode).
5893 With a prefix argument ARG, enable Auto Fill mode if ARG is
5894 positive, and disable it otherwise. If called from Lisp, enable
5895 the mode if ARG is omitted or nil.
5897 When Auto Fill mode is enabled, inserting a space at a column
5898 beyond `current-fill-column' automatically breaks the line at a
5901 When `auto-fill-mode' is on, the `auto-fill-function' variable is
5904 The value of `normal-auto-fill-function' specifies the function to use
5905 for `auto-fill-function' when turning Auto Fill mode on."
5906 :variable
(auto-fill-function
5907 .
(lambda (v) (setq auto-fill-function
5908 (if v normal-auto-fill-function
)))))
5910 ;; This holds a document string used to document auto-fill-mode.
5911 (defun auto-fill-function ()
5912 "Automatically break line at a previous space, in insertion of text."
5915 (defun turn-on-auto-fill ()
5916 "Unconditionally turn on Auto Fill mode."
5919 (defun turn-off-auto-fill ()
5920 "Unconditionally turn off Auto Fill mode."
5921 (auto-fill-mode -
1))
5923 (custom-add-option 'text-mode-hook
'turn-on-auto-fill
)
5925 (defun set-fill-column (arg)
5926 "Set `fill-column' to specified argument.
5927 Use \\[universal-argument] followed by a number to specify a column.
5928 Just \\[universal-argument] as argument means to use the current column."
5930 (list (or current-prefix-arg
5931 ;; We used to use current-column silently, but C-x f is too easily
5932 ;; typed as a typo for C-x C-f, so we turned it into an error and
5933 ;; now an interactive prompt.
5934 (read-number "Set fill-column to: " (current-column)))))
5936 (setq arg
(current-column)))
5937 (if (not (integerp arg
))
5938 ;; Disallow missing argument; it's probably a typo for C-x C-f.
5939 (error "set-fill-column requires an explicit argument")
5940 (message "Fill column set to %d (was %d)" arg fill-column
)
5941 (setq fill-column arg
)))
5943 (defun set-selective-display (arg)
5944 "Set `selective-display' to ARG; clear it if no arg.
5945 When the value of `selective-display' is a number > 0,
5946 lines whose indentation is >= that value are not displayed.
5947 The variable `selective-display' has a separate value for each buffer."
5949 (if (eq selective-display t
)
5950 (error "selective-display already in use for marked lines"))
5953 (narrow-to-region (point-min) (point))
5954 (goto-char (window-start))
5955 (vertical-motion (window-height)))))
5956 (setq selective-display
5957 (and arg
(prefix-numeric-value arg
)))
5958 (recenter current-vpos
))
5959 (set-window-start (selected-window) (window-start))
5960 (princ "selective-display set to " t
)
5961 (prin1 selective-display t
)
5964 (defvaralias 'indicate-unused-lines
'indicate-empty-lines
)
5966 (defun toggle-truncate-lines (&optional arg
)
5967 "Toggle truncating of long lines for the current buffer.
5968 When truncating is off, long lines are folded.
5969 With prefix argument ARG, truncate long lines if ARG is positive,
5970 otherwise fold them. Note that in side-by-side windows, this
5971 command has no effect if `truncate-partial-width-windows' is
5974 (setq truncate-lines
5976 (not truncate-lines
)
5977 (> (prefix-numeric-value arg
) 0)))
5978 (force-mode-line-update)
5979 (unless truncate-lines
5980 (let ((buffer (current-buffer)))
5981 (walk-windows (lambda (window)
5982 (if (eq buffer
(window-buffer window
))
5983 (set-window-hscroll window
0)))
5985 (message "Truncate long lines %s"
5986 (if truncate-lines
"enabled" "disabled")))
5988 (defun toggle-word-wrap (&optional arg
)
5989 "Toggle whether to use word-wrapping for continuation lines.
5990 With prefix argument ARG, wrap continuation lines at word boundaries
5991 if ARG is positive, otherwise wrap them at the right screen edge.
5992 This command toggles the value of `word-wrap'. It has no effect
5993 if long lines are truncated."
5998 (> (prefix-numeric-value arg
) 0)))
5999 (force-mode-line-update)
6000 (message "Word wrapping %s"
6001 (if word-wrap
"enabled" "disabled")))
6003 (defvar overwrite-mode-textual
(purecopy " Ovwrt")
6004 "The string displayed in the mode line when in overwrite mode.")
6005 (defvar overwrite-mode-binary
(purecopy " Bin Ovwrt")
6006 "The string displayed in the mode line when in binary overwrite mode.")
6008 (define-minor-mode overwrite-mode
6009 "Toggle Overwrite mode.
6010 With a prefix argument ARG, enable Overwrite mode if ARG is
6011 positive, and disable it otherwise. If called from Lisp, enable
6012 the mode if ARG is omitted or nil.
6014 When Overwrite mode is enabled, printing characters typed in
6015 replace existing text on a one-for-one basis, rather than pushing
6016 it to the right. At the end of a line, such characters extend
6017 the line. Before a tab, such characters insert until the tab is
6018 filled in. \\[quoted-insert] still inserts characters in
6019 overwrite mode; this is supposed to make it easier to insert
6020 characters when necessary."
6021 :variable
(overwrite-mode
6022 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-textual
)))))
6024 (define-minor-mode binary-overwrite-mode
6025 "Toggle Binary Overwrite mode.
6026 With a prefix argument ARG, enable Binary Overwrite mode if ARG
6027 is positive, and disable it otherwise. If called from Lisp,
6028 enable the mode if ARG is omitted or nil.
6030 When Binary Overwrite mode is enabled, printing characters typed
6031 in replace existing text. Newlines are not treated specially, so
6032 typing at the end of a line joins the line to the next, with the
6033 typed character between them. Typing before a tab character
6034 simply replaces the tab with the character typed.
6035 \\[quoted-insert] replaces the text at the cursor, just as
6036 ordinary typing characters do.
6038 Note that Binary Overwrite mode is not its own minor mode; it is
6039 a specialization of overwrite mode, entered by setting the
6040 `overwrite-mode' variable to `overwrite-mode-binary'."
6041 :variable
(overwrite-mode
6042 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-binary
)))))
6044 (define-minor-mode line-number-mode
6045 "Toggle line number display in the mode line (Line Number mode).
6046 With a prefix argument ARG, enable Line Number mode if ARG is
6047 positive, and disable it otherwise. If called from Lisp, enable
6048 the mode if ARG is omitted or nil.
6050 Line numbers do not appear for very large buffers and buffers
6051 with very long lines; see variables `line-number-display-limit'
6052 and `line-number-display-limit-width'."
6053 :init-value t
:global t
:group
'mode-line
)
6055 (define-minor-mode column-number-mode
6056 "Toggle column number display in the mode line (Column Number mode).
6057 With a prefix argument ARG, enable Column Number mode if ARG is
6058 positive, and disable it otherwise.
6060 If called from Lisp, enable the mode if ARG is omitted or nil."
6061 :global t
:group
'mode-line
)
6063 (define-minor-mode size-indication-mode
6064 "Toggle buffer size display in the mode line (Size Indication mode).
6065 With a prefix argument ARG, enable Size Indication mode if ARG is
6066 positive, and disable it otherwise.
6068 If called from Lisp, enable the mode if ARG is omitted or nil."
6069 :global t
:group
'mode-line
)
6071 (define-minor-mode auto-save-mode
6072 "Toggle auto-saving in the current buffer (Auto Save mode).
6073 With a prefix argument ARG, enable Auto Save mode if ARG is
6074 positive, and disable it otherwise.
6076 If called from Lisp, enable the mode if ARG is omitted or nil."
6077 :variable
((and buffer-auto-save-file-name
6078 ;; If auto-save is off because buffer has shrunk,
6079 ;; then toggling should turn it on.
6080 (>= buffer-saved-size
0))
6082 (setq buffer-auto-save-file-name
6085 ((and buffer-file-name auto-save-visited-file-name
6086 (not buffer-read-only
))
6088 (t (make-auto-save-file-name))))))
6089 ;; If -1 was stored here, to temporarily turn off saving,
6091 (and (< buffer-saved-size
0)
6092 (setq buffer-saved-size
0)))
6094 (defgroup paren-blinking nil
6095 "Blinking matching of parens and expressions."
6096 :prefix
"blink-matching-"
6097 :group
'paren-matching
)
6099 (defcustom blink-matching-paren t
6100 "Non-nil means show matching open-paren when close-paren is inserted."
6102 :group
'paren-blinking
)
6104 (defcustom blink-matching-paren-on-screen t
6105 "Non-nil means show matching open-paren when it is on screen.
6106 If nil, don't show it (but the open-paren can still be shown
6107 when it is off screen).
6109 This variable has no effect if `blink-matching-paren' is nil.
6110 \(In that case, the open-paren is never shown.)
6111 It is also ignored if `show-paren-mode' is enabled."
6113 :group
'paren-blinking
)
6115 (defcustom blink-matching-paren-distance
(* 100 1024)
6116 "If non-nil, maximum distance to search backwards for matching open-paren.
6117 If nil, search stops at the beginning of the accessible portion of the buffer."
6118 :version
"23.2" ; 25->100k
6119 :type
'(choice (const nil
) integer
)
6120 :group
'paren-blinking
)
6122 (defcustom blink-matching-delay
1
6123 "Time in seconds to delay after showing a matching paren."
6125 :group
'paren-blinking
)
6127 (defcustom blink-matching-paren-dont-ignore-comments nil
6128 "If nil, `blink-matching-paren' ignores comments.
6129 More precisely, when looking for the matching parenthesis,
6130 it skips the contents of comments that end before point."
6132 :group
'paren-blinking
)
6134 (defun blink-matching-check-mismatch (start end
)
6135 "Return whether or not START...END are matching parens.
6136 END is the current point and START is the blink position.
6137 START might be nil if no matching starter was found.
6138 Returns non-nil if we find there is a mismatch."
6139 (let* ((end-syntax (syntax-after (1- end
)))
6140 (matching-paren (and (consp end-syntax
)
6141 (eq (syntax-class end-syntax
) 5)
6143 ;; For self-matched chars like " and $, we can't know when they're
6144 ;; mismatched or unmatched, so we can only do it for parens.
6145 (when matching-paren
6148 (eq (char-after start
) matching-paren
)
6149 ;; The cdr might hold a new paren-class info rather than
6150 ;; a matching-char info, in which case the two CDRs
6152 (eq matching-paren
(cdr-safe (syntax-after start
)))))))))
6154 (defvar blink-matching-check-function
#'blink-matching-check-mismatch
6155 "Function to check parentheses mismatches.
6156 The function takes two arguments (START and END) where START is the
6157 position just before the opening token and END is the position right after.
6158 START can be nil, if it was not found.
6159 The function should return non-nil if the two tokens do not match.")
6161 (defun blink-matching-open ()
6162 "Move cursor momentarily to the beginning of the sexp before point."
6164 (when (and (not (bobp))
6165 blink-matching-paren
)
6166 (let* ((oldpos (point))
6167 (message-log-max nil
) ; Don't log messages about paren matching.
6171 (if blink-matching-paren-distance
6173 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
6174 (- (point) blink-matching-paren-distance
))
6176 (let ((parse-sexp-ignore-comments
6177 (and parse-sexp-ignore-comments
6178 (not blink-matching-paren-dont-ignore-comments
))))
6182 ;; backward-sexp skips backward over prefix chars,
6183 ;; so move back to the matching paren.
6184 (while (and (< (point) (1- oldpos
))
6185 (let ((code (syntax-after (point))))
6186 (or (eq (syntax-class code
) 6)
6187 (eq (logand 1048576 (car code
))
6192 (mismatch (funcall blink-matching-check-function blinkpos oldpos
)))
6197 (minibuffer-message "Mismatched parentheses")
6198 (message "Mismatched parentheses"))
6200 (minibuffer-message "No matching parenthesis found")
6201 (message "No matching parenthesis found"))))
6202 ((not blinkpos
) nil
)
6203 ((pos-visible-in-window-p blinkpos
)
6204 ;; Matching open within window, temporarily move to blinkpos but only
6205 ;; if `blink-matching-paren-on-screen' is non-nil.
6206 (and blink-matching-paren-on-screen
6207 (not show-paren-mode
)
6209 (goto-char blinkpos
)
6210 (sit-for blink-matching-delay
))))
6213 (goto-char blinkpos
)
6214 (let ((open-paren-line-string
6215 ;; Show what precedes the open in its line, if anything.
6217 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
6218 (buffer-substring (line-beginning-position)
6220 ;; Show what follows the open in its line, if anything.
6223 (skip-chars-forward " \t")
6225 (buffer-substring blinkpos
6226 (line-end-position)))
6227 ;; Otherwise show the previous nonblank line,
6229 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
6231 (buffer-substring (progn
6232 (skip-chars-backward "\n \t")
6233 (line-beginning-position))
6234 (progn (end-of-line)
6235 (skip-chars-backward " \t")
6237 ;; Replace the newline and other whitespace with `...'.
6239 (buffer-substring blinkpos
(1+ blinkpos
))))
6240 ;; There is nothing to show except the char itself.
6241 (t (buffer-substring blinkpos
(1+ blinkpos
))))))
6242 (message "Matches %s"
6243 (substring-no-properties open-paren-line-string
)))))))))
6245 (defvar blink-paren-function
'blink-matching-open
6246 "Function called, if non-nil, whenever a close parenthesis is inserted.
6247 More precisely, a char with closeparen syntax is self-inserted.")
6249 (defun blink-paren-post-self-insert-function ()
6250 (when (and (eq (char-before) last-command-event
) ; Sanity check.
6251 (memq (char-syntax last-command-event
) '(?\
) ?\$
))
6252 blink-paren-function
6253 (not executing-kbd-macro
)
6254 (not noninteractive
)
6255 ;; Verify an even number of quoting characters precede the close.
6256 (= 1 (logand 1 (- (point)
6259 (skip-syntax-backward "/\\")
6261 (funcall blink-paren-function
)))
6263 (add-hook 'post-self-insert-hook
#'blink-paren-post-self-insert-function
6264 ;; Most likely, this hook is nil, so this arg doesn't matter,
6265 ;; but I use it as a reminder that this function usually
6266 ;; likes to be run after others since it does `sit-for'.
6269 ;; This executes C-g typed while Emacs is waiting for a command.
6270 ;; Quitting out of a program does not go through here;
6271 ;; that happens in the QUIT macro at the C code level.
6272 (defun keyboard-quit ()
6273 "Signal a `quit' condition.
6274 During execution of Lisp code, this character causes a quit directly.
6275 At top-level, as an editor command, this simply beeps."
6277 ;; Avoid adding the region to the window selection.
6278 (setq saved-region-selection nil
)
6279 (let (select-active-regions)
6281 (if (fboundp 'kmacro-keyboard-quit
)
6282 (kmacro-keyboard-quit))
6283 (setq defining-kbd-macro nil
)
6284 (let ((debug-on-quit nil
))
6285 (signal 'quit nil
)))
6287 (defvar buffer-quit-function nil
6288 "Function to call to \"quit\" the current buffer, or nil if none.
6289 \\[keyboard-escape-quit] calls this function when its more local actions
6290 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
6292 (defun keyboard-escape-quit ()
6293 "Exit the current \"mode\" (in a generalized sense of the word).
6294 This command can exit an interactive command such as `query-replace',
6295 can clear out a prefix argument or a region,
6296 can get out of the minibuffer or other recursive edit,
6297 cancel the use of the current buffer (for special-purpose buffers),
6298 or go back to just one window (by deleting all but the selected window)."
6300 (cond ((eq last-command
'mode-exited
) nil
)
6303 ((> (minibuffer-depth) 0)
6304 (abort-recursive-edit))
6307 ((> (recursion-depth) 0)
6308 (exit-recursive-edit))
6309 (buffer-quit-function
6310 (funcall buffer-quit-function
))
6311 ((not (one-window-p t
))
6312 (delete-other-windows))
6313 ((string-match "^ \\*" (buffer-name (current-buffer)))
6316 (defun play-sound-file (file &optional volume device
)
6317 "Play sound stored in FILE.
6318 VOLUME and DEVICE correspond to the keywords of the sound
6319 specification for `play-sound'."
6320 (interactive "fPlay sound file: ")
6321 (let ((sound (list :file file
)))
6323 (plist-put sound
:volume volume
))
6325 (plist-put sound
:device device
))
6327 (play-sound sound
)))
6330 (defcustom read-mail-command
'rmail
6331 "Your preference for a mail reading package.
6332 This is used by some keybindings which support reading mail.
6333 See also `mail-user-agent' concerning sending mail."
6334 :type
'(radio (function-item :tag
"Rmail" :format
"%t\n" rmail
)
6335 (function-item :tag
"Gnus" :format
"%t\n" gnus
)
6336 (function-item :tag
"Emacs interface to MH"
6337 :format
"%t\n" mh-rmail
)
6338 (function :tag
"Other"))
6342 (defcustom mail-user-agent
'message-user-agent
6343 "Your preference for a mail composition package.
6344 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
6345 outgoing email message. This variable lets you specify which
6346 mail-sending package you prefer.
6348 Valid values include:
6350 `message-user-agent' -- use the Message package.
6351 See Info node `(message)'.
6352 `sendmail-user-agent' -- use the Mail package.
6353 See Info node `(emacs)Sending Mail'.
6354 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
6355 See Info node `(mh-e)'.
6356 `gnus-user-agent' -- like `message-user-agent', but with Gnus
6357 paraphernalia if Gnus is running, particularly
6358 the Gcc: header for archiving.
6360 Additional valid symbols may be available; check with the author of
6361 your package for details. The function should return non-nil if it
6364 See also `read-mail-command' concerning reading mail."
6365 :type
'(radio (function-item :tag
"Message package"
6368 (function-item :tag
"Mail package"
6370 sendmail-user-agent
)
6371 (function-item :tag
"Emacs interface to MH"
6374 (function-item :tag
"Message with full Gnus features"
6377 (function :tag
"Other"))
6378 :version
"23.2" ; sendmail->message
6381 (defcustom compose-mail-user-agent-warnings t
6382 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
6383 If the value of `mail-user-agent' is the default, and the user
6384 appears to have customizations applying to the old default,
6385 `compose-mail' issues a warning."
6390 (defun rfc822-goto-eoh ()
6391 "If the buffer starts with a mail header, move point to the header's end.
6392 Otherwise, moves to `point-min'.
6393 The end of the header is the start of the next line, if there is one,
6394 else the end of the last line. This function obeys RFC822."
6395 (goto-char (point-min))
6396 (when (re-search-forward
6397 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil
'move
)
6398 (goto-char (match-beginning 0))))
6400 ;; Used by Rmail (e.g., rmail-forward).
6401 (defvar mail-encode-mml nil
6402 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
6403 the outgoing message before sending it.")
6405 (defun compose-mail (&optional to subject other-headers continue
6406 switch-function yank-action send-actions
6408 "Start composing a mail message to send.
6409 This uses the user's chosen mail composition package
6410 as selected with the variable `mail-user-agent'.
6411 The optional arguments TO and SUBJECT specify recipients
6412 and the initial Subject field, respectively.
6414 OTHER-HEADERS is an alist specifying additional
6415 header fields. Elements look like (HEADER . VALUE) where both
6416 HEADER and VALUE are strings.
6418 CONTINUE, if non-nil, says to continue editing a message already
6419 being composed. Interactively, CONTINUE is the prefix argument.
6421 SWITCH-FUNCTION, if non-nil, is a function to use to
6422 switch to and display the buffer used for mail composition.
6424 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
6425 to insert the raw text of the message being replied to.
6426 It has the form (FUNCTION . ARGS). The user agent will apply
6427 FUNCTION to ARGS, to insert the raw text of the original message.
6428 \(The user agent will also run `mail-citation-hook', *after* the
6429 original text has been inserted in this way.)
6431 SEND-ACTIONS is a list of actions to call when the message is sent.
6432 Each action has the form (FUNCTION . ARGS).
6434 RETURN-ACTION, if non-nil, is an action for returning to the
6435 caller. It has the form (FUNCTION . ARGS). The function is
6436 called after the mail has been sent or put aside, and the mail
6439 (list nil nil nil current-prefix-arg
))
6441 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
6442 ;; from sendmail-user-agent to message-user-agent. Some users may
6443 ;; encounter incompatibilities. This hack tries to detect problems
6444 ;; and warn about them.
6445 (and compose-mail-user-agent-warnings
6446 (eq mail-user-agent
'message-user-agent
)
6448 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
6449 mail-yank-hooks mail-archive-file-name
6450 mail-default-reply-to mail-mailing-lists
6454 (push var warn-vars
)))
6456 (display-warning 'mail
6458 The default mail mode is now Message mode.
6459 You have the following Mail mode variable%s customized:
6460 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
6461 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
6462 (if (> (length warn-vars
) 1) "s" "")
6463 (mapconcat 'symbol-name
6466 (let ((function (get mail-user-agent
'composefunc
)))
6467 (funcall function to subject other-headers continue switch-function
6468 yank-action send-actions return-action
)))
6470 (defun compose-mail-other-window (&optional to subject other-headers continue
6471 yank-action send-actions
6473 "Like \\[compose-mail], but edit the outgoing message in another window."
6474 (interactive (list nil nil nil current-prefix-arg
))
6475 (compose-mail to subject other-headers continue
6476 'switch-to-buffer-other-window yank-action send-actions
6479 (defun compose-mail-other-frame (&optional to subject other-headers continue
6480 yank-action send-actions
6482 "Like \\[compose-mail], but edit the outgoing message in another frame."
6483 (interactive (list nil nil nil current-prefix-arg
))
6484 (compose-mail to subject other-headers continue
6485 'switch-to-buffer-other-frame yank-action send-actions
6489 (defvar set-variable-value-history nil
6490 "History of values entered with `set-variable'.
6492 Maximum length of the history list is determined by the value
6493 of `history-length', which see.")
6495 (defun set-variable (variable value
&optional make-local
)
6496 "Set VARIABLE to VALUE. VALUE is a Lisp object.
6497 VARIABLE should be a user option variable name, a Lisp variable
6498 meant to be customized by users. You should enter VALUE in Lisp syntax,
6499 so if you want VALUE to be a string, you must surround it with doublequotes.
6500 VALUE is used literally, not evaluated.
6502 If VARIABLE has a `variable-interactive' property, that is used as if
6503 it were the arg to `interactive' (which see) to interactively read VALUE.
6505 If VARIABLE has been defined with `defcustom', then the type information
6506 in the definition is used to check that VALUE is valid.
6508 With a prefix argument, set VARIABLE to VALUE buffer-locally."
6510 (let* ((default-var (variable-at-point))
6511 (var (if (custom-variable-p default-var
)
6512 (read-variable (format "Set variable (default %s): " default-var
)
6514 (read-variable "Set variable: ")))
6515 (minibuffer-help-form '(describe-variable var
))
6516 (prop (get var
'variable-interactive
))
6517 (obsolete (car (get var
'byte-obsolete-variable
)))
6518 (prompt (format "Set %s %s to value: " var
6519 (cond ((local-variable-p var
)
6521 ((or current-prefix-arg
6522 (local-variable-if-set-p var
))
6527 (message (concat "`%S' is obsolete; "
6528 (if (symbolp obsolete
) "use `%S' instead" "%s"))
6532 ;; Use VAR's `variable-interactive' property
6533 ;; as an interactive spec for prompting.
6534 (call-interactively `(lambda (arg)
6537 (read-from-minibuffer prompt nil
6538 read-expression-map t
6539 'set-variable-value-history
6540 (format "%S" (symbol-value var
)))))))
6541 (list var val current-prefix-arg
)))
6543 (and (custom-variable-p variable
)
6544 (not (get variable
'custom-type
))
6545 (custom-load-symbol variable
))
6546 (let ((type (get variable
'custom-type
)))
6548 ;; Match with custom type.
6550 (setq type
(widget-convert type
))
6551 (unless (widget-apply type
:match value
)
6552 (error "Value `%S' does not match type %S of %S"
6553 value
(car type
) variable
))))
6556 (make-local-variable variable
))
6558 (set variable value
)
6560 ;; Force a thorough redisplay for the case that the variable
6561 ;; has an effect on the display, like `tab-width' has.
6562 (force-mode-line-update))
6564 ;; Define the major mode for lists of completions.
6566 (defvar completion-list-mode-map
6567 (let ((map (make-sparse-keymap)))
6568 (define-key map
[mouse-2
] 'mouse-choose-completion
)
6569 (define-key map
[follow-link
] 'mouse-face
)
6570 (define-key map
[down-mouse-2
] nil
)
6571 (define-key map
"\C-m" 'choose-completion
)
6572 (define-key map
"\e\e\e" 'delete-completion-window
)
6573 (define-key map
[left] 'previous-completion)
6574 (define-key map [right] 'next-completion)
6575 (define-key map "q" 'quit-window)
6576 (define-key map "z" 'kill-this-buffer)
6578 "Local map for completion list buffers.")
6580 ;; Completion mode is suitable only for specially formatted data.
6581 (put 'completion-list-mode 'mode-class 'special)
6583 (defvar completion-reference-buffer nil
6584 "Record the buffer that was current when the completion list was requested.
6585 This is a local variable in the completion list buffer.
6586 Initial value is nil to avoid some compiler warnings.")
6588 (defvar completion-no-auto-exit nil
6589 "Non-nil means `choose-completion-string' should never exit the minibuffer.
6590 This also applies to other functions such as `choose-completion'.")
6592 (defvar completion-base-position nil
6593 "Position of the base of the text corresponding to the shown completions.
6594 This variable is used in the *Completions* buffers.
6595 Its value is a list of the form (START END) where START is the place
6596 where the completion should be inserted and END (if non-nil) is the end
6597 of the text to replace. If END is nil, point is used instead.")
6599 (defvar completion-list-insert-choice-function #'completion--replace
6600 "Function to use to insert the text chosen in *Completions*.
6601 Called with three arguments (BEG END TEXT), it should replace the text
6602 between BEG and END with TEXT. Expected to be set buffer-locally
6603 in the *Completions* buffer.")
6605 (defvar completion-base-size nil
6606 "Number of chars before point not involved in completion.
6607 This is a local variable in the completion list buffer.
6608 It refers to the chars in the minibuffer if completing in the
6609 minibuffer, or in `completion-reference-buffer' otherwise.
6610 Only characters in the field at point are included.
6612 If nil, Emacs determines which part of the tail end of the
6613 buffer's text is involved in completion by comparing the text
6615 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
6617 (defun delete-completion-window ()
6618 "Delete the completion list window.
6619 Go to the window from which completion was requested."
6621 (let ((buf completion-reference-buffer))
6622 (if (one-window-p t)
6623 (if (window-dedicated-p) (delete-frame))
6624 (delete-window (selected-window))
6625 (if (get-buffer-window buf)
6626 (select-window (get-buffer-window buf))))))
6628 (defun previous-completion (n)
6629 "Move to the previous item in the completion list."
6631 (next-completion (- n)))
6633 (defun next-completion (n)
6634 "Move to the next item in the completion list.
6635 With prefix argument N, move N items (negative N means move backward)."
6637 (let ((beg (point-min)) (end (point-max)))
6638 (while (and (> n 0) (not (eobp)))
6639 ;; If in a completion, move to the end of it.
6640 (when (get-text-property (point) 'mouse-face)
6641 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6642 ;; Move to start of next one.
6643 (unless (get-text-property (point) 'mouse-face)
6644 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6646 (while (and (< n 0) (not (bobp)))
6647 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
6648 ;; If in a completion, move to the start of it.
6649 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
6650 (goto-char (previous-single-property-change
6651 (point) 'mouse-face nil beg)))
6652 ;; Move to end of the previous completion.
6653 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
6654 (goto-char (previous-single-property-change
6655 (point) 'mouse-face nil beg)))
6656 ;; Move to the start of that one.
6657 (goto-char (previous-single-property-change
6658 (point) 'mouse-face nil beg))
6661 (defun choose-completion (&optional event)
6662 "Choose the completion at point."
6663 (interactive (list last-nonmenu-event))
6664 ;; In case this is run via the mouse, give temporary modes such as
6665 ;; isearch a chance to turn off.
6666 (run-hooks 'mouse-leave-buffer-hook)
6667 (with-current-buffer (window-buffer (posn-window (event-start event)))
6668 (let ((buffer completion-reference-buffer)
6669 (base-size completion-base-size)
6670 (base-position completion-base-position)
6671 (insert-function completion-list-insert-choice-function)
6674 (goto-char (posn-point (event-start event)))
6677 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
6678 (setq end (point) beg (1+ (point))))
6680 (get-text-property (1- (point)) 'mouse-face))
6681 (setq end (1- (point)) beg (point)))
6682 (t (error "No completion here")))
6683 (setq beg (previous-single-property-change beg 'mouse-face))
6684 (setq end (or (next-single-property-change end 'mouse-face)
6686 (buffer-substring-no-properties beg end)))))
6688 (unless (buffer-live-p buffer)
6689 (error "Destination buffer is dead"))
6690 (quit-window nil (posn-window (event-start event)))
6692 (with-current-buffer buffer
6693 (choose-completion-string
6697 ;; Someone's using old completion code that doesn't know
6698 ;; about base-position yet.
6699 (list (+ base-size (field-beginning))))
6700 ;; If all else fails, just guess.
6701 (list (choose-completion-guess-base-position choice)))
6702 insert-function)))))
6704 ;; Delete the longest partial match for STRING
6705 ;; that can be found before POINT.
6706 (defun choose-completion-guess-base-position (string)
6708 (let ((opoint (point))
6710 ;; Try moving back by the length of the string.
6711 (goto-char (max (- (point) (length string))
6712 (minibuffer-prompt-end)))
6713 ;; See how far back we were actually able to move. That is the
6714 ;; upper bound on how much we can match and delete.
6715 (setq len (- opoint (point)))
6716 (if completion-ignore-case
6717 (setq string (downcase string)))
6718 (while (and (> len 0)
6719 (let ((tail (buffer-substring (point) opoint)))
6720 (if completion-ignore-case
6721 (setq tail (downcase tail)))
6722 (not (string= tail (substring string 0 len)))))
6727 (defun choose-completion-delete-max-match (string)
6728 (declare (obsolete choose-completion-guess-base-position "23.2"))
6729 (delete-region (choose-completion-guess-base-position string) (point)))
6731 (defvar choose-completion-string-functions nil
6732 "Functions that may override the normal insertion of a completion choice.
6733 These functions are called in order with four arguments:
6734 CHOICE - the string to insert in the buffer,
6735 BUFFER - the buffer in which the choice should be inserted,
6736 MINI-P - non-nil if BUFFER is a minibuffer, and
6737 BASE-SIZE - the number of characters in BUFFER before
6738 the string being completed.
6740 If a function in the list returns non-nil, that function is supposed
6741 to have inserted the CHOICE in the BUFFER, and possibly exited
6742 the minibuffer; no further functions will be called.
6744 If all functions in the list return nil, that means to use
6745 the default method of inserting the completion in BUFFER.")
6747 (defun choose-completion-string (choice &optional
6748 buffer base-position insert-function)
6749 "Switch to BUFFER and insert the completion choice CHOICE.
6750 BASE-POSITION says where to insert the completion.
6751 INSERT-FUNCTION says how to insert the completion and falls
6752 back on `completion-list-insert-choice-function' when nil."
6754 ;; If BUFFER is the minibuffer, exit the minibuffer
6755 ;; unless it is reading a file name and CHOICE is a directory,
6756 ;; or completion-no-auto-exit is non-nil.
6758 ;; Some older code may call us passing `base-size' instead of
6759 ;; `base-position'. It's difficult to make any use of `base-size',
6760 ;; so we just ignore it.
6761 (unless (consp base-position)
6762 (message "Obsolete `base-size' passed to choose-completion-string")
6763 (setq base-position nil))
6765 (let* ((buffer (or buffer completion-reference-buffer))
6766 (mini-p (minibufferp buffer)))
6767 ;; If BUFFER is a minibuffer, barf unless it's the currently
6768 ;; active minibuffer.
6770 (not (and (active-minibuffer-window)
6772 (window-buffer (active-minibuffer-window))))))
6773 (error "Minibuffer is not active for completion")
6774 ;; Set buffer so buffer-local choose-completion-string-functions works.
6776 (unless (run-hook-with-args-until-success
6777 'choose-completion-string-functions
6778 ;; The fourth arg used to be `mini-p' but was useless
6779 ;; (since minibufferp can be used on the `buffer' arg)
6780 ;; and indeed unused. The last used to be `base-size', so we
6781 ;; keep it to try and avoid breaking old code.
6782 choice buffer base-position nil)
6783 ;; This remove-text-properties should be unnecessary since `choice'
6784 ;; comes from buffer-substring-no-properties.
6785 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
6786 ;; Insert the completion into the buffer where it was requested.
6787 (funcall (or insert-function completion-list-insert-choice-function)
6788 (or (car base-position) (point))
6789 (or (cadr base-position) (point))
6791 ;; Update point in the window that BUFFER is showing in.
6792 (let ((window (get-buffer-window buffer t)))
6793 (set-window-point window (point)))
6794 ;; If completing for the minibuffer, exit it with this choice.
6795 (and (not completion-no-auto-exit)
6796 (minibufferp buffer)
6797 minibuffer-completion-table
6798 ;; If this is reading a file name, and the file name chosen
6799 ;; is a directory, don't exit the minibuffer.
6800 (let* ((result (buffer-substring (field-beginning) (point)))
6802 (completion-boundaries result minibuffer-completion-table
6803 minibuffer-completion-predicate
6805 (if (eq (car bounds) (length result))
6806 ;; The completion chosen leads to a new set of completions
6807 ;; (e.g. it's a directory): don't exit the minibuffer yet.
6808 (let ((mini (active-minibuffer-window)))
6809 (select-window mini)
6810 (when minibuffer-auto-raise
6811 (raise-frame (window-frame mini))))
6812 (exit-minibuffer))))))))
6814 (define-derived-mode completion-list-mode nil "Completion List"
6815 "Major mode for buffers showing lists of possible completions.
6816 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
6817 to select the completion near point.
6818 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
6821 \\{completion-list-mode-map}"
6822 (set (make-local-variable 'completion-base-size) nil))
6824 (defun completion-list-mode-finish ()
6825 "Finish setup of the completions buffer.
6826 Called from `temp-buffer-show-hook'."
6827 (when (eq major-mode 'completion-list-mode)
6828 (setq buffer-read-only t)))
6830 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
6833 ;; Variables and faces used in `completion-setup-function'.
6835 (defcustom completion-show-help t
6836 "Non-nil means show help message in *Completions* buffer."
6841 ;; This function goes in completion-setup-hook, so that it is called
6842 ;; after the text of the completion list buffer is written.
6843 (defun completion-setup-function ()
6844 (let* ((mainbuf (current-buffer))
6846 ;; FIXME: This is a bad hack. We try to set the default-directory
6847 ;; in the *Completions* buffer so that the relative file names
6848 ;; displayed there can be treated as valid file names, independently
6849 ;; from the completion context. But this suffers from many problems:
6850 ;; - It's not clear when the completions are file names. With some
6851 ;; completion tables (e.g. bzr revision specs), the listed
6852 ;; completions can mix file names and other things.
6853 ;; - It doesn't pay attention to possible quoting.
6854 ;; - With fancy completion styles, the code below will not always
6855 ;; find the right base directory.
6856 (if minibuffer-completing-file-name
6857 (file-name-as-directory
6859 (buffer-substring (minibuffer-prompt-end)
6860 (- (point) (or completion-base-size 0))))))))
6861 (with-current-buffer standard-output
6862 (let ((base-size completion-base-size) ;Read before killing localvars.
6863 (base-position completion-base-position)
6864 (insert-fun completion-list-insert-choice-function))
6865 (completion-list-mode)
6866 (set (make-local-variable 'completion-base-size) base-size)
6867 (set (make-local-variable 'completion-base-position) base-position)
6868 (set (make-local-variable 'completion-list-insert-choice-function)
6870 (set (make-local-variable 'completion-reference-buffer) mainbuf)
6871 (if base-dir (setq default-directory base-dir))
6872 ;; Maybe insert help string.
6873 (when completion-show-help
6874 (goto-char (point-min))
6875 (if (display-mouse-p)
6876 (insert (substitute-command-keys
6877 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
6878 (insert (substitute-command-keys
6879 "In this buffer, type \\[choose-completion] to \
6880 select the completion near point.\n\n"))))))
6882 (add-hook 'completion-setup-hook 'completion-setup-function)
6884 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
6885 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
6887 (defun switch-to-completions ()
6888 "Select the completion list window."
6890 (let ((window (or (get-buffer-window "*Completions*" 0)
6891 ;; Make sure we have a completions window.
6892 (progn (minibuffer-completion-help)
6893 (get-buffer-window "*Completions*" 0)))))
6895 (select-window window)
6896 ;; In the new buffer, go to the first completion.
6897 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
6899 (next-completion 1)))))
6901 ;;; Support keyboard commands to turn on various modifiers.
6903 ;; These functions -- which are not commands -- each add one modifier
6904 ;; to the following event.
6906 (defun event-apply-alt-modifier (_ignore-prompt)
6907 "\\<function-key-map>Add the Alt modifier to the following event.
6908 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
6909 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
6910 (defun event-apply-super-modifier (_ignore-prompt)
6911 "\\<function-key-map>Add the Super modifier to the following event.
6912 For example, type \\[event-apply-super-modifier] & to enter Super-&."
6913 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
6914 (defun event-apply-hyper-modifier (_ignore-prompt)
6915 "\\<function-key-map>Add the Hyper modifier to the following event.
6916 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
6917 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
6918 (defun event-apply-shift-modifier (_ignore-prompt)
6919 "\\<function-key-map>Add the Shift modifier to the following event.
6920 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
6921 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
6922 (defun event-apply-control-modifier (_ignore-prompt)
6923 "\\<function-key-map>Add the Ctrl modifier to the following event.
6924 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
6925 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
6926 (defun event-apply-meta-modifier (_ignore-prompt)
6927 "\\<function-key-map>Add the Meta modifier to the following event.
6928 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
6929 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
6931 (defun event-apply-modifier (event symbol lshiftby prefix)
6932 "Apply a modifier flag to event EVENT.
6933 SYMBOL is the name of this modifier, as a symbol.
6934 LSHIFTBY is the numeric value of this modifier, in keyboard events.
6935 PREFIX is the string that represents this modifier in an event type symbol."
6937 (cond ((eq symbol 'control)
6938 (if (and (<= (downcase event) ?z)
6939 (>= (downcase event) ?a))
6940 (- (downcase event) ?a -1)
6941 (if (and (<= (downcase event) ?Z)
6942 (>= (downcase event) ?A))
6943 (- (downcase event) ?A -1)
6944 (logior (lsh 1 lshiftby) event))))
6946 (if (and (<= (downcase event) ?z)
6947 (>= (downcase event) ?a))
6949 (logior (lsh 1 lshiftby) event)))
6951 (logior (lsh 1 lshiftby) event)))
6952 (if (memq symbol (event-modifiers event))
6954 (let ((event-type (if (symbolp event) event (car event))))
6955 (setq event-type (intern (concat prefix (symbol-name event-type))))
6958 (cons event-type (cdr event)))))))
6960 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
6961 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
6962 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
6963 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
6964 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
6965 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
6967 ;;;; Keypad support.
6969 ;; Make the keypad keys act like ordinary typing keys. If people add
6970 ;; bindings for the function key symbols, then those bindings will
6971 ;; override these, so this shouldn't interfere with any existing
6974 ;; Also tell read-char how to handle these keys.
6976 (lambda (keypad-normal)
6977 (let ((keypad (nth 0 keypad-normal))
6978 (normal (nth 1 keypad-normal)))
6979 (put keypad 'ascii-character normal)
6980 (define-key function-key-map (vector keypad) (vector normal))))
6981 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
6982 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
6993 ;; Do the same for various keys that are represented as symbols under
6994 ;; GUIs but naturally correspond to characters.
7005 ;;;; forking a twin copy of a buffer.
7008 (defvar clone-buffer-hook nil
7009 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
7011 (defvar clone-indirect-buffer-hook nil
7012 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
7014 (defun clone-process (process &optional newname)
7015 "Create a twin copy of PROCESS.
7016 If NEWNAME is nil, it defaults to PROCESS' name;
7017 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
7018 If PROCESS is associated with a buffer, the new process will be associated
7019 with the current buffer instead.
7020 Returns nil if PROCESS has already terminated."
7021 (setq newname (or newname (process-name process)))
7022 (if (string-match "<[0-9]+>\\'" newname)
7023 (setq newname (substring newname 0 (match-beginning 0))))
7024 (when (memq (process-status process) '(run stop open))
7025 (let* ((process-connection-type (process-tty-name process))
7027 (if (memq (process-status process) '(open))
7028 (let ((args (process-contact process t)))
7029 (setq args (plist-put args :name newname))
7030 (setq args (plist-put args :buffer
7031 (if (process-buffer process)
7033 (apply 'make-network-process args))
7034 (apply 'start-process newname
7035 (if (process-buffer process) (current-buffer))
7036 (process-command process)))))
7037 (set-process-query-on-exit-flag
7038 new-process (process-query-on-exit-flag process))
7039 (set-process-inherit-coding-system-flag
7040 new-process (process-inherit-coding-system-flag process))
7041 (set-process-filter new-process (process-filter process))
7042 (set-process-sentinel new-process (process-sentinel process))
7043 (set-process-plist new-process (copy-sequence (process-plist process)))
7046 ;; things to maybe add (currently partly covered by `funcall mode'):
7049 (defun clone-buffer (&optional newname display-flag)
7050 "Create and return a twin copy of the current buffer.
7051 Unlike an indirect buffer, the new buffer can be edited
7052 independently of the old one (if it is not read-only).
7053 NEWNAME is the name of the new buffer. It may be modified by
7054 adding or incrementing <N> at the end as necessary to create a
7055 unique buffer name. If nil, it defaults to the name of the
7056 current buffer, with the proper suffix. If DISPLAY-FLAG is
7057 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
7058 clone a file-visiting buffer, or a buffer whose major mode symbol
7059 has a non-nil `no-clone' property, results in an error.
7061 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
7062 current buffer with appropriate suffix. However, if a prefix
7063 argument is given, then the command prompts for NEWNAME in the
7066 This runs the normal hook `clone-buffer-hook' in the new buffer
7067 after it has been set up properly in other respects."
7070 (if buffer-file-name
7071 (error "Cannot clone a file-visiting buffer"))
7072 (if (get major-mode 'no-clone)
7073 (error "Cannot clone a buffer in %s mode" mode-name))
7074 (list (if current-prefix-arg
7075 (read-buffer "Name of new cloned buffer: " (current-buffer)))
7077 (if buffer-file-name
7078 (error "Cannot clone a file-visiting buffer"))
7079 (if (get major-mode 'no-clone)
7080 (error "Cannot clone a buffer in %s mode" mode-name))
7081 (setq newname (or newname (buffer-name)))
7082 (if (string-match "<[0-9]+>\\'" newname)
7083 (setq newname (substring newname 0 (match-beginning 0))))
7084 (let ((buf (current-buffer))
7088 (mk (if mark-active (mark t)))
7089 (modified (buffer-modified-p))
7091 (lvars (buffer-local-variables))
7092 (process (get-buffer-process (current-buffer)))
7093 (new (generate-new-buffer (or newname (buffer-name)))))
7096 (with-current-buffer new
7097 (insert-buffer-substring buf)))
7098 (with-current-buffer new
7099 (narrow-to-region ptmin ptmax)
7101 (if mk (set-mark mk))
7102 (set-buffer-modified-p modified)
7104 ;; Clone the old buffer's process, if any.
7105 (when process (clone-process process))
7107 ;; Now set up the major mode.
7110 ;; Set up other local variables.
7112 (condition-case () ;in case var is read-only
7115 (set (make-local-variable (car v)) (cdr v)))
7119 ;; Run any hooks (typically set up by the major mode
7120 ;; for cloning to work properly).
7121 (run-hooks 'clone-buffer-hook))
7123 ;; Presumably the current buffer is shown in the selected frame, so
7124 ;; we want to display the clone elsewhere.
7125 (let ((same-window-regexps nil)
7126 (same-window-buffer-names))
7127 (pop-to-buffer new)))
7131 (defun clone-indirect-buffer (newname display-flag &optional norecord)
7132 "Create an indirect buffer that is a twin copy of the current buffer.
7134 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
7135 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
7136 or if not called with a prefix arg, NEWNAME defaults to the current
7137 buffer's name. The name is modified by adding a `<N>' suffix to it
7138 or by incrementing the N in an existing suffix. Trying to clone a
7139 buffer whose major mode symbol has a non-nil `no-clone-indirect'
7140 property results in an error.
7142 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7143 This is always done when called interactively.
7145 Optional third arg NORECORD non-nil means do not put this buffer at the
7146 front of the list of recently selected ones."
7149 (if (get major-mode 'no-clone-indirect)
7150 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7151 (list (if current-prefix-arg
7152 (read-buffer "Name of indirect buffer: " (current-buffer)))
7154 (if (get major-mode 'no-clone-indirect)
7155 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7156 (setq newname (or newname (buffer-name)))
7157 (if (string-match "<[0-9]+>\\'" newname)
7158 (setq newname (substring newname 0 (match-beginning 0))))
7159 (let* ((name (generate-new-buffer-name newname))
7160 (buffer (make-indirect-buffer (current-buffer) name t)))
7161 (with-current-buffer buffer
7162 (run-hooks 'clone-indirect-buffer-hook))
7164 (pop-to-buffer buffer norecord))
7168 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
7169 "Like `clone-indirect-buffer' but display in another window."
7172 (if (get major-mode 'no-clone-indirect)
7173 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7174 (list (if current-prefix-arg
7175 (read-buffer "Name of indirect buffer: " (current-buffer)))
7177 (let ((pop-up-windows t))
7178 (clone-indirect-buffer newname display-flag norecord)))
7181 ;;; Handling of Backspace and Delete keys.
7183 (defcustom normal-erase-is-backspace 'maybe
7184 "Set the default behavior of the Delete and Backspace keys.
7186 If set to t, Delete key deletes forward and Backspace key deletes
7189 If set to nil, both Delete and Backspace keys delete backward.
7191 If set to 'maybe (which is the default), Emacs automatically
7192 selects a behavior. On window systems, the behavior depends on
7193 the keyboard used. If the keyboard has both a Backspace key and
7194 a Delete key, and both are mapped to their usual meanings, the
7195 option's default value is set to t, so that Backspace can be used
7196 to delete backward, and Delete can be used to delete forward.
7198 If not running under a window system, customizing this option
7199 accomplishes a similar effect by mapping C-h, which is usually
7200 generated by the Backspace key, to DEL, and by mapping DEL to C-d
7201 via `keyboard-translate'. The former functionality of C-h is
7202 available on the F1 key. You should probably not use this
7203 setting if you don't have both Backspace, Delete and F1 keys.
7205 Setting this variable with setq doesn't take effect. Programmatically,
7206 call `normal-erase-is-backspace-mode' (which see) instead."
7207 :type '(choice (const :tag "Off" nil)
7208 (const :tag "Maybe" maybe)
7209 (other :tag "On" t))
7210 :group 'editing-basics
7212 :set (lambda (symbol value)
7213 ;; The fboundp is because of a problem with :set when
7214 ;; dumping Emacs. It doesn't really matter.
7215 (if (fboundp 'normal-erase-is-backspace-mode)
7216 (normal-erase-is-backspace-mode (or value 0))
7217 (set-default symbol value))))
7219 (defun normal-erase-is-backspace-setup-frame (&optional frame)
7220 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
7221 (unless frame (setq frame (selected-frame)))
7222 (with-selected-frame frame
7223 (unless (terminal-parameter nil 'normal-erase-is-backspace)
7224 (normal-erase-is-backspace-mode
7225 (if (if (eq normal-erase-is-backspace 'maybe)
7226 (and (not noninteractive)
7227 (or (memq system-type '(ms-dos windows-nt))
7228 (memq window-system '(w32 ns))
7229 (and (memq window-system '(x))
7230 (fboundp 'x-backspace-delete-keys-p)
7231 (x-backspace-delete-keys-p))
7232 ;; If the terminal Emacs is running on has erase char
7233 ;; set to ^H, use the Backspace key for deleting
7234 ;; backward, and the Delete key for deleting forward.
7235 (and (null window-system)
7236 (eq tty-erase-char ?\^H))))
7237 normal-erase-is-backspace)
7240 (define-minor-mode normal-erase-is-backspace-mode
7241 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
7242 With a prefix argument ARG, enable this feature if ARG is
7243 positive, and disable it otherwise. If called from Lisp, enable
7244 the mode if ARG is omitted or nil.
7246 On window systems, when this mode is on, Delete is mapped to C-d
7247 and Backspace is mapped to DEL; when this mode is off, both
7248 Delete and Backspace are mapped to DEL. (The remapping goes via
7249 `local-function-key-map', so binding Delete or Backspace in the
7250 global or local keymap will override that.)
7252 In addition, on window systems, the bindings of C-Delete, M-Delete,
7253 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
7254 the global keymap in accordance with the functionality of Delete and
7255 Backspace. For example, if Delete is remapped to C-d, which deletes
7256 forward, C-Delete is bound to `kill-word', but if Delete is remapped
7257 to DEL, which deletes backward, C-Delete is bound to
7258 `backward-kill-word'.
7260 If not running on a window system, a similar effect is accomplished by
7261 remapping C-h (normally produced by the Backspace key) and DEL via
7262 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
7263 to C-d; if it's off, the keys are not remapped.
7265 When not running on a window system, and this mode is turned on, the
7266 former functionality of C-h is available on the F1 key. You should
7267 probably not turn on this mode on a text-only terminal if you don't
7268 have both Backspace, Delete and F1 keys.
7270 See also `normal-erase-is-backspace'."
7271 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
7273 (setf (terminal-parameter nil 'normal-erase-is-backspace)
7275 (let ((enabled (eq 1 (terminal-parameter
7276 nil 'normal-erase-is-backspace))))
7278 (cond ((or (memq window-system '(x w32 ns pc))
7279 (memq system-type '(ms-dos windows-nt)))
7281 `(([M-delete] [M-backspace])
7282 ([C-M-delete] [C-M-backspace])
7283 ([?\e C-delete] [?\e C-backspace]))))
7287 (define-key local-function-key-map [delete] [deletechar])
7288 (define-key local-function-key-map [kp-delete] [?\C-d])
7289 (define-key local-function-key-map [backspace] [?\C-?])
7290 (dolist (b bindings)
7291 ;; Not sure if input-decode-map is really right, but
7292 ;; keyboard-translate-table (used below) only works
7293 ;; for integer events, and key-translation-table is
7294 ;; global (like the global-map, used earlier).
7295 (define-key input-decode-map (car b) nil)
7296 (define-key input-decode-map (cadr b) nil)))
7297 (define-key local-function-key-map [delete] [?\C-?])
7298 (define-key local-function-key-map [kp-delete] [?\C-?])
7299 (define-key local-function-key-map [backspace] [?\C-?])
7300 (dolist (b bindings)
7301 (define-key input-decode-map (car b) (cadr b))
7302 (define-key input-decode-map (cadr b) (car b))))))
7306 (keyboard-translate ?\C-h ?\C-?)
7307 (keyboard-translate ?\C-? ?\C-d))
7308 (keyboard-translate ?\C-h ?\C-h)
7309 (keyboard-translate ?\C-? ?\C-?))))
7311 (if (called-interactively-p 'interactive)
7312 (message "Delete key deletes %s"
7313 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
7314 "forward" "backward")))))
7316 (defvar vis-mode-saved-buffer-invisibility-spec nil
7317 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7319 (define-minor-mode read-only-mode
7320 "Change whether the current buffer is read-only.
7321 With prefix argument ARG, make the buffer read-only if ARG is
7322 positive, otherwise make it writable. If buffer is read-only
7323 and `view-read-only' is non-nil, enter view mode.
7325 Do not call this from a Lisp program unless you really intend to
7326 do the same thing as the \\[read-only-mode] command, including
7327 possibly enabling or disabling View mode. Also, note that this
7328 command works by setting the variable `buffer-read-only', which
7329 does not affect read-only regions caused by text properties. To
7330 ignore read-only status in a Lisp program (whether due to text
7331 properties or buffer state), bind `inhibit-read-only' temporarily
7332 to a non-nil value."
7333 :variable buffer-read-only
7335 ((and (not buffer-read-only) view-mode)
7336 (View-exit-and-edit)
7337 (make-local-variable 'view-read-only)
7338 (setq view-read-only t)) ; Must leave view mode.
7339 ((and buffer-read-only view-read-only
7340 ;; If view-mode is already active, `view-mode-enter' is a nop.
7342 (not (eq (get major-mode 'mode-class) 'special)))
7343 (view-mode-enter))))
7345 (define-minor-mode visible-mode
7346 "Toggle making all invisible text temporarily visible (Visible mode).
7347 With a prefix argument ARG, enable Visible mode if ARG is
7348 positive, and disable it otherwise. If called from Lisp, enable
7349 the mode if ARG is omitted or nil.
7351 This mode works by saving the value of `buffer-invisibility-spec'
7352 and setting it to nil."
7354 :group 'editing-basics
7355 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
7356 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
7357 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
7359 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
7360 buffer-invisibility-spec)
7361 (setq buffer-invisibility-spec nil)))
7363 (defvar messages-buffer-mode-map
7364 (let ((map (make-sparse-keymap)))
7365 (set-keymap-parent map special-mode-map)
7366 (define-key map "g" nil) ; nothing to revert
7369 (define-derived-mode messages-buffer-mode special-mode "Messages"
7370 "Major mode used in the \"*Messages*\" buffer.")
7372 (defun messages-buffer ()
7373 "Return the \"*Messages*\" buffer.
7374 If it does not exist, create and it switch it to `messages-buffer-mode'."
7375 (or (get-buffer "*Messages*")
7376 (with-current-buffer (get-buffer-create "*Messages*")
7377 (messages-buffer-mode)
7381 ;; Minibuffer prompt stuff.
7383 ;;(defun minibuffer-prompt-modification (start end)
7384 ;; (error "You cannot modify the prompt"))
7387 ;;(defun minibuffer-prompt-insertion (start end)
7388 ;; (let ((inhibit-modification-hooks t))
7389 ;; (delete-region start end)
7390 ;; ;; Discard undo information for the text insertion itself
7391 ;; ;; and for the text deletion.above.
7392 ;; (when (consp buffer-undo-list)
7393 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
7394 ;; (message "You cannot modify the prompt")))
7397 ;;(setq minibuffer-prompt-properties
7398 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
7399 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
7402 ;;;; Problematic external packages.
7404 ;; rms says this should be done by specifying symbols that define
7405 ;; versions together with bad values. This is therefore not as
7406 ;; flexible as it could be. See the thread:
7407 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
7408 (defconst bad-packages-alist
7409 ;; Not sure exactly which semantic versions have problems.
7410 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
7411 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
7412 "The version of `semantic' loaded does not work in Emacs 22.
7413 It can cause constant high CPU load.
7414 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
7415 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
7416 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
7417 ;; provided the `CUA-mode' feature. Since this is no longer true,
7418 ;; we can warn the user if the `CUA-mode' feature is ever provided.
7420 "CUA-mode is now part of the standard GNU Emacs distribution,
7421 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
7423 You have loaded an older version of CUA-mode which does not work
7424 correctly with this version of Emacs. You should remove the old
7425 version and use the one distributed with Emacs."))
7426 "Alist of packages known to cause problems in this version of Emacs.
7427 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
7428 PACKAGE is either a regular expression to match file names, or a
7429 symbol (a feature name), like for `with-eval-after-load'.
7430 SYMBOL is either the name of a string variable, or `t'. Upon
7431 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
7432 warning using STRING as the message.")
7434 (defun bad-package-check (package)
7435 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
7437 (let* ((list (assoc package bad-packages-alist))
7438 (symbol (nth 1 list)))
7442 (and (stringp (setq symbol (eval symbol)))
7443 (string-match-p (nth 2 list) symbol)))
7444 (display-warning package (nth 3 list) :warning)))
7447 (dolist (elem bad-packages-alist)
7448 (let ((pkg (car elem)))
7449 (with-eval-after-load pkg
7450 (bad-package-check pkg))))
7453 ;;; Generic dispatcher commands
7455 ;; Macro `define-alternatives' is used to create generic commands.
7456 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
7457 ;; that can have different alternative implementations where choosing
7458 ;; among them is exclusively a matter of user preference.
7460 ;; (define-alternatives COMMAND) creates a new interactive command
7461 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
7462 ;; Typically, the user will not need to customize this variable; packages
7463 ;; wanting to add alternative implementations should use
7465 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
7467 (defmacro define-alternatives (command &rest customizations)
7468 "Define new command `COMMAND'.
7469 The variable `COMMAND-alternatives' will contain alternative
7470 implementations of COMMAND, so that running `C-u M-x COMMAND'
7471 will allow the user to chose among them.
7472 CUSTOMIZATIONS, if non-nil, should be composed of alternating
7473 `defcustom' keywords and values to add to the declaration of
7474 `COMMAND-alternatives' (typically :group and :version)."
7475 (let* ((command-name (symbol-name command))
7476 (varalt-name (concat command-name "-alternatives"))
7477 (varalt-sym (intern varalt-name))
7478 (varimp-sym (intern (concat command-name "--implementation"))))
7481 (defcustom ,varalt-sym nil
7482 ,(format "Alist of alternative implementations for the `%s' command.
7484 Each entry must be a pair (ALTNAME . ALTFUN), where:
7485 ALTNAME - The name shown at user to describe the alternative implementation.
7486 ALTFUN - The function called to implement this alternative."
7488 :type '(alist :key-type string :value-type function)
7491 (defvar ,varimp-sym nil "Internal use only.")
7493 (defun ,command (&optional arg)
7494 ,(format "Run generic command `%s'.
7495 If used for the first time, or with interactive ARG, ask the user which
7496 implementation to use for `%s'. The variable `%s'
7497 contains the list of implementations currently supported for this command."
7498 command-name command-name varalt-name)
7500 (when (or arg (null ,varimp-sym))
7501 (let ((val (completing-read
7502 ,(format "Select implementation for command `%s': " command-name)
7503 ,varalt-sym nil t)))
7504 (unless (string-equal val "")
7505 (customize-save-variable ',varimp-sym
7506 (cdr (assoc-string val ,varalt-sym))))))
7508 (funcall ,varimp-sym)
7509 (message ,(format "No implementation selected for command `%s'"
7514 ;;; simple.el ends here